mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-05 05:18:44 +00:00
Compare commits
164
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
389b14ede0 | ||
|
|
4e0ab25106 | ||
|
|
c52db6095a | ||
|
|
1464940eeb | ||
|
|
f274e464cd | ||
|
|
c3e7736534 | ||
|
|
9b95dd5be1 | ||
|
|
77da5f4a30 | ||
|
|
43ced9b2f0 | ||
|
|
4ffad63f1b | ||
|
|
62e7ea1ef2 | ||
|
|
91492b849d | ||
|
|
d54d0abc07 | ||
|
|
3b096b38e7 | ||
|
|
9593297cf0 | ||
|
|
8ac5591189 | ||
|
|
4232fa687d | ||
|
|
bd9aea303d | ||
|
|
5abc737bf0 | ||
|
|
d4d14e3dd7 | ||
|
|
660d2b1fe7 | ||
|
|
bb44f48414 | ||
|
|
bbe7d2f1ca | ||
|
|
45e0de9960 | ||
|
|
1920482158 | ||
|
|
0437c0fed6 | ||
|
|
d08d2f52fb | ||
|
|
d1ff0912f1 | ||
|
|
e069e2732e | ||
|
|
c791e376e8 | ||
|
|
acf1eb935b | ||
|
|
87c4b1cfa8 | ||
|
|
d0fc34b199 | ||
|
|
9cee1e218d | ||
|
|
f5d55cb1a1 | ||
|
|
345a3dae28 | ||
|
|
1239178bee | ||
|
|
e5a7c73dc9 | ||
|
|
11e914db12 | ||
|
|
181ccd8d7d | ||
|
|
2800e9a81e | ||
|
|
18d2d512f0 | ||
|
|
c06552fbd4 | ||
|
|
a00a3f7c80 | ||
|
|
b9ac9b1ca8 | ||
|
|
07f1ddac04 | ||
|
|
12829e5bfb | ||
|
|
09fa46a0d9 | ||
|
|
e359529503 | ||
|
|
ac8d1b77b9 | ||
|
|
002c5ec2f1 | ||
|
|
b42f618a01 | ||
|
|
27a4215424 | ||
|
|
65167ec7da | ||
|
|
73489fc0e7 | ||
|
|
1aca8efa65 | ||
|
|
a22bf83ae8 | ||
|
|
f00a974211 | ||
|
|
ac475cc158 | ||
|
|
eacbdf23af | ||
|
|
e31a80e3c4 | ||
|
|
e3cf966c81 | ||
|
|
eeb71039d4 | ||
|
|
c5203f078d | ||
|
|
e29c52d7e5 | ||
|
|
06ac26a213 | ||
|
|
fae845a986 | ||
|
|
b671bb0faa | ||
|
|
93462cfd2c | ||
|
|
54357e4fec | ||
|
|
d8760253ff | ||
|
|
dc281cee25 | ||
|
|
a8ed98e414 | ||
|
|
f1a8c5ac92 | ||
|
|
079c0c7f26 | ||
|
|
bced461c4f | ||
|
|
9d6e127822 | ||
|
|
dff7971cd7 | ||
|
|
3df718c1a6 | ||
|
|
3e52e265ce | ||
|
|
abf48eb86f | ||
|
|
56ad833ab7 | ||
|
|
8afd986790 | ||
|
|
918afbd33e | ||
|
|
b5cb8fadf0 | ||
|
|
1a16bdeac8 | ||
|
|
5e749eb50b | ||
|
|
836e7733da | ||
|
|
8b19c3424c | ||
|
|
7eaf67fb6a | ||
|
|
753d7db65f | ||
|
|
f0fe5ff017 | ||
|
|
225d7a8c2d | ||
|
|
46ad19d2e3 | ||
|
|
2603b6ea03 | ||
|
|
f7156b9490 | ||
|
|
f1f8e8438a | ||
|
|
6bd1e6b8fb | ||
|
|
ae21996947 | ||
|
|
8479c4c874 | ||
|
|
4c8fc93fec | ||
|
|
38bb8d3505 | ||
|
|
850542dd25 | ||
|
|
aaad020b0b | ||
|
|
ba320a08e3 | ||
|
|
42fd32731a | ||
|
|
8fa434272e | ||
|
|
fd2e552cfb | ||
|
|
13bf0686ef | ||
|
|
1a9e306c78 | ||
|
|
565335ea0d | ||
|
|
aabdffabc2 | ||
|
|
85792b8293 | ||
|
|
c4c13b6f53 | ||
|
|
d597fd56e9 | ||
|
|
94a7a59cc9 | ||
|
|
f6f93469fb | ||
|
|
120241b069 | ||
|
|
856d9cbe53 | ||
|
|
a8331d7335 | ||
|
|
dc1f9450c0 | ||
|
|
7a7ee554c7 | ||
|
|
aadb887b34 | ||
|
|
69ae4c4e96 | ||
|
|
f4ac0ab119 | ||
|
|
8d4cc05021 | ||
|
|
16d6c92722 | ||
|
|
c7047c4b33 | ||
|
|
e22bf8fe0a | ||
|
|
e994fca2b5 | ||
|
|
c599f6423e | ||
|
|
458b7211df | ||
|
|
703e3c2b68 | ||
|
|
0eb973b6db | ||
|
|
cbcc057222 | ||
|
|
d64de2bbdb | ||
|
|
1f0b52a012 | ||
|
|
908f8b242a | ||
|
|
9faea276d8 | ||
|
|
5a42d78e06 | ||
|
|
546e8aa77c | ||
|
|
ed01d40ba9 | ||
|
|
97e6f88b31 | ||
|
|
718102f743 | ||
|
|
8cc52983b7 | ||
|
|
b896923fd4 | ||
|
|
4abcbdf452 | ||
|
|
6706de0103 | ||
|
|
cc534fd19c | ||
|
|
65dd5f1da8 | ||
|
|
76dbcfe700 | ||
|
|
7944979d56 | ||
|
|
7f6ab59250 | ||
|
|
746f65a979 | ||
|
|
9188251780 | ||
|
|
1e995b659d | ||
|
|
e560993b44 | ||
|
|
eec476b9ba | ||
|
|
3f96a965b9 | ||
|
|
ce63f697ed | ||
|
|
92f5b2a9dd | ||
|
|
5f103df04d | ||
|
|
7cbcbe12f0 | ||
|
|
c12fff16d3 |
No files matched your search
@@ -77,7 +77,7 @@ jobs:
|
||||
destination: "OS=16.0,name=iPhone 14"
|
||||
name: "iOS"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
|
||||
SPM:
|
||||
@@ -103,7 +103,7 @@ jobs:
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_SPM test_install_SPM
|
||||
SQLCipher3:
|
||||
@@ -123,7 +123,7 @@ jobs:
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher3Encrypted
|
||||
SQLCipher4:
|
||||
@@ -143,7 +143,7 @@ jobs:
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher4Encrypted
|
||||
CustomSQLite:
|
||||
@@ -163,7 +163,7 @@ jobs:
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBCustomSQLiteOSX
|
||||
XCFramework:
|
||||
@@ -183,7 +183,7 @@ jobs:
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_universal_xcframework
|
||||
|
||||
+100
@@ -7,6 +7,15 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
- `6.25.x` Releases - [6.25.0](#6250)
|
||||
- `6.24.x` Releases - [6.24.0](#6240) - [6.24.1](#6241) - [6.24.2](#6242)
|
||||
- `6.23.x` Releases - [6.23.0](#6230)
|
||||
- `6.22.x` Releases - [6.22.0](#6220)
|
||||
- `6.21.x` Releases - [6.21.0](#6210)
|
||||
- `6.20.x` Releases - [6.20.0](#6200) - [6.20.1](#6201) - [6.20.2](#6202)
|
||||
- `6.19.x` Releases - [6.19.0](#6190)
|
||||
- `6.18.x` Releases - [6.18.0](#6180)
|
||||
- `6.17.x` Releases - [6.17.0](#6170)
|
||||
- `6.16.x` Releases - [6.16.0](#6160)
|
||||
- `6.15.x` Releases - [6.15.0](#6150) - [6.15.1](#6151)
|
||||
- `6.14.x` Releases - [6.14.0](#6140)
|
||||
@@ -114,6 +123,97 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## Next Release
|
||||
|
||||
- **New**: [#1503](https://github.com/groue/GRDB.swift/pull/1503) by [@simba909](https://github.com/simba909): Conform Database.ColumnType to Sendable
|
||||
- **New**: [#1510](https://github.com/groue/GRDB.swift/pull/1510) by [@groue](https://github.com/groue): Add Sendable conformances and unavailabilities
|
||||
- **New**: [#1511](https://github.com/groue/GRDB.swift/pull/1511) by [@groue](https://github.com/groue): Database schema dump
|
||||
- **Fixed**: [#1508](https://github.com/groue/GRDB.swift/pull/1508) by [@groue](https://github.com/groue): Fix ValueObservation mishandling of database schema modification
|
||||
|
||||
## 6.25.0
|
||||
|
||||
Released February 25, 2024
|
||||
|
||||
- **New**: [#1496](https://github.com/groue/GRDB.swift/pull/1496) by [@danielepantaleone](https://github.com/danielepantaleone): Add privacy manifest file.
|
||||
|
||||
A `PrivacyInfo.xcprivacy` resource was added to the GRDB SPM package and Xcode projects. It declares that GRDB does not collect anything.
|
||||
|
||||
## 6.24.2
|
||||
|
||||
Released January 21, 2024
|
||||
|
||||
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
|
||||
- **New**: Associations that involve views instead of tables were already supported, with an explicit `ForeignKey` in their definition. When the foreign key is missing, a clear diagnostic message is now emitted, instead of an unhelpful "no such table" runtime error.
|
||||
|
||||
## 6.24.1
|
||||
|
||||
Released January 6, 2024
|
||||
|
||||
- **New**: [#1477](https://github.com/groue/GRDB.swift/pull/1477): Remove shadow tables from database dump
|
||||
|
||||
## 6.24.0
|
||||
|
||||
Released January 6, 2024
|
||||
|
||||
- **New**: [#1466](https://github.com/groue/GRDB.swift/pull/1466) by [@barnettben](https://github.com/barnettben): Add schema name option to database introspection methods
|
||||
|
||||
## 6.23.0
|
||||
|
||||
Released December 1, 2023
|
||||
|
||||
- **New**: [#1462](https://github.com/groue/GRDB.swift/pull/1462) Temporary read-only access
|
||||
|
||||
## 6.22.0
|
||||
|
||||
Released November 26, 2023
|
||||
|
||||
- **New**: [#1452](https://github.com/groue/GRDB.swift/pull/1452) by [@groue](https://github.com/groue): SQLite 3.44.0, FILTER and ORDER BY clauses in aggregate functions
|
||||
- **New**: [#1460](https://github.com/groue/GRDB.swift/pull/1460) by [@groue](https://github.com/groue): Explicit change notifications help applications deal with undetected database changes.
|
||||
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
|
||||
|
||||
## 6.21.0
|
||||
|
||||
Released October 29, 2023
|
||||
|
||||
- **New**: [#1448](https://github.com/groue/GRDB.swift/pull/1448) by [@groue](https://github.com/groue): Add support for stable ordering and dump of views
|
||||
- **New**: [#1449](https://github.com/groue/GRDB.swift/pull/1449) by [@groue](https://github.com/groue): Backport temporary copies from GRDBSnapshotTesting
|
||||
|
||||
## 6.20.2
|
||||
|
||||
Released October 15, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.20.1...v6.20.2)
|
||||
|
||||
- **Fixed**: [#1442](https://github.com/groue/GRDB.swift/pull/1442) by [@groue](https://github.com/groue): Extend the macOS availability of JSON functions
|
||||
|
||||
## 6.20.1
|
||||
|
||||
Released October 13, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.20.0...v6.20.1)
|
||||
|
||||
- **Fixed**: Removed a debug print
|
||||
|
||||
## 6.20.0
|
||||
|
||||
Released October 13, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.19.0...v6.20.0)
|
||||
|
||||
- **New**: [#1439](https://github.com/groue/GRDB.swift/pull/1439) by [@groue](https://github.com/groue): Dump requests
|
||||
- **New**: `QueryInterfaceRequest.withStableOrder()` returns a request with well-defined order, suitable for tests.
|
||||
|
||||
## 6.19.0
|
||||
|
||||
Released October 4, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.18.0...v6.19.0)
|
||||
|
||||
- **New**: [#1429](https://github.com/groue/GRDB.swift/pull/1429) by [@JhonnyBillM](https://github.com/JhonnyBillM): Allow `DatabaseValueConvertible` types to customize their database JSON format
|
||||
- **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions
|
||||
- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method.
|
||||
- **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information.
|
||||
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling.
|
||||
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
|
||||
|
||||
## 6.18.0
|
||||
|
||||
Released September 1, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.17.0...v6.18.0)
|
||||
|
||||
- **New**: Expose the database path from `DatabaseReader`.
|
||||
|
||||
## 6.17.0
|
||||
|
||||
Released August 26, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.16.0...v6.17.0)
|
||||
|
||||
+2
-2
@@ -61,7 +61,7 @@ How you can Contribute
|
||||
- Get familiar with the [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/).
|
||||
- Spaces, not tabs.
|
||||
- Whitespace-only lines are not trimmed.
|
||||
- Documentation comments are hard-wrapped at column 80 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 80).
|
||||
- Documentation comments are hard-wrapped at column 76 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 76).
|
||||
- No Swiftlint warning after a build.
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ How you can Contribute
|
||||
|
||||
GRDB documentation is provided as a DocC reference, and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
|
||||
|
||||
Please keep the reference and the guides up-to-date. Use Xcode > Product > Build Documentation in order to control the quality of your reference documentation.
|
||||
Please keep the reference and the guides up-to-date. To control the quality of your DocC reference documentation, close the workspace, open `Package.swift` in Xcode, and use Product > Build Documentation.
|
||||
|
||||
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed.
|
||||
|
||||
|
||||
@@ -362,7 +362,9 @@ And we can fetch the data that feeds our application screen:
|
||||
|
||||
```swift
|
||||
|
||||
let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
|
||||
let chatInfos: [ChatInfos] = try dbQueue.read { db in
|
||||
try request.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, anonymous `CommonTableExpression` CTEs can work against type safety. When you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your common table expressions with an explicit type: `CommonTableExpression<SomeType>`.
|
||||
|
||||
@@ -3,7 +3,7 @@ Custom SQLite Builds
|
||||
|
||||
By default, GRDB uses the version of SQLite that ships with the target operating system.
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.42.0](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.44.0](https://www.sqlite.org/changes.html).**
|
||||
|
||||
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<key>NSExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>WKAppBundleIdentifier</key>
|
||||
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
|
||||
<string>com.github.groue.GRDBDemoiOS2.watchkitapp</string>
|
||||
</dict>
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
<string>com.apple.watchkit</string>
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
<string>UIInterfaceOrientationPortraitUpsideDown</string>
|
||||
</array>
|
||||
<key>WKCompanionAppBundleIdentifier</key>
|
||||
<string>com.github.groue.GRDBDemoiOS</string>
|
||||
<string>com.github.groue.GRDBDemoiOS2</string>
|
||||
<key>WKWatchKitApp</key>
|
||||
<true/>
|
||||
</dict>
|
||||
|
||||
@@ -640,7 +640,7 @@
|
||||
"@executable_path/Frameworks",
|
||||
"@executable_path/../../Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
|
||||
PRODUCT_NAME = "${TARGET_NAME}";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -660,7 +660,7 @@
|
||||
"@executable_path/Frameworks",
|
||||
"@executable_path/../../Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
|
||||
PRODUCT_NAME = "${TARGET_NAME}";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -677,7 +677,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
IBSC_MODULE = GRDBDemoWatchOS_Extension;
|
||||
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -694,7 +694,7 @@
|
||||
DEVELOPMENT_TEAM = AMD8W895CT;
|
||||
IBSC_MODULE = GRDBDemoWatchOS_Extension;
|
||||
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -832,7 +832,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -849,7 +849,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Release;
|
||||
|
||||
@@ -397,7 +397,9 @@ let publisher = observation
|
||||
|
||||
// NEW: GRDB 5
|
||||
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let (sql, arguments) = try dbQueue.read(query.build)
|
||||
let (sql, arguments) = try dbQueue.read { db in
|
||||
try query.build(db)
|
||||
}
|
||||
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
```
|
||||
|
||||
@@ -6,7 +6,7 @@ Release Process
|
||||
To release a new GRDB version:
|
||||
|
||||
- Tests
|
||||
- `make test`
|
||||
- `make distclean test`
|
||||
- Build and run GRDBDemoiOS in Release configuration on a device
|
||||
- Archive GRDBDemoiOS
|
||||
- Check for performance regression with GRDBOSXPerformanceTests
|
||||
|
||||
@@ -112,13 +112,15 @@ let components: [SQL] = [
|
||||
let query = components.joined(separator: " ")
|
||||
```
|
||||
|
||||
Extract the plain SQL string from a literal:
|
||||
To extract the plain SQL string from a literal, you need a `Database` connection such as the one provided by the `read` and `write` methods:
|
||||
|
||||
```swift
|
||||
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let (sql, arguments) = try dbQueue.read(query.build)
|
||||
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
try dbQueue.read { db in
|
||||
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
let (sql, arguments) = try query.build(db)
|
||||
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
}
|
||||
```
|
||||
|
||||
Build a literal from a plain SQL string:
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.17.0'
|
||||
s.version = '6.25.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -13,6 +13,10 @@
|
||||
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56012B742574048B00B4925B /* CommonTableExpression.swift */; };
|
||||
560233C42724234F00529DF3 /* SharedValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C32724234F00529DF3 /* SharedValueObservation.swift */; };
|
||||
560233C92724338800529DF3 /* SharedValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560233C82724338800529DF3 /* SharedValueObservationTests.swift */; };
|
||||
5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */; };
|
||||
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */; };
|
||||
5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEB82AC862EC00CF097D /* JSONColumn.swift */; };
|
||||
5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */; };
|
||||
560432A0228F00C2009D3FE2 /* OrderedDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */; };
|
||||
560432A3228F1668009D3FE2 /* AssociationPrefetchingObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */; };
|
||||
5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */; };
|
||||
@@ -54,6 +58,9 @@
|
||||
561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; };
|
||||
561CFA982376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
|
||||
561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */; };
|
||||
561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */; };
|
||||
561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */; };
|
||||
561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */; };
|
||||
562205F11E420E47005860AC /* DatabasePoolReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363CF1C943D13000BE133 /* DatabasePoolReleaseMemoryTests.swift */; };
|
||||
562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569531281C908A5B00CF1A2B /* DatabasePoolSchemaCacheTests.swift */; };
|
||||
562205F31E420E47005860AC /* DatabaseQueueReleaseMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */; };
|
||||
@@ -68,6 +75,8 @@
|
||||
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623935F1DEE06D300A6B01F /* CursorTests.swift */; };
|
||||
562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */; };
|
||||
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
|
||||
5623B6142AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */; };
|
||||
5623B6152AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */; };
|
||||
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
@@ -116,6 +125,7 @@
|
||||
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */; };
|
||||
56419C7824A51A38004967E1 /* Recorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5E24A51601004967E1 /* Recorder.swift */; };
|
||||
56419C7924A51A38004967E1 /* RecordingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419A5F24A51601004967E1 /* RecordingError.swift */; };
|
||||
5642A3182AD66DFE0065F717 /* LineDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */; };
|
||||
564448831EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */; };
|
||||
564CE43121AA901800652B19 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */; };
|
||||
564CE4E921B2E06F00652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */; };
|
||||
@@ -147,6 +157,7 @@
|
||||
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; };
|
||||
5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EB0220944C7C00F46237 /* HasOneAssociation.swift */; };
|
||||
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EC0B2098738B00F46237 /* SQLGenerationContext.swift */; };
|
||||
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */; };
|
||||
5656A7FF22946B34001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A7F822946B33001FF3FF /* ValueObservationQueryInterfaceRequestTests.swift */; };
|
||||
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A81D2295B12F001FF3FF /* SQLAssociation.swift */; };
|
||||
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A92295BFD5001FF3FF /* TableRecord+Association.swift */; };
|
||||
@@ -195,12 +206,21 @@
|
||||
5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5676FB9F22F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift */; };
|
||||
56781B0B243F86E600650A83 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56781B0A243F86E600650A83 /* Refinable.swift */; };
|
||||
5679533327E0A2FB004D18BD /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5679533227E0A2FB004D18BD /* ValueWriteOnlyObserver.swift */; };
|
||||
567B5BE72AD3284100629622 /* DatabaseReader+dump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */; };
|
||||
567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE12AD3284100629622 /* DumpFormat.swift */; };
|
||||
567B5BE92AD3284100629622 /* QuoteDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */; };
|
||||
567B5BEA2AD3284100629622 /* JSONDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE42AD3284100629622 /* JSONDumpFormat.swift */; };
|
||||
567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE52AD3284100629622 /* DebugDumpFormat.swift */; };
|
||||
567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BE62AD3284100629622 /* Database+Dump.swift */; };
|
||||
567B5C532AD32FF100629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */; };
|
||||
567B5C542AD32FF100629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */; };
|
||||
567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
|
||||
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
|
||||
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
|
||||
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; };
|
||||
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; };
|
||||
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */; };
|
||||
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
|
||||
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
|
||||
568C3F7A2A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F792A5AB2C300A2309D /* ForeignKeyDefinitionTests.swift */; };
|
||||
@@ -418,6 +438,10 @@
|
||||
56012B742574048B00B4925B /* CommonTableExpression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommonTableExpression.swift; sourceTree = "<group>"; };
|
||||
560233C32724234F00529DF3 /* SharedValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservation.swift; sourceTree = "<group>"; };
|
||||
560233C82724338800529DF3 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = "<group>"; };
|
||||
5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONFunctions.swift; sourceTree = "<group>"; };
|
||||
5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLJSONExpressible.swift; sourceTree = "<group>"; };
|
||||
5603CEB82AC862EC00CF097D /* JSONColumn.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumn.swift; sourceTree = "<group>"; };
|
||||
5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONExpressionsTests.swift; sourceTree = "<group>"; };
|
||||
56043299228F00C2009D3FE2 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
|
||||
560432A2228F1667009D3FE2 /* AssociationPrefetchingObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingObservationTests.swift; sourceTree = "<group>"; };
|
||||
5604484825DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
|
||||
@@ -458,6 +482,9 @@
|
||||
561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = "<group>"; };
|
||||
561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
|
||||
561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
|
||||
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
|
||||
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
|
||||
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
|
||||
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
|
||||
@@ -465,6 +492,8 @@
|
||||
5623935F1DEE06D300A6B01F /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = "<group>"; };
|
||||
562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FlattenCursorTests.swift; sourceTree = "<group>"; };
|
||||
562393711DEE104400A6B01F /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = "<group>"; };
|
||||
5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryCopyTests.swift; sourceTree = "<group>"; };
|
||||
5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTemporaryCopyTests.swift; sourceTree = "<group>"; };
|
||||
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
|
||||
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
|
||||
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
|
||||
@@ -525,6 +554,7 @@
|
||||
56419A6C24A51601004967E1 /* Support.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Support.swift; sourceTree = "<group>"; };
|
||||
56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = "<group>"; };
|
||||
56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = "<group>"; };
|
||||
5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LineDumpFormat.swift; sourceTree = "<group>"; };
|
||||
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
|
||||
@@ -623,12 +653,21 @@
|
||||
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>"; };
|
||||
567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = "<group>"; };
|
||||
567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = "<group>"; };
|
||||
567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "DatabaseReader+dump.swift"; sourceTree = "<group>"; };
|
||||
567B5BE12AD3284100629622 /* DumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DumpFormat.swift; sourceTree = "<group>"; };
|
||||
567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QuoteDumpFormat.swift; sourceTree = "<group>"; };
|
||||
567B5BE42AD3284100629622 /* JSONDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONDumpFormat.swift; sourceTree = "<group>"; };
|
||||
567B5BE52AD3284100629622 /* DebugDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DebugDumpFormat.swift; sourceTree = "<group>"; };
|
||||
567B5BE62AD3284100629622 /* Database+Dump.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Database+Dump.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>"; };
|
||||
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
|
||||
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = "<group>"; };
|
||||
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = "<group>"; };
|
||||
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
|
||||
56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
|
||||
56894F94260657D600268F4D /* Decimal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = "<group>"; };
|
||||
@@ -814,6 +853,7 @@
|
||||
56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = "<group>"; };
|
||||
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
|
||||
6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = "<group>"; };
|
||||
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
|
||||
C96C0F242084A442006B2981 /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = "<group>"; };
|
||||
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = "<group>"; };
|
||||
@@ -842,6 +882,25 @@
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
5603CEB52AC862EC00CF097D /* JSON */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5603CEB82AC862EC00CF097D /* JSONColumn.swift */,
|
||||
5603CEB72AC862EC00CF097D /* SQLJSONExpressible.swift */,
|
||||
5603CEB62AC862EC00CF097D /* SQLJSONFunctions.swift */,
|
||||
);
|
||||
path = JSON;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5603CEC82AC8630300CF097D /* JSON */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */,
|
||||
5603CEC92AC8631600CF097D /* JSONExpressionsTests.swift */,
|
||||
);
|
||||
name = JSON;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5605F1471C672E4000235C62 /* Support */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -921,6 +980,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
D263F40926C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift */,
|
||||
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */,
|
||||
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
|
||||
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
|
||||
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */,
|
||||
@@ -948,12 +1008,14 @@
|
||||
56176C581EACC2D8000F3F2B /* GRDBTests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56677C14241D14450050755D /* FailureTestCase.swift */,
|
||||
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
|
||||
562EA81E1F17B26F00FA528C /* Compilation */,
|
||||
56A238111B9C74A90082EB20 /* Core */,
|
||||
56677C14241D14450050755D /* FailureTestCase.swift */,
|
||||
567B5BDA2AD3281B00629622 /* Dump */,
|
||||
5698AC3E1DA2BEBB0056AF8C /* FTS */,
|
||||
56176CA01EACEE2A000F3F2B /* GRDBCipher */,
|
||||
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */,
|
||||
5603CEC82AC8630300CF097D /* JSON */,
|
||||
56A238231B9C74A90082EB20 /* Migrations */,
|
||||
569978D31B539038005EBEED /* Private */,
|
||||
56300B5C1C53C38F005A543B /* QueryInterface */,
|
||||
@@ -1069,8 +1131,10 @@
|
||||
5687359E1CEDE16C009B9116 /* Betty.jpeg */,
|
||||
5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */,
|
||||
563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */,
|
||||
5623B6122AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift */,
|
||||
56A238141B9C74A90082EB20 /* DatabaseQueueInMemoryTests.swift */,
|
||||
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */,
|
||||
5623B6132AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift */,
|
||||
569178451CED9B6000E179EA /* DatabaseQueueTests.swift */,
|
||||
);
|
||||
name = DatabaseQueue;
|
||||
@@ -1278,6 +1342,7 @@
|
||||
5674A7251F30A8EF0095F066 /* FetchableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */,
|
||||
5665FA132129C9D6004D8612 /* DatabaseDateDecodingStrategyTests.swift */,
|
||||
5674A7261F30A9090095F066 /* FetchableRecordDecodableTests.swift */,
|
||||
565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */,
|
||||
@@ -1285,6 +1350,38 @@
|
||||
name = FetchableRecord;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567B5BDA2AD3281B00629622 /* Dump */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567B5BDC2AD3283500629622 /* DatabaseDumpTests.swift */,
|
||||
567B5BDB2AD3283500629622 /* DatabaseReaderDumpTests.swift */,
|
||||
);
|
||||
name = Dump;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567B5BDF2AD3284100629622 /* Dump */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567B5BE62AD3284100629622 /* Database+Dump.swift */,
|
||||
567B5BE02AD3284100629622 /* DatabaseReader+dump.swift */,
|
||||
567B5BE12AD3284100629622 /* DumpFormat.swift */,
|
||||
567B5BE22AD3284100629622 /* DumpFormats */,
|
||||
);
|
||||
path = Dump;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
567B5BE22AD3284100629622 /* DumpFormats */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567B5BE32AD3284100629622 /* QuoteDumpFormat.swift */,
|
||||
567B5BE42AD3284100629622 /* JSONDumpFormat.swift */,
|
||||
5642A3172AD66DFE0065F717 /* LineDumpFormat.swift */,
|
||||
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */,
|
||||
567B5BE52AD3284100629622 /* DebugDumpFormat.swift */,
|
||||
);
|
||||
path = DumpFormats;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
569530FA1C9067CC00CF1A2B /* Crash */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -1642,8 +1739,11 @@
|
||||
children = (
|
||||
56A2FA3524424D2A00E97D23 /* Export.swift */,
|
||||
566DDE0C288D763C0000DCFB /* Fixits.swift */,
|
||||
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */,
|
||||
56A2386F1B9C75030082EB20 /* Core */,
|
||||
567B5BDF2AD3284100629622 /* Dump */,
|
||||
5698AC291D9E5A480056AF8C /* FTS */,
|
||||
5603CEB52AC862EC00CF097D /* JSON */,
|
||||
56A238911B9C750B0082EB20 /* Migration */,
|
||||
56300B6D1C53F592005A543B /* QueryInterface */,
|
||||
56A2389F1B9C753B0082EB20 /* Record */,
|
||||
@@ -1776,6 +1876,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -1828,6 +1929,7 @@
|
||||
56DA7CF7260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */,
|
||||
56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */,
|
||||
562393691DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
|
||||
567B5C532AD32FF100629622 /* DatabaseDumpTests.swift in Sources */,
|
||||
562205F21E420E47005860AC /* DatabasePoolSchemaCacheTests.swift in Sources */,
|
||||
56D496B01D813385008276D7 /* DatabaseErrorTests.swift in Sources */,
|
||||
56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */,
|
||||
@@ -1839,6 +1941,7 @@
|
||||
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */,
|
||||
560714E3227DD0810091BB10 /* AssociationPrefetchingSQLTests.swift in Sources */,
|
||||
56D496841D813147008276D7 /* SelectStatementTests.swift in Sources */,
|
||||
561F38D82AC88A550051EEE9 /* JSONColumnTests.swift in Sources */,
|
||||
56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */,
|
||||
56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
|
||||
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */,
|
||||
@@ -1853,6 +1956,7 @@
|
||||
56D496BF1D8135D4008276D7 /* TableDefinitionTests.swift in Sources */,
|
||||
5674A7171F3087710095F066 /* DatabaseValueConvertibleDecodableTests.swift in Sources */,
|
||||
56D496801D813131008276D7 /* StatementColumnConvertibleFetchTests.swift in Sources */,
|
||||
5603CED42AC8642F00CF097D /* JSONExpressionsTests.swift in Sources */,
|
||||
563B0705218627F800B38F35 /* ValueObservationRowTests.swift in Sources */,
|
||||
56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
|
||||
56D496891D81316E008276D7 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
|
||||
@@ -1912,6 +2016,7 @@
|
||||
56419C6B24A519A2004967E1 /* Support.swift in Sources */,
|
||||
56D496871D81316E008276D7 /* DatabaseTimestampTests.swift in Sources */,
|
||||
5615B26A222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift in Sources */,
|
||||
5623B6152AED39A600436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */,
|
||||
561CFA9C2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */,
|
||||
56176C5A1EACCCC7000F3F2B /* FTS5PatternTests.swift in Sources */,
|
||||
56D496581D81304E008276D7 /* FoundationDateTests.swift in Sources */,
|
||||
@@ -1930,6 +2035,7 @@
|
||||
56D496B81D813465008276D7 /* DataMemoryTests.swift in Sources */,
|
||||
563B06CA2185D2E500B38F35 /* ValueObservationFetchTests.swift in Sources */,
|
||||
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */,
|
||||
561F38F42AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift in Sources */,
|
||||
56D496961D81317B008276D7 /* PersistableRecordTests.swift in Sources */,
|
||||
5616B4FB28B5F5220052017E /* SingletonRecordTest.swift in Sources */,
|
||||
56419C5724A51998004967E1 /* Inverted.swift in Sources */,
|
||||
@@ -1940,6 +2046,7 @@
|
||||
56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
|
||||
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */,
|
||||
56419C5124A51998004967E1 /* Finished.swift in Sources */,
|
||||
561F38EF2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift in Sources */,
|
||||
56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
|
||||
564D4F7E261C6DC200F55856 /* CaseInsensitiveIdentifierTests.swift in Sources */,
|
||||
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */,
|
||||
@@ -1956,6 +2063,7 @@
|
||||
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */,
|
||||
5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
|
||||
56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */,
|
||||
567B5C542AD32FF100629622 /* DatabaseReaderDumpTests.swift in Sources */,
|
||||
56915782231BF28B00E1D237 /* PoolTests.swift in Sources */,
|
||||
56419C6C24A519A2004967E1 /* DatabaseRegionObservationPublisherTests.swift in Sources */,
|
||||
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
|
||||
@@ -1983,6 +2091,7 @@
|
||||
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
|
||||
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
5623B6142AED39A600436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */,
|
||||
56AFEF372996B9DC00CA1E51 /* TransactionDateTests.swift in Sources */,
|
||||
564F9C1E1F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
|
||||
@@ -2049,6 +2158,7 @@
|
||||
files = (
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */,
|
||||
56158780288D875E00A67323 /* Optional.swift in Sources */,
|
||||
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
@@ -2097,6 +2207,7 @@
|
||||
563B8FB524A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
564F9C2D1F075DD200877A00 /* DatabaseFunction.swift in Sources */,
|
||||
564CE5AC21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
567B5BE72AD3284100629622 /* DatabaseReader+dump.swift in Sources */,
|
||||
5659F4981EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */,
|
||||
5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
|
||||
@@ -2125,6 +2236,7 @@
|
||||
56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
56D110C928AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */,
|
||||
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
567B5BEA2AD3284100629622 /* JSONDumpFormat.swift in Sources */,
|
||||
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */,
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */,
|
||||
56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
@@ -2133,6 +2245,7 @@
|
||||
56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */,
|
||||
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
56A238A41B9C753B0082EB20 /* Record.swift in Sources */,
|
||||
567B5BE92AD3284100629622 /* QuoteDumpFormat.swift in Sources */,
|
||||
56CEB5451EAA359A00BFAF62 /* Column.swift in Sources */,
|
||||
5657AB0F1D10899D006283EF /* URL.swift in Sources */,
|
||||
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */,
|
||||
@@ -2151,8 +2264,10 @@
|
||||
56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
|
||||
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
|
||||
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */,
|
||||
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
|
||||
56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
|
||||
5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */,
|
||||
56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */,
|
||||
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
5695311F1C907A8C00CF1A2B /* DatabaseSchemaCache.swift in Sources */,
|
||||
@@ -2181,9 +2296,12 @@
|
||||
56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
|
||||
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
5603CEBC2AC862EC00CF097D /* JSONColumn.swift in Sources */,
|
||||
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
|
||||
5642A3182AD66DFE0065F717 /* LineDumpFormat.swift in Sources */,
|
||||
5605F1671C672E4000235C62 /* NSNumber.swift in Sources */,
|
||||
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */,
|
||||
5603CEBA2AC862EC00CF097D /* SQLJSONFunctions.swift in Sources */,
|
||||
56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
|
||||
563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */,
|
||||
C96C0F2B2084A442006B2981 /* SQLiteDateParser.swift in Sources */,
|
||||
@@ -2198,7 +2316,9 @@
|
||||
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
|
||||
5657AAB91D107001006283EF /* NSData.swift in Sources */,
|
||||
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
|
||||
567B5BEC2AD3284100629622 /* Database+Dump.swift in Sources */,
|
||||
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
|
||||
567B5BEB2AD3284100629622 /* DebugDumpFormat.swift in Sources */,
|
||||
56B9649D1DA51B4C0002DA19 /* FTS5.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
|
||||
@@ -294,7 +294,7 @@ public struct Configuration {
|
||||
/// connection is opened.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
|
||||
public enum JournalModeConfiguration {
|
||||
public enum JournalModeConfiguration: Sendable {
|
||||
/// The default setup has ``DatabaseQueue`` perform no specific
|
||||
/// configuration of the journal mode, and ``DatabasePool``
|
||||
/// configure the database for the WAL mode (just like the
|
||||
|
||||
@@ -733,6 +733,11 @@ public final class AnyCursor<Element>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: a type-erased cursor can't be more
|
||||
// sendable than non-sendable cursors (such as `DatabaseCursor`).
|
||||
@available(*, unavailable)
|
||||
extension AnyCursor: Sendable { }
|
||||
|
||||
/// A `Cursor` that consumes and drops n elements from an underlying `Base`
|
||||
/// cursor before possibly returning the first available element.
|
||||
public final class DropFirstCursor<Base: Cursor> {
|
||||
@@ -747,6 +752,11 @@ public final class DropFirstCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `DropFirstCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension DropFirstCursor: Sendable { }
|
||||
|
||||
extension DropFirstCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
while dropped < limit {
|
||||
@@ -773,6 +783,11 @@ public final class DropWhileCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `DropWhileCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension DropWhileCursor: Sendable { }
|
||||
|
||||
extension DropWhileCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if predicateHasFailed {
|
||||
@@ -818,6 +833,11 @@ public final class EnumeratedCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension EnumeratedCursor: Sendable { }
|
||||
|
||||
extension EnumeratedCursor: Cursor {
|
||||
public func next() throws -> (Int, Base.Element)? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
@@ -875,6 +895,11 @@ public final class FlattenCursor<Base: Cursor> where Base.Element: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `EnumeratedCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FlattenCursor: Sendable { }
|
||||
|
||||
extension FlattenCursor: Cursor {
|
||||
public func next() throws -> Base.Element.Element? {
|
||||
while true {
|
||||
@@ -901,6 +926,11 @@ public final class MapCursor<Base: Cursor, Element> {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: There is no known reason for making
|
||||
// it thread-safe (`transform` a Sendable closure).
|
||||
@available(*, unavailable)
|
||||
extension MapCursor: Sendable { }
|
||||
|
||||
extension MapCursor: Cursor {
|
||||
public func next() throws -> Element? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
@@ -927,6 +957,11 @@ public final class PrefixCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension PrefixCursor: Sendable { }
|
||||
|
||||
extension PrefixCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if taken >= maxLength { return nil }
|
||||
@@ -954,6 +989,11 @@ public final class PrefixWhileCursor<Base: Cursor> {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `PrefixCursor` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension PrefixWhileCursor: Sendable { }
|
||||
|
||||
extension PrefixWhileCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if !predicateHasFailed, let nextElement = try base.next() {
|
||||
|
||||
+194
-44
@@ -57,6 +57,14 @@ extension Database {
|
||||
case let .attached(name): return "\(name).sqlite_master"
|
||||
}
|
||||
}
|
||||
|
||||
/// The name of the master sqlite table, without the schema name.
|
||||
var unqualifiedMasterTableName: String { // swiftlint:disable:this inclusive_language
|
||||
switch self {
|
||||
case .main, .attached: return "sqlite_master"
|
||||
case .temp: return "sqlite_temp_master"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier of a database table or view.
|
||||
@@ -146,6 +154,19 @@ extension Database {
|
||||
return schemaIdentifiers
|
||||
}
|
||||
|
||||
/// The `SchemaIdentifier` named `schemaName` if it exists.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if no such schema exists.
|
||||
private func schemaIdentifier(named schemaName: String) throws -> SchemaIdentifier {
|
||||
let allIdentifiers = try schemaIdentifiers()
|
||||
if let result = allIdentifiers.first(where: { $0.sql.lowercased() == schemaName.lowercased() }) {
|
||||
return result
|
||||
} else {
|
||||
throw DatabaseError.noSuchSchema(schemaName)
|
||||
}
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Returns information about a table or a view
|
||||
func table(_ tableName: String) throws -> TableInfo? {
|
||||
@@ -202,10 +223,19 @@ extension Database {
|
||||
return tableInfo
|
||||
}
|
||||
|
||||
/// Returns whether a table exists, in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func tableExists(_ name: String) throws -> Bool {
|
||||
try schemaIdentifiers().contains {
|
||||
/// Returns whether a table exists
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if the specified schema does not exist
|
||||
public func tableExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
|
||||
if let schemaName {
|
||||
return try exists(type: .table, name: name, in: schemaName)
|
||||
}
|
||||
|
||||
return try schemaIdentifiers().contains {
|
||||
try exists(type: .table, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
@@ -238,20 +268,57 @@ extension Database {
|
||||
|
||||
/// Returns whether a view exists, in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func viewExists(_ name: String) throws -> Bool {
|
||||
try schemaIdentifiers().contains {
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if the specified schema does not exist
|
||||
public func viewExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
|
||||
if let schemaName {
|
||||
return try exists(type: .view, name: name, in: schemaName)
|
||||
}
|
||||
|
||||
return try schemaIdentifiers().contains {
|
||||
try exists(type: .view, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether a trigger exists, in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func triggerExists(_ name: String) throws -> Bool {
|
||||
try schemaIdentifiers().contains {
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if the specified schema does not exist
|
||||
public func triggerExists(_ name: String, in schemaName: String? = nil) throws -> Bool {
|
||||
if let schemaName {
|
||||
return try exists(type: .trigger, name: name, in: schemaName)
|
||||
}
|
||||
|
||||
return try schemaIdentifiers().contains {
|
||||
try exists(type: .trigger, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if an entity exists in a given schema
|
||||
///
|
||||
/// This is checking for the existence of the entity specified by
|
||||
/// `type` and `name`. It is assumed that the existence of a schema
|
||||
/// named `schemaName` is already known and will throw an error if it
|
||||
/// cannot be found.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if the specified schema does not exist
|
||||
private func exists(type: SchemaObjectType, name: String, in schemaName: String) throws -> Bool {
|
||||
if let schemaID = try schemaIdentifiers().first(where: { $0.sql.lowercased() == schemaName.lowercased() }) {
|
||||
return try exists(type: type, name: name, in: schemaID)
|
||||
} else {
|
||||
throw DatabaseError.noSuchSchema(schemaName)
|
||||
}
|
||||
}
|
||||
|
||||
private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool {
|
||||
// SQLite identifiers are case-insensitive, case-preserving:
|
||||
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
|
||||
@@ -264,10 +331,17 @@ extension Database {
|
||||
/// table has no explicit primary key, the result is the hidden
|
||||
/// "rowid" column.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist, or if no such table exists in
|
||||
/// the main or temp schema, or in an attached database.
|
||||
public func primaryKey(_ tableName: String, in schemaName: String? = nil) throws -> PrimaryKeyInfo {
|
||||
if let schemaName {
|
||||
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: primaryKey(_:))
|
||||
}
|
||||
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
@@ -426,10 +500,18 @@ extension Database {
|
||||
/// the columns contain the primary key or a unique index, use
|
||||
/// ``table(_:hasUniqueKey:)``.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func indexes(on tableName: String) throws -> [IndexInfo] {
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist, or if no such table or view
|
||||
/// with this name exists in the main or temp schema, or in an attached
|
||||
/// database.
|
||||
public func indexes(on tableName: String, in schemaName: String? = nil) throws -> [IndexInfo] {
|
||||
if let schemaName {
|
||||
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: indexes(on:))
|
||||
}
|
||||
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
@@ -518,10 +600,18 @@ extension Database {
|
||||
|
||||
/// Returns the foreign keys defined on table named `tableName`.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist, or if no such table or view
|
||||
/// with this name exists in the main or temp schema, or in an attached
|
||||
/// database.
|
||||
public func foreignKeys(on tableName: String, in schemaName: String? = nil) throws -> [ForeignKeyInfo] {
|
||||
if let schemaName {
|
||||
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: foreignKeys(on:))
|
||||
}
|
||||
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
@@ -602,10 +692,27 @@ extension Database {
|
||||
|
||||
/// Returns a cursor over foreign key violations in the table.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func foreignKeyViolations(in tableName: String) throws -> RecordCursor<ForeignKeyViolation> {
|
||||
/// When `schemaName` is not specified, known schemas are checked in
|
||||
/// SQLite resolution order and the first matching table is used.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist, or if no such table or view
|
||||
/// with this name exists in the main or temp schema, or in an attached
|
||||
/// database.
|
||||
public func foreignKeyViolations(
|
||||
in tableName: String,
|
||||
in schemaName: String? = nil)
|
||||
throws -> RecordCursor<ForeignKeyViolation>
|
||||
{
|
||||
if let schemaName {
|
||||
let schemaID = try schemaIdentifier(named: schemaName)
|
||||
if try exists(type: .table, name: tableName, in: schemaID) {
|
||||
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaID, name: tableName))
|
||||
} else {
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
}
|
||||
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if try exists(type: .table, name: tableName, in: schemaIdentifier) {
|
||||
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName))
|
||||
@@ -634,14 +741,21 @@ extension Database {
|
||||
|
||||
/// Throws an error if there exists a foreign key violation in the table.
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are checked in
|
||||
/// SQLite resolution order and the first matching table is used.
|
||||
///
|
||||
/// On the first foreign key violation found in the table, this method
|
||||
/// throws a ``DatabaseError`` with extended code
|
||||
/// `SQLITE_CONSTRAINT_FOREIGNKEY`.
|
||||
///
|
||||
/// If you are looking for the list of foreign key violations, prefer
|
||||
/// ``foreignKeyViolations(in:)`` instead.
|
||||
public func checkForeignKeys(in tableName: String) throws {
|
||||
try checkForeignKeys(from: foreignKeyViolations(in: tableName))
|
||||
/// ``foreignKeyViolations(in:in:)`` instead.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` as described above; when a
|
||||
/// specified schema does not exist; if no such table or view with this
|
||||
/// name exists in the main or temp schema or in an attached database.
|
||||
public func checkForeignKeys(in tableName: String, in schemaName: String? = nil) throws {
|
||||
try checkForeignKeys(from: foreignKeyViolations(in: tableName, in: schemaName))
|
||||
}
|
||||
|
||||
private func checkForeignKeys(from violations: RecordCursor<ForeignKeyViolation>) throws {
|
||||
@@ -658,9 +772,17 @@ extension Database {
|
||||
/// attached database.
|
||||
func canonicalTableName(_ tableName: String) throws -> String? {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
// Regular tables
|
||||
if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) {
|
||||
return result
|
||||
}
|
||||
|
||||
// Master table (sqlite_master, sqlite_temp_master)
|
||||
// swiftlint:disable:next inclusive_language
|
||||
let masterTableName = schemaIdentifier.unqualifiedMasterTableName
|
||||
if tableName.lowercased() == masterTableName.lowercased() {
|
||||
return masterTableName
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -673,16 +795,44 @@ extension Database {
|
||||
schemaCache[schemaID].schemaInfo = schemaInfo
|
||||
return schemaInfo
|
||||
}
|
||||
|
||||
/// Attempts to perform a table introspection function on a given
|
||||
/// table and schema
|
||||
///
|
||||
/// - parameter tableName: The name of the table to examine
|
||||
/// - parameter schemaName: The name of the schema to check
|
||||
/// - parameter introspector: An introspection function taking a
|
||||
/// `TableIdentifier` as the only parameter
|
||||
private func introspect<T>(
|
||||
tableNamed tableName: String,
|
||||
inSchemaNamed schemaName: String,
|
||||
using introspector: (TableIdentifier) throws -> T?
|
||||
) throws -> T {
|
||||
let schemaIdentifier = try schemaIdentifier(named: schemaName)
|
||||
if let result = try introspector(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
} else {
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
/// Returns the columns in a table or a view.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table or view with this name exists in the main or temp schema, or
|
||||
/// in an attached database.
|
||||
public func columns(in tableName: String) throws -> [ColumnInfo] {
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist,or if no such table or view
|
||||
/// with this name exists in the main or temp schema, or in an attached
|
||||
/// database.
|
||||
public func columns(in tableName: String, in schemaName: String? = nil) throws -> [ColumnInfo] {
|
||||
if let schemaName {
|
||||
return try introspect(tableNamed: tableName, inSchemaNamed: schemaName, using: columns(in:))
|
||||
}
|
||||
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
@@ -840,14 +990,14 @@ extension Database {
|
||||
|
||||
/// Information about a column of a database table.
|
||||
///
|
||||
/// You get `ColumnInfo` instances with the ``Database/columns(in:)``
|
||||
/// You get `ColumnInfo` instances with the ``Database/columns(in:in:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
/// - [pragma `table_info`](https://www.sqlite.org/pragma.html#pragma_table_info)
|
||||
/// - [pragma `table_xinfo`](https://www.sqlite.org/pragma.html#pragma_table_xinfo)
|
||||
public struct ColumnInfo: FetchableRecord {
|
||||
public struct ColumnInfo: FetchableRecord, Sendable {
|
||||
let cid: Int
|
||||
let hidden: Int?
|
||||
|
||||
@@ -926,16 +1076,16 @@ public struct ColumnInfo: FetchableRecord {
|
||||
|
||||
/// Information about an index.
|
||||
///
|
||||
/// You get `IndexInfo` instances with the ``Database/indexes(on:)``
|
||||
/// You get `IndexInfo` instances with the ``Database/indexes(on:in:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
/// - [pragma `index_list`](https://www.sqlite.org/pragma.html#pragma_index_list)
|
||||
/// - [pragma `index_info`](https://www.sqlite.org/pragma.html#pragma_index_info)
|
||||
public struct IndexInfo {
|
||||
public struct IndexInfo: Sendable{
|
||||
/// The origin of an index.
|
||||
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible {
|
||||
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible, Sendable {
|
||||
public var rawValue: String
|
||||
|
||||
public init(rawValue: String) {
|
||||
@@ -969,7 +1119,7 @@ public struct IndexInfo {
|
||||
///
|
||||
/// You get instances of `ForeignKeyViolation` from the `Database` methods
|
||||
/// ``Database/foreignKeyViolations()`` and
|
||||
/// ``Database/foreignKeyViolations(in:)`` methods.
|
||||
/// ``Database/foreignKeyViolations(in:in:)`` methods.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -1008,7 +1158,7 @@ public struct IndexInfo {
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
|
||||
public struct ForeignKeyViolation {
|
||||
public struct ForeignKeyViolation: Sendable {
|
||||
/// The name of the table that contains the foreign key.
|
||||
public var originTable: String
|
||||
|
||||
@@ -1023,7 +1173,7 @@ public struct ForeignKeyViolation {
|
||||
/// The id of the foreign key constraint that failed.
|
||||
///
|
||||
/// This id matches the ``ForeignKeyInfo/id`` property in
|
||||
/// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:)``.
|
||||
/// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:in:)``.
|
||||
public var foreignKeyId: Int
|
||||
|
||||
/// A precise description of the foreign key violation.
|
||||
@@ -1113,7 +1263,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
|
||||
|
||||
/// Information about a primary key.
|
||||
///
|
||||
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:)``
|
||||
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:in:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// When the table's primary key is the rowid:
|
||||
@@ -1157,7 +1307,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
/// ```
|
||||
public struct PrimaryKeyInfo {
|
||||
public struct PrimaryKeyInfo: Sendable {
|
||||
private enum Impl {
|
||||
/// The hidden rowID.
|
||||
case hiddenRowID
|
||||
@@ -1279,11 +1429,11 @@ public struct PrimaryKeyInfo {
|
||||
|
||||
/// Information about a foreign key.
|
||||
///
|
||||
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:)``
|
||||
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:in:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation: [pragma `foreign_key_list`](https://www.sqlite.org/pragma.html#pragma_foreign_key_list).
|
||||
public struct ForeignKeyInfo {
|
||||
public struct ForeignKeyInfo: Sendable {
|
||||
/// The first column in the output of the `foreign_key_list` pragma.
|
||||
public var id: Int
|
||||
|
||||
@@ -1367,7 +1517,7 @@ struct SchemaObject: Hashable, FetchableRecord {
|
||||
|
||||
/// All objects in a database schema (tables, views, indexes, triggers).
|
||||
struct SchemaInfo: Equatable {
|
||||
private var objects: Set<SchemaObject>
|
||||
let objects: Set<SchemaObject>
|
||||
|
||||
/// Returns whether there exists a object of given type with this name
|
||||
/// (case-insensitive).
|
||||
|
||||
@@ -361,6 +361,11 @@ public class SQLStatementCursor {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension SQLStatementCursor: Sendable { }
|
||||
|
||||
extension SQLStatementCursor: Cursor {
|
||||
public func next() throws -> Statement? {
|
||||
guard offset < cString.count - 1 /* trailing \0 */ else {
|
||||
|
||||
+133
-12
@@ -60,16 +60,28 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``inSavepoint(_:)``
|
||||
/// - ``inTransaction(_:_:)``
|
||||
/// - ``isInsideTransaction``
|
||||
/// - ``readOnly(_:)``
|
||||
/// - ``rollback()``
|
||||
/// - ``transactionDate``
|
||||
/// - ``TransactionCompletion``
|
||||
/// - ``TransactionKind``
|
||||
///
|
||||
/// ### Printing Database Content
|
||||
///
|
||||
/// - ``dumpContent(format:to:)``
|
||||
/// - ``dumpRequest(_:format:to:)``
|
||||
/// - ``dumpSchema(to:)``
|
||||
/// - ``dumpSQL(_:format:to:)``
|
||||
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
|
||||
/// - ``DumpFormat``
|
||||
/// - ``DumpTableHeaderOptions``
|
||||
///
|
||||
/// ### Database Observation
|
||||
///
|
||||
/// - ``add(transactionObserver:extent:)``
|
||||
/// - ``remove(transactionObserver:)``
|
||||
/// - ``afterNextTransaction(onCommit:onRollback:)``
|
||||
/// - ``notifyChanges(in:)``
|
||||
/// - ``registerAccess(to:)``
|
||||
///
|
||||
/// ### Collations
|
||||
@@ -762,11 +774,38 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
/// Grants read-only access in the wrapped closure.
|
||||
func readOnly<T>(_ block: () throws -> T) throws -> T {
|
||||
/// Executes read-only database operations, and returns their result
|
||||
/// after they have finished executing.
|
||||
///
|
||||
/// Attempts to write throw a ``DatabaseError`` with
|
||||
/// resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write do { db in
|
||||
/// // Write OK
|
||||
/// try Player(...).insert(db)
|
||||
///
|
||||
/// try db.readOnly {
|
||||
/// // Read OK
|
||||
/// let players = try Player.fetchAll(db)
|
||||
///
|
||||
/// // Throws SQLITE_READONLY
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This method is reentrant.
|
||||
///
|
||||
/// - parameter value: A closure that reads from the database.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
|
||||
/// error thrown by `value`.
|
||||
public func readOnly<T>(_ value: () throws -> T) throws -> T {
|
||||
try beginReadOnly()
|
||||
return try throwingFirstError(
|
||||
execute: block,
|
||||
execute: value,
|
||||
finally: endReadOnly)
|
||||
}
|
||||
|
||||
@@ -811,6 +850,65 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
/// Notifies that some changes were performed in the provided
|
||||
/// database region.
|
||||
///
|
||||
/// This method makes it possible to notify undetected changes, such as
|
||||
/// changes performed by another process, changes performed by
|
||||
/// direct calls to SQLite C functions, or changes to the
|
||||
/// database schema.
|
||||
/// See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
|
||||
/// for a detailed list of undetected database modifications.
|
||||
///
|
||||
/// It triggers active transaction observers (``TransactionObserver``).
|
||||
/// In particular, ``ValueObservation`` that observe the input `region`
|
||||
/// will fetch and notify a fresh value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// // Notify observers that some changes were performed in the database
|
||||
/// try db.notifyChanges(in: .fullDatabase)
|
||||
///
|
||||
/// // Notify observers that some changes were performed in the player table
|
||||
/// try db.notifyChanges(in: Player.all())
|
||||
///
|
||||
/// // Equivalent alternative
|
||||
/// try db.notifyChanges(in: Table("player"))
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This method has no effect when called from a read-only
|
||||
/// database access.
|
||||
///
|
||||
/// > Caveat: Individual rowids in the input region are ignored.
|
||||
/// > Notifying a change to a specific rowid is the same as notifying a
|
||||
/// > change in the whole table:
|
||||
/// >
|
||||
/// > ```swift
|
||||
/// > try dbQueue.write { db in
|
||||
/// > // Equivalent
|
||||
/// > try db.notifyChanges(in: Player.all())
|
||||
/// > try db.notifyChanges(in: Player.filter(id: 1))
|
||||
/// > }
|
||||
/// > ```
|
||||
public func notifyChanges(in region: some DatabaseRegionConvertible) throws {
|
||||
// Don't do anything when read-only, because read-only transactions
|
||||
// are not notified. We don't want to notify transactions observers
|
||||
// of changes, and have them wait for a commit notification that
|
||||
// will never come.
|
||||
if !isReadOnly, let observationBroker {
|
||||
let eventKinds = try region
|
||||
.databaseRegion(self)
|
||||
// Use canonical table names for case insensitivity of the input.
|
||||
.canonicalTables(self)
|
||||
.impactfulEventKinds(self)
|
||||
|
||||
try observationBroker.notifyChanges(withEventsOfKind: eventKinds)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extends the `region` argument with the database region selected by all
|
||||
/// statements executed by the closure, and all regions explicitly tracked
|
||||
/// with the ``registerAccess(to:)`` method.
|
||||
@@ -1156,7 +1254,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.writeWithoutTransaction do {
|
||||
/// try dbQueue.writeWithoutTransaction do { db in
|
||||
/// try db.inTransaction {
|
||||
/// try db.execute(sql: "INSERT ...")
|
||||
/// return .commit
|
||||
@@ -1632,6 +1730,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `Database` must be used from a
|
||||
// serialized database access dispatch queue (see `SerializedDatabase`).
|
||||
@available(*, unavailable)
|
||||
extension Database: Sendable { }
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension Database {
|
||||
|
||||
@@ -1757,7 +1860,7 @@ extension Database {
|
||||
/// The available checkpoint modes.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html>
|
||||
public enum CheckpointMode: CInt {
|
||||
public enum CheckpointMode: CInt, Sendable {
|
||||
/// The `SQLITE_CHECKPOINT_PASSIVE` mode.
|
||||
case passive = 0
|
||||
|
||||
@@ -1776,7 +1879,7 @@ extension Database {
|
||||
/// Related SQLite documentation:
|
||||
/// - <https://www.sqlite.org/datatype3.html#collating_sequences>
|
||||
/// - <https://www.sqlite.org/datatype3.html#collation>
|
||||
public struct CollationName: RawRepresentable, Hashable {
|
||||
public struct CollationName: RawRepresentable, Hashable, Sendable {
|
||||
public let rawValue: String
|
||||
|
||||
/// Creates a collation name.
|
||||
@@ -1813,7 +1916,7 @@ extension Database {
|
||||
///
|
||||
/// For more information, see
|
||||
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
|
||||
public struct ColumnType: RawRepresentable, Hashable {
|
||||
public struct ColumnType: RawRepresentable, Hashable, Sendable {
|
||||
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
|
||||
public let rawValue: String
|
||||
|
||||
@@ -1826,6 +1929,14 @@ extension Database {
|
||||
/// The `TEXT` column type.
|
||||
public static let text = ColumnType(rawValue: "TEXT")
|
||||
|
||||
/// The `TEXT` column type, suitable for JSON columns.
|
||||
///
|
||||
/// SQLite JSON functions and operators are
|
||||
/// [documented](https://www.sqlite.org/json1.html#interface_overview)
|
||||
/// to throw errors if any of their arguments are binary blobs.
|
||||
/// That's the reason why it is recommended to store JSON as text.
|
||||
public static let jsonText = ColumnType(rawValue: "TEXT")
|
||||
|
||||
/// The `INTEGER` column type.
|
||||
public static let integer = ColumnType(rawValue: "INTEGER")
|
||||
|
||||
@@ -1857,7 +1968,7 @@ extension Database {
|
||||
/// An SQLite conflict resolution.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
|
||||
public enum ConflictResolution: String {
|
||||
public enum ConflictResolution: String, Sendable {
|
||||
/// The `ROLLBACK` conflict resolution.
|
||||
case rollback = "ROLLBACK"
|
||||
|
||||
@@ -1877,7 +1988,7 @@ extension Database {
|
||||
/// A foreign key action.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
|
||||
public enum ForeignKeyAction: String {
|
||||
public enum ForeignKeyAction: String, Sendable {
|
||||
/// The `CASCADE` foreign key action.
|
||||
case cascade = "CASCADE"
|
||||
|
||||
@@ -1900,7 +2011,7 @@ extension Database {
|
||||
/// ``Database/trace(options:_:)`` method.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/c_trace.html>
|
||||
public struct TracingOptions: OptionSet {
|
||||
public struct TracingOptions: OptionSet, Sendable {
|
||||
/// The raw trace event code.
|
||||
public let rawValue: CInt
|
||||
|
||||
@@ -2033,7 +2144,7 @@ extension Database {
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
|
||||
@frozen
|
||||
public enum TransactionCompletion {
|
||||
public enum TransactionCompletion: Sendable {
|
||||
case commit
|
||||
case rollback
|
||||
}
|
||||
@@ -2041,7 +2152,7 @@ extension Database {
|
||||
/// A transaction kind.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
|
||||
public enum TransactionKind: String {
|
||||
public enum TransactionKind: String, Sendable {
|
||||
/// The `DEFERRED` transaction kind.
|
||||
case deferred = "DEFERRED"
|
||||
|
||||
@@ -2074,3 +2185,13 @@ extension Database {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: a trace event contains transient
|
||||
// information.
|
||||
@available(*, unavailable)
|
||||
extension Database.TraceEvent: Sendable { }
|
||||
|
||||
// Explicit non-conformance to Sendable: a trace event contains transient
|
||||
// information.
|
||||
@available(*, unavailable)
|
||||
extension Database.TraceEvent.Statement: Sendable { }
|
||||
@@ -1,7 +1,7 @@
|
||||
/// Describe the progress of a database backup.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
public struct DatabaseBackupProgress {
|
||||
public struct DatabaseBackupProgress: Sendable {
|
||||
/// The number of pages still to be backed up.
|
||||
///
|
||||
/// It is the result of the `sqlite3_backup_remaining` function.
|
||||
|
||||
@@ -396,6 +396,10 @@ public struct DatabaseError: Error {
|
||||
static func noSuchTable(_ tableName: String) -> Self {
|
||||
DatabaseError(message: "no such table: \(tableName)")
|
||||
}
|
||||
|
||||
static func noSuchSchema(_ schemaName: String) -> Self {
|
||||
DatabaseError(message: "no such schema: \(schemaName)")
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseError {
|
||||
@@ -549,7 +553,7 @@ extension DatabaseError: CustomStringConvertible {
|
||||
description += ": \(message)"
|
||||
}
|
||||
if let sql {
|
||||
description += " - while executing `\(sql)`"
|
||||
description += " - while executing `\(sql.trimmedSQLStatement)`"
|
||||
}
|
||||
if publicStatementArguments, let arguments, !arguments.isEmpty {
|
||||
description += " with arguments \(arguments)"
|
||||
@@ -577,7 +581,7 @@ extension DatabaseError: CustomStringConvertible {
|
||||
description += ": \(message)"
|
||||
}
|
||||
if let sql {
|
||||
description += " - while executing `\(sql)`"
|
||||
description += " - while executing `\(sql.trimmedSQLStatement)`"
|
||||
}
|
||||
if let arguments, !arguments.isEmpty {
|
||||
description += " with arguments \(arguments)"
|
||||
|
||||
@@ -30,9 +30,9 @@ public final class DatabaseFunction: Hashable {
|
||||
/// The name of the SQL function
|
||||
public var name: String { identity.name }
|
||||
private let identity: Identity
|
||||
let pure: Bool
|
||||
let isPure: Bool
|
||||
private let kind: Kind
|
||||
private var eTextRep: CInt { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
private var eTextRep: CInt { (SQLITE_UTF8 | (isPure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
|
||||
/// Creates an SQL function.
|
||||
///
|
||||
@@ -76,7 +76,7 @@ public final class DatabaseFunction: Hashable {
|
||||
function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.pure = pure
|
||||
self.isPure = pure
|
||||
self.kind = .function{ (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
@@ -140,10 +140,11 @@ public final class DatabaseFunction: Hashable {
|
||||
aggregate: Aggregate.Type)
|
||||
{
|
||||
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.pure = pure
|
||||
self.isPure = pure
|
||||
self.kind = .aggregate { Aggregate() }
|
||||
}
|
||||
|
||||
// TODO: GRDB7 -> expose ORDER BY and FILTER when we have distinct types for simple functions and aggregates.
|
||||
/// Returns an SQL expression that applies the function.
|
||||
///
|
||||
/// You can use a `DatabaseFunction` as a regular Swift function. It returns
|
||||
@@ -171,13 +172,23 @@ public final class DatabaseFunction: Hashable {
|
||||
/// ```
|
||||
public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression {
|
||||
switch kind {
|
||||
case .aggregate:
|
||||
return .function(name, arguments.map(\.sqlExpression))
|
||||
case .function:
|
||||
return .aggregate(name, arguments.map(\.sqlExpression))
|
||||
return .simpleFunction(
|
||||
name,
|
||||
arguments.map(\.sqlExpression),
|
||||
isPure: isPure,
|
||||
isJSONValue: false)
|
||||
case .aggregate:
|
||||
return .aggregateFunction(
|
||||
name,
|
||||
arguments.map(\.sqlExpression),
|
||||
isDistinct: false,
|
||||
ordering: nil,
|
||||
filter: nil,
|
||||
isJSONValue: false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See <https://sqlite.org/c3ref/create_function.html>
|
||||
func install(in db: Database) {
|
||||
|
||||
@@ -16,9 +16,6 @@ public final class DatabaseQueue {
|
||||
writer.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file.
|
||||
///
|
||||
/// The path is `:memory:` for in-memory databases.
|
||||
public var path: String {
|
||||
writer.path
|
||||
}
|
||||
@@ -432,3 +429,96 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
writer.async(updates)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Temp Copy
|
||||
|
||||
extension DatabaseQueue {
|
||||
/// Returns a connection to an in-memory copy of the database at `path`.
|
||||
///
|
||||
/// Changes performed on the returned connection do not impact the
|
||||
/// original database at `path`.
|
||||
///
|
||||
/// The database memory is released when the returned connection
|
||||
/// is deallocated.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let path = "/path/to/database.sqlite"
|
||||
/// let dbQueue = try DatabaseQueue.inMemoryCopy(fromPath: path)
|
||||
/// ```
|
||||
public static func inMemoryCopy(
|
||||
fromPath path: String,
|
||||
configuration: Configuration = Configuration())
|
||||
throws -> DatabaseQueue
|
||||
{
|
||||
var sourceConfig = configuration
|
||||
sourceConfig.readonly = true
|
||||
let source = try DatabaseQueue(path: path, configuration: sourceConfig)
|
||||
|
||||
var copyConfig = configuration
|
||||
copyConfig.readonly = false
|
||||
let result = try DatabaseQueue(configuration: copyConfig)
|
||||
|
||||
try source.backup(to: result)
|
||||
|
||||
if configuration.readonly {
|
||||
// Result was not opened read-only so that we could perform the
|
||||
// copy. And SQLITE_OPEN_READONLY has no effect on in-memory
|
||||
// databases anyway.
|
||||
//
|
||||
// So let's simulate read-only with PRAGMA query_only.
|
||||
try result.inDatabase { db in
|
||||
try db.beginReadOnly()
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns a connection to a private, temporary, on-disk copy of the
|
||||
/// database at `path`.
|
||||
///
|
||||
/// Changes performed on the returned connection do not impact the
|
||||
/// original database at `path`.
|
||||
///
|
||||
/// The on-disk copy will be automatically deleted from disk as soon as
|
||||
/// the returned connection is closed or deallocated.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let path = "/path/to/database.sqlite"
|
||||
/// let dbQueue = try DatabaseQueue.temporaryCopy(fromPath: path)
|
||||
/// ```
|
||||
public static func temporaryCopy(
|
||||
fromPath path: String,
|
||||
configuration: Configuration = Configuration())
|
||||
throws -> DatabaseQueue
|
||||
{
|
||||
var sourceConfig = configuration
|
||||
sourceConfig.readonly = true
|
||||
let source = try DatabaseQueue(path: path, configuration: sourceConfig)
|
||||
|
||||
// <https://www.sqlite.org/c3ref/open.html>
|
||||
// > If the filename is an empty string, then a private, temporary
|
||||
// > on-disk database will be created. This private database will be
|
||||
// > automatically deleted as soon as the database connection
|
||||
// > is closed.
|
||||
var copyConfig = configuration
|
||||
copyConfig.readonly = false
|
||||
let result = try DatabaseQueue(path: "", configuration: copyConfig)
|
||||
|
||||
try source.backup(to: result)
|
||||
|
||||
if configuration.readonly {
|
||||
// Result was not opened read-only so that we could perform the
|
||||
// copy. So let's simulate read-only with PRAGMA query_only.
|
||||
try result.inDatabase { db in
|
||||
try db.beginReadOnly()
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import Dispatch
|
||||
/// ### Database Information
|
||||
///
|
||||
/// - ``configuration``
|
||||
/// - ``path``
|
||||
///
|
||||
/// ### Reading from the Database
|
||||
///
|
||||
@@ -32,6 +33,16 @@ import Dispatch
|
||||
/// - ``unsafeReentrantRead(_:)``
|
||||
/// - ``asyncUnsafeRead(_:)``
|
||||
///
|
||||
/// ### Printing Database Content
|
||||
///
|
||||
/// - ``dumpContent(format:to:)``
|
||||
/// - ``dumpRequest(_:format:to:)``
|
||||
/// - ``dumpSchema(to:)``
|
||||
/// - ``dumpSQL(_:format:to:)``
|
||||
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
|
||||
/// - ``DumpFormat``
|
||||
/// - ``DumpTableHeaderOptions``
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``backup(to:pagesPerStep:progress:)``
|
||||
@@ -46,6 +57,12 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// The database configuration.
|
||||
var configuration: Configuration { get }
|
||||
|
||||
/// The path to the database file.
|
||||
///
|
||||
/// In-memory databases also have a path:
|
||||
/// see [In-Memory Databases](https://www.sqlite.org/inmemorydb.html).
|
||||
var path: String { get }
|
||||
|
||||
/// Closes the database connection.
|
||||
///
|
||||
/// - note: You do not have to call this method, and you should not call
|
||||
@@ -644,6 +661,10 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
base.configuration
|
||||
}
|
||||
|
||||
public var path: String {
|
||||
base.path
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try base.close()
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
///
|
||||
/// - ``isModified(byEventsOfKind:)``
|
||||
/// - ``isModified(by:)``
|
||||
public struct DatabaseRegion {
|
||||
public struct DatabaseRegion: Sendable {
|
||||
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
|
||||
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
|
||||
@@ -169,16 +169,16 @@ public struct DatabaseRegion {
|
||||
// the observed region, we optimize database observation.
|
||||
//
|
||||
// And by canonicalizing table names, we remove views, and help the
|
||||
// `isModified` methods.
|
||||
// `isModified` methods. (TODO: is this comment still accurate?
|
||||
// Isn't it about providing TransactionObserver.observes() with
|
||||
// real tables names, instead?)
|
||||
try ignoringInternalSQLiteTables().canonicalTables(db)
|
||||
}
|
||||
|
||||
/// Returns a region only made of actual tables with their canonical names.
|
||||
/// Canonical names help the `isModified` methods.
|
||||
///
|
||||
/// This method removes views (assuming no table exists with the same name
|
||||
/// as a view).
|
||||
private func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
/// This method removes views.
|
||||
func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
guard let tableRegions else { return .fullDatabase }
|
||||
var region = DatabaseRegion()
|
||||
for (table, tableRegion) in tableRegions {
|
||||
@@ -233,6 +233,44 @@ extension DatabaseRegion {
|
||||
}
|
||||
return tableRegion.contains(rowID: event.rowID)
|
||||
}
|
||||
|
||||
/// Returns an array of all event kinds that can impact this region.
|
||||
///
|
||||
/// - precondition: the region is canonical.
|
||||
func impactfulEventKinds(_ db: Database) throws -> [DatabaseEventKind] {
|
||||
if let tableRegions {
|
||||
return try tableRegions.flatMap { (table, tableRegion) -> [DatabaseEventKind] in
|
||||
let tableName = table.rawValue // canonical table name
|
||||
let columnNames: Set<String>
|
||||
if let columns = tableRegion.columns {
|
||||
columnNames = Set(columns.map(\.rawValue))
|
||||
} else {
|
||||
columnNames = try Set(db.columns(in: tableName).map(\.name))
|
||||
}
|
||||
|
||||
return [
|
||||
DatabaseEventKind.delete(tableName: tableName),
|
||||
DatabaseEventKind.insert(tableName: tableName),
|
||||
DatabaseEventKind.update(tableName: tableName, columnNames: columnNames),
|
||||
]
|
||||
}
|
||||
} else {
|
||||
// full database
|
||||
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
|
||||
let schema = try db.schema(schemaIdentifier)
|
||||
return try schema.objects
|
||||
.filter { $0.type == .table }
|
||||
.flatMap { table in
|
||||
let columnNames = try Set(db.columns(in: table.name).map(\.name))
|
||||
return [
|
||||
DatabaseEventKind.delete(tableName: table.name),
|
||||
DatabaseEventKind.insert(tableName: table.name),
|
||||
DatabaseEventKind.update(tableName: table.name, columnNames: columnNames),
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseRegion: Equatable {
|
||||
|
||||
@@ -161,6 +161,11 @@ private class DatabaseRegionObserver: TransactionObserver {
|
||||
region.isModified(byEventsOfKind: eventKind)
|
||||
}
|
||||
|
||||
func databaseDidChange() {
|
||||
isChanged = true
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if region.isModified(by: event) {
|
||||
isChanged = true
|
||||
|
||||
@@ -59,10 +59,14 @@ import Dispatch
|
||||
/// let snapshot2 = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// // Guaranteed to be zero
|
||||
/// let count1 = try snapshot1.read(Player.fetchCount)
|
||||
/// let count1 = try snapshot1.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// // Could be anything
|
||||
/// let count2 = try snapshot2.read(Player.fetchCount)
|
||||
/// let count2 = try snapshot2.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseSnapshot` inherits its database access methods from the
|
||||
|
||||
@@ -104,7 +104,9 @@ public final class DatabaseSnapshotPool {
|
||||
///
|
||||
/// // Later... Maybe some players have been created.
|
||||
/// // The snapshot is guaranteed to see an empty table of players, though:
|
||||
/// let count = try snapshot.read(Player.fetchCount)
|
||||
/// let count = try snapshot.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// assert(count == 0)
|
||||
/// ```
|
||||
///
|
||||
|
||||
@@ -44,6 +44,7 @@ import Foundation
|
||||
/// ### Creating a DatabaseValue
|
||||
///
|
||||
/// - ``init(value:)``
|
||||
/// - ``init(sqliteStatement:index:)``
|
||||
/// - ``null``
|
||||
///
|
||||
/// ### Accessing the SQLite storage
|
||||
@@ -149,7 +150,7 @@ public struct DatabaseValue: Hashable {
|
||||
}
|
||||
|
||||
/// Creates a `DatabaseValue` initialized from a raw SQLite statement pointer.
|
||||
init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
storage = .null
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import Foundation
|
||||
|
||||
// Standard collections `Array`, `Set`, and `Dictionary` do not conform to
|
||||
// `DatabaseValueConvertible`, on purpose.
|
||||
//
|
||||
@@ -59,6 +61,18 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
|
||||
///
|
||||
/// - returns: A decoded value, or, if decoding is impossible, nil.
|
||||
static func fromMissingColumn() -> Self?
|
||||
|
||||
/// Returns the `JSONDecoder` that decodes the value.
|
||||
///
|
||||
/// This method is dedicated to ``DatabaseValueConvertible`` types that
|
||||
/// also conform to the standard `Decodable` protocol.
|
||||
static func databaseJSONDecoder() -> JSONDecoder
|
||||
|
||||
/// Returns the `JSONEncoder` that encodes the value.
|
||||
///
|
||||
/// This method is dedicated to ``DatabaseValueConvertible`` types that
|
||||
/// also conform to the standard `Encodable` protocol.
|
||||
static func databaseJSONEncoder() -> JSONEncoder
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
@@ -75,6 +89,41 @@ extension DatabaseValueConvertible {
|
||||
public static func fromMissingColumn() -> Self? {
|
||||
nil // failure.
|
||||
}
|
||||
|
||||
/// Returns the `JSONDecoder` that decodes the value.
|
||||
///
|
||||
/// The default implementation returns a `JSONDecoder` with the
|
||||
/// following properties:
|
||||
///
|
||||
/// - `dataDecodingStrategy`: `.base64`
|
||||
/// - `dateDecodingStrategy`: `.millisecondsSince1970`
|
||||
/// - `nonConformingFloatDecodingStrategy`: `.throw`
|
||||
public static func databaseJSONDecoder() -> JSONDecoder {
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dataDecodingStrategy = .base64
|
||||
decoder.dateDecodingStrategy = .millisecondsSince1970
|
||||
decoder.nonConformingFloatDecodingStrategy = .throw
|
||||
return decoder
|
||||
}
|
||||
|
||||
/// Returns the `JSONEncoder` that encodes the value.
|
||||
///
|
||||
/// The default implementation returns a `JSONEncoder` with the
|
||||
/// following properties:
|
||||
///
|
||||
/// - `dataEncodingStrategy`: `.base64`
|
||||
/// - `dateEncodingStrategy`: `.millisecondsSince1970`
|
||||
/// - `nonConformingFloatEncodingStrategy`: `.throw`
|
||||
/// - `outputFormatting`: `.sortedKeys`
|
||||
public static func databaseJSONEncoder() -> JSONEncoder {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dataEncodingStrategy = .base64
|
||||
encoder.dateEncodingStrategy = .millisecondsSince1970
|
||||
encoder.nonConformingFloatEncodingStrategy = .throw
|
||||
// guarantee some stability in order to ease value comparison
|
||||
encoder.outputFormatting = .sortedKeys
|
||||
return encoder
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
@@ -173,6 +222,11 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension DatabaseValueCursor: Sendable { }
|
||||
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
|
||||
/// cursors, arrays, or single values:
|
||||
///
|
||||
|
||||
@@ -445,10 +445,21 @@ extension DatabaseWriter {
|
||||
|
||||
// MARK: - Transaction Observers
|
||||
|
||||
/// Adds a transaction observer, so that it gets notified of
|
||||
/// database changes and transactions.
|
||||
/// Adds a transaction observer to the writer connection, so that it
|
||||
/// gets notified of database changes and transactions.
|
||||
///
|
||||
/// This method has no effect on read-only database connections.
|
||||
/// This method waits until all currently executing database accesses
|
||||
/// performed by the writer dispatch queue finish executing.
|
||||
/// At that point, database observation begins.
|
||||
///
|
||||
/// It has no effect on read-only database connections.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let myObserver = MyObserver()
|
||||
/// try dbQueue.add(transactionObserver: myObserver)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter transactionObserver: A transaction observer.
|
||||
/// - parameter extent: The duration of the observation. The default is
|
||||
@@ -461,7 +472,18 @@ extension DatabaseWriter {
|
||||
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
|
||||
}
|
||||
|
||||
/// Removes a transaction observer.
|
||||
/// Removes a transaction observer from the writer connection.
|
||||
///
|
||||
/// This method waits until all currently executing database accesses
|
||||
/// performed by the writer dispatch queue finish executing.
|
||||
/// At that point, database observation stops.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let myObserver = MyObserver()
|
||||
/// try dbQueue.remove(transactionObserver: myObserver)
|
||||
/// ```
|
||||
public func remove(transactionObserver: some TransactionObserver) {
|
||||
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
|
||||
}
|
||||
@@ -964,6 +986,10 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
base.configuration
|
||||
}
|
||||
|
||||
public var path: String {
|
||||
base.path
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try base.close()
|
||||
}
|
||||
|
||||
@@ -107,6 +107,28 @@ extension FetchRequest {
|
||||
|
||||
// MARK: - PreparedRequest
|
||||
|
||||
/// A closure executed before a supplementary fetch is performed.
|
||||
///
|
||||
/// Support for `Database.dumpRequest`.
|
||||
///
|
||||
/// - parameter request: The supplementary request
|
||||
/// - parameter keyPath: The key path target of the supplementary fetch.
|
||||
typealias WillExecuteSupplementaryRequest = (_ request: AnyFetchRequest<Row>, _ keyPath: [String]) throws -> Void
|
||||
|
||||
/// A closure that performs supplementary fetches.
|
||||
///
|
||||
/// Support for eager loading of hasMany associations.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter rows: The rows that are modified by the supplementary fetch.
|
||||
/// - parameter willExecuteSupplementaryRequest: A closure to execute before
|
||||
/// performing supplementary fetches.
|
||||
typealias SupplementaryFetch = (
|
||||
_ db: Database,
|
||||
_ rows: [Row],
|
||||
_ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?)
|
||||
throws -> Void
|
||||
|
||||
/// A `PreparedRequest` is a request that is ready to be executed.
|
||||
public struct PreparedRequest {
|
||||
/// A prepared statement with bound parameters.
|
||||
@@ -115,13 +137,14 @@ public struct PreparedRequest {
|
||||
/// An eventual adapter for rows fetched by the select statement.
|
||||
public var adapter: (any RowAdapter)?
|
||||
|
||||
/// A closure that performs supplementary fetches.
|
||||
/// Support for eager loading of hasMany associations.
|
||||
var supplementaryFetch: ((Database, [Row]) throws -> Void)?
|
||||
var supplementaryFetch: SupplementaryFetch?
|
||||
|
||||
init(
|
||||
statement: Statement,
|
||||
adapter: (any RowAdapter)?,
|
||||
supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil)
|
||||
supplementaryFetch: SupplementaryFetch? = nil)
|
||||
{
|
||||
self.statement = statement
|
||||
self.adapter = adapter
|
||||
@@ -129,6 +152,11 @@ public struct PreparedRequest {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `PreparedRequest` contains
|
||||
// a statement.
|
||||
@available(*, unavailable)
|
||||
extension PreparedRequest: Sendable { }
|
||||
|
||||
extension PreparedRequest: Refinable { }
|
||||
|
||||
// MARK: - AdaptedFetchRequest
|
||||
|
||||
+15
-4
@@ -245,6 +245,12 @@ public final class Row {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: a row contains transient
|
||||
// information. TODO GRDB7: split non sendable statement rows from sendable
|
||||
// copied rows.
|
||||
@available(*, unavailable)
|
||||
extension Row: Sendable { }
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Columns
|
||||
@@ -1377,6 +1383,11 @@ public final class RowCursor: DatabaseCursor {
|
||||
public func _element(sqliteStatement: SQLiteStatement) -> Row { _row }
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension RowCursor: Sendable { }
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Fetching From Prepared Statement
|
||||
@@ -1739,7 +1750,7 @@ extension Row {
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
let rows = try fetchAll(request.statement, adapter: request.adapter)
|
||||
try request.supplementaryFetch?(db, rows)
|
||||
try request.supplementaryFetch?(db, rows, nil)
|
||||
return rows
|
||||
}
|
||||
|
||||
@@ -1772,7 +1783,7 @@ extension Row {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
if let supplementaryFetch = request.supplementaryFetch {
|
||||
let rows = try fetchAll(request.statement, adapter: request.adapter)
|
||||
try supplementaryFetch(db, rows)
|
||||
try supplementaryFetch(db, rows, nil)
|
||||
return Set(rows)
|
||||
} else {
|
||||
return try fetchSet(request.statement, adapter: request.adapter)
|
||||
@@ -1809,7 +1820,7 @@ extension Row {
|
||||
guard let row = try fetchOne(request.statement, adapter: request.adapter) else {
|
||||
return nil
|
||||
}
|
||||
try request.supplementaryFetch?(db, [row])
|
||||
try request.supplementaryFetch?(db, [row], nil)
|
||||
return row
|
||||
}
|
||||
}
|
||||
@@ -2059,7 +2070,7 @@ typealias RowIndex = Row.Index
|
||||
|
||||
extension Row {
|
||||
/// An index to a (column, value) pair in a ``Row``.
|
||||
public struct Index {
|
||||
public struct Index: Sendable {
|
||||
let index: Int
|
||||
init(_ index: Int) { self.index = index }
|
||||
}
|
||||
|
||||
@@ -378,7 +378,7 @@ extension RowAdapter {
|
||||
///
|
||||
/// This limit adapter may turn out useful in some narrow use cases. You'll
|
||||
/// be happy to find it when you need it.
|
||||
public struct EmptyRowAdapter: RowAdapter {
|
||||
public struct EmptyRowAdapter: RowAdapter, Sendable {
|
||||
/// Creates an `EmptyRowAdapter`.
|
||||
public init() { }
|
||||
|
||||
@@ -403,7 +403,7 @@ public struct EmptyRowAdapter: RowAdapter {
|
||||
///
|
||||
/// Note that columns that are not present in the dictionary are not present
|
||||
/// in the resulting adapted row.
|
||||
public struct ColumnMapping: RowAdapter {
|
||||
public struct ColumnMapping: RowAdapter, Sendable {
|
||||
/// A dictionary from mapped column names to column names in a base row.
|
||||
let mapping: [String: String]
|
||||
|
||||
@@ -444,7 +444,7 @@ public struct ColumnMapping: RowAdapter {
|
||||
/// // [c:2, d: 3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```
|
||||
public struct SuffixRowAdapter: RowAdapter {
|
||||
public struct SuffixRowAdapter: RowAdapter, Sendable {
|
||||
/// The suffix index
|
||||
let index: Int
|
||||
|
||||
@@ -473,7 +473,7 @@ public struct SuffixRowAdapter: RowAdapter {
|
||||
/// // [b:1 c:2]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// ```
|
||||
public struct RangeRowAdapter: RowAdapter {
|
||||
public struct RangeRowAdapter: RowAdapter, Sendable {
|
||||
/// The range
|
||||
let range: CountableRange<Int>
|
||||
|
||||
|
||||
@@ -623,6 +623,11 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: statements must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension Statement: Sendable { }
|
||||
|
||||
extension Statement: CustomStringConvertible {
|
||||
public var description: String {
|
||||
SchedulingWatchdog.allows(database) ? sql : "Statement"
|
||||
|
||||
@@ -241,6 +241,11 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension FastDatabaseValueCursor: Sendable { }
|
||||
|
||||
/// Types that adopt both DatabaseValueConvertible and
|
||||
/// StatementColumnConvertible can be efficiently initialized from
|
||||
/// database values.
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import Foundation
|
||||
|
||||
/// A database value that holds date components.
|
||||
public struct DatabaseDateComponents {
|
||||
public struct DatabaseDateComponents: Sendable {
|
||||
|
||||
/// The SQLite formats for date components.
|
||||
public enum Format: String {
|
||||
public enum Format: String, Sendable {
|
||||
|
||||
/// The format "yyyy-MM-dd".
|
||||
case YMD = "yyyy-MM-dd"
|
||||
|
||||
@@ -179,11 +179,7 @@ extension DatabaseValueConvertible where Self: Decodable {
|
||||
guard let data = Data.fromDatabaseValue(databaseValue) else {
|
||||
return nil
|
||||
}
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dataDecodingStrategy = .base64
|
||||
decoder.dateDecodingStrategy = .millisecondsSince1970
|
||||
decoder.nonConformingFloatDecodingStrategy = .throw
|
||||
return try? decoder.decode(Self.self, from: data)
|
||||
return try? databaseJSONDecoder().decode(Self.self, from: data)
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import Foundation
|
||||
|
||||
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
let jsonEncoder: JSONEncoder
|
||||
|
||||
var codingPath: [any CodingKey] { [] }
|
||||
|
||||
@@ -42,16 +43,21 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
|
||||
// This allows us to encode Date as String, for example.
|
||||
encode(dbValueConvertible.databaseValue)
|
||||
} else {
|
||||
try DatabaseValueEncoder(encode: encode).encode(value)
|
||||
try DatabaseValueEncoder(jsonEncoder: jsonEncoder, encode: encode).encode(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class DatabaseValueEncoder: Encoder {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
let jsonEncoder: JSONEncoder
|
||||
var requiresJSON = false
|
||||
|
||||
init(encode: @escaping (DatabaseValue) -> Void) {
|
||||
init(
|
||||
jsonEncoder: JSONEncoder,
|
||||
encode: @escaping (DatabaseValue) -> Void
|
||||
) {
|
||||
self.jsonEncoder = jsonEncoder
|
||||
self.encode = encode
|
||||
}
|
||||
|
||||
@@ -104,7 +110,7 @@ private class DatabaseValueEncoder: Encoder {
|
||||
/// - precondition: May not be called after a value has been encoded through
|
||||
/// a previous `self.singleValueContainer()` call.
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
DatabaseValueEncodingContainer(encode: encode)
|
||||
DatabaseValueEncodingContainer(encode: encode, jsonEncoder: jsonEncoder)
|
||||
}
|
||||
|
||||
func encode<T: Encodable>(_ value: T) throws {
|
||||
@@ -115,13 +121,7 @@ private class DatabaseValueEncoder: Encoder {
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
} catch is JSONRequiredError {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dataEncodingStrategy = .base64
|
||||
encoder.dateEncodingStrategy = .millisecondsSince1970
|
||||
encoder.nonConformingFloatEncodingStrategy = .throw
|
||||
// guarantee some stability in order to ease value comparison
|
||||
encoder.outputFormatting = .sortedKeys
|
||||
let jsonData = try encoder.encode(value)
|
||||
let jsonData = try jsonEncoder.encode(value)
|
||||
|
||||
// Store JSON String in the database for easier debugging and
|
||||
// database inspection. Thanks to SQLite weak typing, we won't
|
||||
@@ -138,7 +138,11 @@ private class DatabaseValueEncoder: Encoder {
|
||||
extension DatabaseValueConvertible where Self: Encodable {
|
||||
public var databaseValue: DatabaseValue {
|
||||
var dbValue: DatabaseValue! = nil
|
||||
try! DatabaseValueEncoder(encode: { dbValue = $0 }).encode(self)
|
||||
try! DatabaseValueEncoder(
|
||||
jsonEncoder: Self.databaseJSONEncoder(),
|
||||
encode: { dbValue = $0 }
|
||||
)
|
||||
.encode(self)
|
||||
return dbValue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,20 @@ extension Database {
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// Adds a transaction observer, so that it gets notified of
|
||||
/// database changes and transactions.
|
||||
/// Adds a transaction observer on the database connection, so that it
|
||||
/// gets notified of database changes and transactions.
|
||||
///
|
||||
/// This method has no effect on read-only database connections.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let myObserver = MyObserver()
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(transactionObserver: myObserver)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter transactionObserver: A transaction observer.
|
||||
/// - parameter extent: The duration of the observation. The default is
|
||||
/// the observer lifetime (observation lasts until observer
|
||||
@@ -26,7 +35,16 @@ extension Database {
|
||||
observationBroker.add(transactionObserver: transactionObserver, extent: extent)
|
||||
}
|
||||
|
||||
/// Removes a transaction observer.
|
||||
/// Removes a transaction observer from the database connection.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let myObserver = MyObserver()
|
||||
/// try dbQueue.write { db in
|
||||
/// db.remove(transactionObserver: myObserver)
|
||||
/// }
|
||||
/// ```
|
||||
public func remove(transactionObserver: some TransactionObserver) {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
guard let observationBroker else { return }
|
||||
@@ -117,7 +135,7 @@ extension Database {
|
||||
}
|
||||
|
||||
/// The extent of the observation performed by a ``TransactionObserver``.
|
||||
public enum TransactionObservationExtent {
|
||||
public enum TransactionObservationExtent: Sendable {
|
||||
/// Observation lasts until observer is deallocated.
|
||||
case observerLifetime
|
||||
/// Observation lasts until the next transaction.
|
||||
@@ -264,6 +282,20 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
func notifyChanges(withEventsOfKind eventKinds: [DatabaseEventKind]) throws {
|
||||
// Support for stopObservingDatabaseChangesUntilNextTransaction()
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = self
|
||||
defer {
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
}
|
||||
|
||||
for observation in transactionObservations where observation.isEnabled {
|
||||
if eventKinds.contains(where: { observation.observes(eventsOfKind: $0) }) {
|
||||
observation.databaseDidChange()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Statement execution
|
||||
|
||||
/// Returns true if there exists some transaction observer interested in
|
||||
@@ -548,6 +580,11 @@ class DatabaseObservationBroker {
|
||||
// even if we actually execute an empty deferred transaction.
|
||||
//
|
||||
// For better or for worse, let's simulate a transaction:
|
||||
//
|
||||
// 2023-11-26: I'm glad we did, because that's how we support calls
|
||||
// to `Database.notifyChanges(in:)` from an empty transaction, as a
|
||||
// way to tell transaction observers about changes performed by some
|
||||
// external connection.
|
||||
|
||||
do {
|
||||
try databaseWillCommit()
|
||||
@@ -764,6 +801,16 @@ public protocol TransactionObserver: AnyObject {
|
||||
/// from being applied on the observed tables.
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
|
||||
/// Called when the database was modified in some unspecified way.
|
||||
///
|
||||
/// This method allows a transaction observer to handle changes that are
|
||||
/// not automatically detected. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes>
|
||||
/// and ``Database/notifyChanges(in:)`` for more information.
|
||||
///
|
||||
/// The exact nature of changes is unknown, but they comply to the
|
||||
/// ``observes(eventsOfKind:)`` test.
|
||||
func databaseDidChange()
|
||||
|
||||
/// Called when the database is changed by an insert, update, or
|
||||
/// delete event.
|
||||
///
|
||||
@@ -839,11 +886,15 @@ extension TransactionObserver {
|
||||
public func databaseWillChange(with event: DatabasePreUpdateEvent) { }
|
||||
#endif
|
||||
|
||||
/// Prevents the observer from receiving further change notifications until
|
||||
/// the next transaction.
|
||||
/// The default implementation does nothing.
|
||||
public func databaseDidChange() { }
|
||||
|
||||
/// Prevents the observer from receiving further change notifications
|
||||
/// until the next transaction.
|
||||
///
|
||||
/// After this method has been called, the ``databaseDidChange(with:)``
|
||||
/// method won't be called until the next transaction.
|
||||
/// and ``databaseDidChange()-7olv7`` methods won't be called until the
|
||||
/// next transaction.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -856,6 +907,13 @@ extension TransactionObserver {
|
||||
/// return eventKind.tableName == "player"
|
||||
/// }
|
||||
///
|
||||
/// func databaseDidChange() {
|
||||
/// playerTableWasModified = true
|
||||
///
|
||||
/// // It is pointless to keep on tracking further changes:
|
||||
/// stopObservingDatabaseChangesUntilNextTransaction()
|
||||
/// }
|
||||
///
|
||||
/// func databaseDidChange(with event: DatabaseEvent) {
|
||||
/// playerTableWasModified = true
|
||||
///
|
||||
@@ -866,12 +924,12 @@ extension TransactionObserver {
|
||||
/// ```
|
||||
///
|
||||
/// - precondition: This method must be called from
|
||||
/// ``databaseDidChange(with:)``.
|
||||
/// ``databaseDidChange(with:)`` or ``databaseDidChange()-7olv7``.
|
||||
public func stopObservingDatabaseChangesUntilNextTransaction() {
|
||||
guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else {
|
||||
fatalError("""
|
||||
stopObservingDatabaseChangesUntilNextTransaction must be called \
|
||||
from the databaseDidChange method
|
||||
from the `databaseDidChange()` or `databaseDidChange(with:)` methods
|
||||
""")
|
||||
}
|
||||
broker.disableUntilNextTransaction(transactionObserver: self)
|
||||
@@ -924,6 +982,11 @@ final class TransactionObservation {
|
||||
}
|
||||
#endif
|
||||
|
||||
func databaseDidChange() {
|
||||
guard isEnabled else { return }
|
||||
observer?.databaseDidChange()
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
guard isEnabled else { return }
|
||||
observer?.databaseDidChange(with: event)
|
||||
@@ -993,7 +1056,7 @@ struct StatementObservation {
|
||||
/// See the ``TransactionObserver/observes(eventsOfKind:)`` method in the
|
||||
/// ``TransactionObserver`` protocol for more information.
|
||||
@frozen
|
||||
public enum DatabaseEventKind {
|
||||
public enum DatabaseEventKind: Sendable {
|
||||
/// The insertion of a row in a database table.
|
||||
case insert(tableName: String)
|
||||
|
||||
@@ -1046,7 +1109,7 @@ protocol DatabaseEventProtocol {
|
||||
/// ``TransactionObserver`` protocol for more information.
|
||||
public struct DatabaseEvent {
|
||||
/// An event kind.
|
||||
public enum Kind: CInt {
|
||||
public enum Kind: CInt, Sendable {
|
||||
/// An insertion event
|
||||
case insert = 18 // SQLITE_INSERT
|
||||
|
||||
@@ -1110,6 +1173,11 @@ public struct DatabaseEvent {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: this type can't be made Sendable
|
||||
// until GRDB7 where we can distinguish between a transient event and its copy.
|
||||
@available(*, unavailable)
|
||||
extension DatabaseEvent: Sendable { }
|
||||
|
||||
extension DatabaseEvent: DatabaseEventProtocol {
|
||||
func send(to observer: TransactionObservation) {
|
||||
observer.databaseDidChange(with: self)
|
||||
|
||||
@@ -21,7 +21,9 @@
|
||||
/// Yes, this is an awfully complex logic.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
|
||||
final class WALSnapshot: Sendable {
|
||||
final class WALSnapshot: @unchecked Sendable {
|
||||
// @unchecked because sqlite3_snapshot has no threading requirements.
|
||||
// <https://www.sqlite.org/c3ref/snapshot.html>
|
||||
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
|
||||
|
||||
init(_ db: Database) throws {
|
||||
|
||||
@@ -46,7 +46,9 @@ class WALSnapshotTransaction {
|
||||
// Open a long-lived transaction, and enter snapshot isolation
|
||||
self.walSnapshot = try reader.sync(allowingLongLivedTransaction: true) { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
// This also acquires snapshot isolation because checking
|
||||
// database schema performs a read access.
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try WALSnapshot(db)
|
||||
}
|
||||
self.reader = reader
|
||||
|
||||
@@ -20,14 +20,20 @@ GRDB puts this SQLite feature to some good use, and lets you observe the databas
|
||||
- ``ValueObservation``
|
||||
- ``SharedValueObservation``
|
||||
- ``AsyncValueObservation``
|
||||
- ``Database/registerAccess(to:)``
|
||||
|
||||
### Observing Database Transactions
|
||||
|
||||
- ``DatabaseRegionObservation``
|
||||
- ``Database/afterNextTransaction(onCommit:onRollback:)``
|
||||
|
||||
### Low-Level Transaction Observers
|
||||
|
||||
- ``TransactionObserver``
|
||||
- ``Database/add(transactionObserver:extent:)``
|
||||
- ``Database/remove(transactionObserver:)``
|
||||
- ``DatabaseWriter/add(transactionObserver:extent:)``
|
||||
- ``DatabaseWriter/remove(transactionObserver:)``
|
||||
- ``Database/TransactionObservationExtent``
|
||||
|
||||
### Database Regions
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# The Database Schema
|
||||
|
||||
Define or query the database schema.
|
||||
|
||||
## Overview
|
||||
|
||||
**GRDB supports all database schemas, and has no requirement.** Any existing SQLite database can be opened, and you are free to structure your new databases as you wish.
|
||||
@@ -24,7 +26,9 @@ When a schema change is not directly supported by SQLite, or not available on th
|
||||
|
||||
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
|
||||
|
||||
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
|
||||
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
|
||||
|
||||
For recommendations specific to JSON columns, see <doc:JSON>.
|
||||
|
||||
### Table names should be English, singular, and camelCased
|
||||
|
||||
@@ -163,11 +167,6 @@ struct Player: Codable {
|
||||
var score: Int
|
||||
}
|
||||
|
||||
extension Player: Identifiable {
|
||||
// Required because the primary key column is not 'id'
|
||||
var id: Int64? { rowid }
|
||||
}
|
||||
|
||||
extension Player: FetchableRecord, MutablePersistableRecord {
|
||||
// Required because the primary key
|
||||
// is the hidden rowid column.
|
||||
@@ -385,23 +384,24 @@ extension Team: TableRecord {
|
||||
|
||||
- ``Database/create(indexOn:columns:options:condition:)``
|
||||
- ``Database/create(index:on:columns:options:condition:)``
|
||||
- ``Database/create(index:on:expressions:options:condition:)``
|
||||
- ``Database/drop(indexOn:columns:)``
|
||||
- ``Database/drop(index:)``
|
||||
- ``IndexOptions``
|
||||
|
||||
### Querying the Database Schema
|
||||
|
||||
- ``Database/columns(in:)``
|
||||
- ``Database/foreignKeys(on:)``
|
||||
- ``Database/indexes(on:)``
|
||||
- ``Database/columns(in:in:)``
|
||||
- ``Database/foreignKeys(on:in:)``
|
||||
- ``Database/indexes(on:in:)``
|
||||
- ``Database/isGRDBInternalTable(_:)``
|
||||
- ``Database/isSQLiteInternalTable(_:)``
|
||||
- ``Database/primaryKey(_:)``
|
||||
- ``Database/primaryKey(_:in:)``
|
||||
- ``Database/schemaVersion()``
|
||||
- ``Database/table(_:hasUniqueKey:)``
|
||||
- ``Database/tableExists(_:)``
|
||||
- ``Database/triggerExists(_:)``
|
||||
- ``Database/viewExists(_:)``
|
||||
- ``Database/tableExists(_:in:)``
|
||||
- ``Database/triggerExists(_:in:)``
|
||||
- ``Database/viewExists(_:in:)``
|
||||
- ``ColumnInfo``
|
||||
- ``ForeignKeyInfo``
|
||||
- ``IndexInfo``
|
||||
@@ -410,9 +410,9 @@ extension Team: TableRecord {
|
||||
### Integrity Checks
|
||||
|
||||
- ``Database/checkForeignKeys()``
|
||||
- ``Database/checkForeignKeys(in:)``
|
||||
- ``Database/checkForeignKeys(in:in:)``
|
||||
- ``Database/foreignKeyViolations()``
|
||||
- ``Database/foreignKeyViolations(in:)``
|
||||
- ``Database/foreignKeyViolations(in:in:)``
|
||||
- ``ForeignKeyViolation``
|
||||
|
||||
### Sunsetted Methods
|
||||
|
||||
@@ -152,11 +152,14 @@ If several processes want to write in the database, configure the database pool
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.defaultTransactionKind = .immediate
|
||||
configuration.busyMode = .timeout(/* a TimeInterval */)
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
With such a setup, you may still get `SQLITE_BUSY` errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
|
||||
Both the `defaultTransactionKind` and `busyMode` are important for preventing `SQLITE_BUSY`. The `immediate` transaction kind prevents write transactions from overlapping, and the busy timeout has write transactions wait, instead of throwing `SQLITE_BUSY`, whenever another process is writing.
|
||||
|
||||
With such a setup, you will still get `SQLITE_BUSY` errors if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
|
||||
|
||||
```swift
|
||||
do {
|
||||
@@ -228,9 +231,7 @@ In applications that use the background modes supported by iOS, post `resumeNoti
|
||||
|
||||
<doc:DatabaseObservation> features are not able to detect database changes performed by other processes.
|
||||
|
||||
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
|
||||
|
||||
You can trigger those notifications automatically with ``DatabaseRegionObservation``:
|
||||
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter]. You can trigger those notifications automatically with ``DatabaseRegionObservation``:
|
||||
|
||||
```swift
|
||||
// Notify all changes made to the database
|
||||
@@ -246,6 +247,8 @@ let observer = try observation.start(in: dbPool) { db in
|
||||
}
|
||||
```
|
||||
|
||||
The processes that observe the database can catch those notifications, and deal with the notified changes. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes> for some related techniques.
|
||||
|
||||
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
|
||||
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
|
||||
[WAL mode]: https://www.sqlite.org/wal.html
|
||||
|
||||
@@ -78,8 +78,7 @@ A `DatabasePool` needs your application to follow rules in order to deliver its
|
||||
|
||||
### Accessing the Database
|
||||
|
||||
See ``DatabaseReader`` and ``DatabaseWriter`` for more database
|
||||
access methods.
|
||||
See ``DatabaseReader`` and ``DatabaseWriter`` for more database access methods.
|
||||
|
||||
- ``asyncConcurrentRead(_:)``
|
||||
- ``writeInTransaction(_:_:)``
|
||||
|
||||
@@ -88,11 +88,12 @@ A `DatabaseQueue` needs your application to follow rules in order to deliver its
|
||||
|
||||
- ``init(named:configuration:)``
|
||||
- ``init(path:configuration:)``
|
||||
- ``inMemoryCopy(fromPath:configuration:)``
|
||||
- ``temporaryCopy(fromPath:configuration:)``
|
||||
|
||||
### Accessing the Database
|
||||
|
||||
See ``DatabaseReader`` and ``DatabaseWriter`` for more database
|
||||
access methods.
|
||||
See ``DatabaseReader`` and ``DatabaseWriter`` for more database access methods.
|
||||
|
||||
- ``inDatabase(_:)``
|
||||
- ``inTransaction(_:_:)``
|
||||
|
||||
@@ -6,11 +6,7 @@
|
||||
|
||||
`DatabaseRegionObservation` tracks insertions, updates, and deletions that impact the tracked region, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
The only changes that are not notified are:
|
||||
|
||||
- Changes performed by external database connections.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
See <doc:GRDB/DatabaseRegionObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
|
||||
|
||||
`DatabaseRegionObservation` calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check ``ValueObservation`` before using `DatabaseRegionObservation`.
|
||||
|
||||
@@ -78,6 +74,30 @@ let observation = DatabaseRegionObservation(
|
||||
tracking: .fullDatabase)
|
||||
```
|
||||
|
||||
## Dealing with Undetected Changes
|
||||
|
||||
`DatabaseRegionObservation` will not notify impactful transactions whenever the database is modified in an undetectable way:
|
||||
|
||||
- Changes performed by external database connections.
|
||||
- Changes performed by SQLite statements that are not compiled and executed by GRDB.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
|
||||
To have observations notify such undetected changes, applications can take explicit action: call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Notify observations that some changes were performed in the database
|
||||
try db.notifyChanges(in: .fullDatabase)
|
||||
|
||||
// Notify observations that some changes were performed in the player table
|
||||
try db.notifyChanges(in: Player.all())
|
||||
|
||||
// Equivalent alternative
|
||||
try db.notifyChanges(in: Table("player"))
|
||||
}
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Creating DatabaseRegionObservation
|
||||
|
||||
@@ -74,7 +74,14 @@ extension Color: DatabaseValueConvertible { }
|
||||
|
||||
By default, such codable value types are encoded and decoded with the standard [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) and [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder). `Data` values are handled with the `.base64` strategy, `Date` with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy.
|
||||
|
||||
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements.
|
||||
To customize the JSON format, provide an explicit implementation for the `DatabaseValueConvertible` requirements, or implement these two methods:
|
||||
|
||||
```swift
|
||||
protocol DatabaseValueConvertible {
|
||||
static func databaseJSONDecoder() -> JSONDecoder
|
||||
static func databaseJSONEncoder() -> JSONEncoder
|
||||
}
|
||||
```
|
||||
|
||||
### Adding support for the Tagged library
|
||||
|
||||
@@ -144,6 +151,11 @@ This extra conformance is not required: only aim at the low-level C interface if
|
||||
|
||||
- ``databaseValue-1ob9k``
|
||||
|
||||
### Configuring the JSON format for the standard Decodable protocol
|
||||
|
||||
- ``databaseJSONDecoder()-7zou9``
|
||||
- ``databaseJSONEncoder()-37sff``
|
||||
|
||||
### Fetching Values from Raw SQL
|
||||
|
||||
- ``fetchCursor(_:sql:arguments:adapter:)-6elcz``
|
||||
|
||||
@@ -25,13 +25,7 @@ Database changes are notified to the ``databaseDidChange(with:)`` callback. This
|
||||
|
||||
Transaction completions are notified to the ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
|
||||
|
||||
The only changes and transactions that are not notified are:
|
||||
|
||||
- Read-only transactions.
|
||||
- Changes and transactions performed by external database connections.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
|
||||
> Important: Some changes and transactions are not automatically notified. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes> below.
|
||||
|
||||
Notified changes are not actually written to disk until the transaction commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation:
|
||||
|
||||
@@ -189,7 +183,7 @@ class PlayerObserver: TransactionObserver {
|
||||
}
|
||||
```
|
||||
|
||||
### Support for SQLite Pre-Update Hooks
|
||||
## Support for SQLite Pre-Update Hooks
|
||||
|
||||
When SQLite is built with the `SQLITE_ENABLE_PREUPDATE_HOOK` option, `TransactionObserver` gets an extra callback which lets you observe individual column values in the rows modified by a transaction:
|
||||
|
||||
@@ -235,6 +229,41 @@ This extra API can be activated in two ways:
|
||||
|
||||
2. Use a [custom SQLite build](http://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md) and activate the `SQLITE_ENABLE_PREUPDATE_HOOK` compilation option.
|
||||
|
||||
## Dealing with Undetected Changes
|
||||
|
||||
The changes and transactions that are not automatically notified to transaction observers are:
|
||||
|
||||
- Read-only transactions.
|
||||
- Changes and transactions performed by external database connections.
|
||||
- Changes performed by SQLite statements that are not both compiled and executed through GRDB APIs.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
|
||||
|
||||
To notify undetected changes to transaction observers, perform an explicit call to the ``Database/notifyChanges(in:)`` `Database` method. The ``databaseDidChange()-7olv7`` callback will be called accordingly. For example:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Notify observers that some changes were performed in the database
|
||||
try db.notifyChanges(in: .fullDatabase)
|
||||
|
||||
// Notify observers that some changes were performed in the player table
|
||||
try db.notifyChanges(in: Player.all())
|
||||
|
||||
// Equivalent alternative
|
||||
try db.notifyChanges(in: Table("player"))
|
||||
}
|
||||
```
|
||||
|
||||
To notify a change in the database schema, notify a change to the `sqlite_master` table:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Notify all observers of the sqlite_master table
|
||||
try db.notifyChanges(in: Table("sqlite_master"))
|
||||
}
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Filtering Database Changes
|
||||
@@ -244,6 +273,7 @@ This extra API can be activated in two ways:
|
||||
|
||||
### Handling Database Changes
|
||||
|
||||
- ``databaseDidChange()-7olv7``
|
||||
- ``databaseDidChange(with:)``
|
||||
- ``stopObservingDatabaseChangesUntilNextTransaction()``
|
||||
- ``DatabaseEvent``
|
||||
|
||||
@@ -6,11 +6,7 @@
|
||||
|
||||
`ValueObservation` tracks insertions, updates, and deletions that impact the tracked value, whether performed with raw SQL, or <doc:QueryInterface>. This includes indirect changes triggered by [foreign keys actions](https://www.sqlite.org/foreignkeys.html#fk_actions) or [SQL triggers](https://www.sqlite.org/lang_createtrigger.html).
|
||||
|
||||
The only changes that are not notified are:
|
||||
|
||||
- Changes performed by external database connections. See <doc:DatabaseSharing#How-to-perform-cross-process-database-observation> for more information.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
See <doc:GRDB/ValueObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
|
||||
|
||||
## ValueObservation Usage
|
||||
|
||||
@@ -174,6 +170,30 @@ let observation = ValueObservation.tracking(
|
||||
|
||||
This ``tracking(region:_:fetch:)`` method lets you entirely separate the **observed region(s)** from the **fetched value** itself, for maximum flexibility. See ``DatabaseRegionConvertible`` for more information about the regions that can be tracked.
|
||||
|
||||
## Dealing with Undetected Changes
|
||||
|
||||
`ValueObservation` will not fetch and notify a fresh value whenever the database is modified in an undetectable way:
|
||||
|
||||
- Changes performed by external database connections.
|
||||
- Changes performed by SQLite statements that are not compiled and executed by GRDB.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
|
||||
To have observations notify a fresh values after such an undetected change was performed, applications can take explicit action. For example, cancel and restart observations. Alternatively, call the ``Database/notifyChanges(in:)`` `Database` method from a write transaction:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Notify observations that some changes were performed in the database
|
||||
try db.notifyChanges(in: .fullDatabase)
|
||||
|
||||
// Notify observations that some changes were performed in the player table
|
||||
try db.notifyChanges(in: Player.all())
|
||||
|
||||
// Equivalent alternative
|
||||
try db.notifyChanges(in: Table("player"))
|
||||
}
|
||||
```
|
||||
|
||||
## ValueObservation Performance
|
||||
|
||||
This section further describes runtime aspects of `ValueObservation`, and provides some optimization tips for demanding applications.
|
||||
|
||||
@@ -6,10 +6,6 @@ A toolkit for SQLite databases, with a focus on application development
|
||||
|
||||

|
||||
|
||||
- [GitHub Repository](http://github.com/groue/GRDB.swift)
|
||||
- [Installation Instructions, encryption with SQLCipher, custom SQLite builds](https://github.com/groue/GRDB.swift#installation)
|
||||
- [GRDBQuery](https://github.com/groue/GRDBQuery), the SwiftUI companion for GRDB
|
||||
|
||||
## Overview
|
||||
|
||||
Use this library to save your application’s permanent data into SQLite databases. It comes with built-in tools that address common needs:
|
||||
@@ -71,6 +67,12 @@ let players: [Player] = try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
## Links and Companion Libraries
|
||||
|
||||
- [GitHub Repository](http://github.com/groue/GRDB.swift)
|
||||
- [Installation Instructions, encryption with SQLCipher, custom SQLite builds](https://github.com/groue/GRDB.swift#installation)
|
||||
- [GRDBQuery](https://github.com/groue/GRDBQuery): the SwiftUI companion for GRDB.
|
||||
- [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting): Test your database.
|
||||
|
||||
## Topics
|
||||
|
||||
@@ -93,14 +95,9 @@ let players: [Player] = try dbQueue.read { db in
|
||||
- <doc:RecordTimestamps>
|
||||
- <doc:SingleRowTables>
|
||||
|
||||
### Responding to Database Changes
|
||||
### Application Tools
|
||||
|
||||
- <doc:DatabaseObservation>
|
||||
|
||||
### Full-Text Search
|
||||
|
||||
- <doc:FullTextSearch>
|
||||
|
||||
### Combine Publishers
|
||||
|
||||
- <doc:JSON>
|
||||
- ``DatabasePublishers``
|
||||
@@ -0,0 +1,151 @@
|
||||
# JSON Support
|
||||
|
||||
Store and use JSON values in SQLite databases.
|
||||
|
||||
## Overview
|
||||
|
||||
SQLite and GRDB can store and fetch JSON values in database columns. Starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+, JSON values can be manipulated at the database level.
|
||||
|
||||
## Store and fetch JSON values
|
||||
|
||||
### JSON columns in the database schema
|
||||
|
||||
It is recommended to store JSON values in text columns. In the example below, we create a ``Database/ColumnType/jsonText`` column with ``Database/create(table:options:body:)``:
|
||||
|
||||
```swift
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
t.column("address", .jsonText).notNull() // A JSON column
|
||||
}
|
||||
```
|
||||
|
||||
> Note: `.jsonText` and `.text` are equivalent, because both build a TEXT column in SQL. Yet the former better describes the intent of the column.
|
||||
>
|
||||
> Note: SQLite JSON functions and operators are [documented](https://www.sqlite.org/json1.html#interface_overview) to throw errors if any of their arguments are binary blobs. That's the reason why it is recommended to store JSON as text.
|
||||
|
||||
> Tip: When an application performs queries on values embedded inside JSON columns, indexes can help performance:
|
||||
>
|
||||
> ```swift
|
||||
> // CREATE INDEX "player_on_country"
|
||||
> // ON "player"("address" ->> 'country')
|
||||
> try db.create(
|
||||
> index: "player_on_country",
|
||||
> on: "player",
|
||||
> expressions: [
|
||||
> JSONColumn("address")["country"],
|
||||
> ])
|
||||
>
|
||||
> // SELECT * FROM player
|
||||
> // WHERE "address" ->> 'country' = 'DE'
|
||||
> let germanPlayers = try Player
|
||||
> .filter(JSONColumn("address")["country"] == "DE")
|
||||
> .fetchAll(db)
|
||||
> ```
|
||||
|
||||
### Strict and flexible JSON schemas
|
||||
|
||||
[Codable Records](https://github.com/groue/GRDB.swift/blob/master/README.md#codable-records) handle both strict and flexible JSON schemas.
|
||||
|
||||
**For strict schemas**, use `Codable` properties. They will be stored as JSON strings in the database:
|
||||
|
||||
```swift
|
||||
struct Address: Codable {
|
||||
var street: String
|
||||
var city: String
|
||||
var country: String
|
||||
}
|
||||
|
||||
struct Player: Codable {
|
||||
var id: String
|
||||
var name: String
|
||||
|
||||
// Stored as a JSON string
|
||||
// {"street": "...", "city": "...", "country": "..."}
|
||||
var address: Address
|
||||
}
|
||||
|
||||
extension Player: FetchableRecord, PersistableRecord { }
|
||||
```
|
||||
|
||||
**For flexible schemas**, use `String` or `Data` properties.
|
||||
|
||||
In the specific case of `Data` properties, it is recommended to store them as text in the database, because SQLite JSON functions and operators are [documented](https://www.sqlite.org/json1.html#interface_overview) to throw errors if any of their arguments are binary blobs. This encoding is automatic with ``DatabaseDataEncodingStrategy/text``:
|
||||
|
||||
```swift
|
||||
// JSON String property
|
||||
struct Player: Codable {
|
||||
var id: String
|
||||
var name: String
|
||||
var address: String // JSON string
|
||||
}
|
||||
|
||||
extension Player: FetchableRecord, PersistableRecord { }
|
||||
|
||||
// JSON Data property, saved as text in the database
|
||||
struct Team: Codable {
|
||||
var id: String
|
||||
var color: String
|
||||
var info: Data // JSON UTF8 data
|
||||
}
|
||||
|
||||
extension Team: FetchableRecord, PersistableRecord {
|
||||
// Support SQLite JSON functions and operators
|
||||
// by storing JSON data as database text:
|
||||
static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text
|
||||
}
|
||||
```
|
||||
|
||||
## Manipulate JSON values at the database level
|
||||
|
||||
[SQLite JSON functions and operators](https://www.sqlite.org/json1.html) are available starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+.
|
||||
|
||||
Functions such as `JSON`, `JSON_EXTRACT`, `JSON_PATCH` and others are available as static methods on `Database`: ``Database/json(_:)``, ``Database/jsonExtract(_:atPath:)``, ``Database/jsonPatch(_:with:)``, etc.
|
||||
|
||||
See the full list below.
|
||||
|
||||
## JSON table-valued functions
|
||||
|
||||
The JSON table-valued functions `json_each` and `json_tree` are not supported.
|
||||
|
||||
## Topics
|
||||
|
||||
### JSON Values
|
||||
|
||||
- ``SQLJSONExpressible``
|
||||
- ``JSONColumn``
|
||||
|
||||
### Access JSON subcomponents, and query JSON values, at the SQL level
|
||||
|
||||
The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` protocol.
|
||||
|
||||
- ``Database/jsonArrayLength(_:)``
|
||||
- ``Database/jsonArrayLength(_:atPath:)``
|
||||
- ``Database/jsonExtract(_:atPath:)``
|
||||
- ``Database/jsonExtract(_:atPaths:)``
|
||||
- ``Database/jsonType(_:)``
|
||||
- ``Database/jsonType(_:atPath:)``
|
||||
|
||||
### Build new JSON values at the SQL level
|
||||
|
||||
- ``Database/json(_:)``
|
||||
- ``Database/jsonArray(_:)-8xxe3``
|
||||
- ``Database/jsonArray(_:)-469db``
|
||||
- ``Database/jsonObject(_:)``
|
||||
- ``Database/jsonQuote(_:)``
|
||||
- ``Database/jsonGroupArray(_:filter:)``
|
||||
- ``Database/jsonGroupObject(key:value:filter:)``
|
||||
|
||||
### Modify JSON values at the SQL level
|
||||
|
||||
- ``Database/jsonInsert(_:_:)``
|
||||
- ``Database/jsonPatch(_:with:)``
|
||||
- ``Database/jsonReplace(_:_:)``
|
||||
- ``Database/jsonRemove(_:atPath:)``
|
||||
- ``Database/jsonRemove(_:atPaths:)``
|
||||
- ``Database/jsonSet(_:_:)``
|
||||
|
||||
### Validate JSON values at the SQL level
|
||||
|
||||
- ``Database/jsonErrorPosition(_:)``
|
||||
- ``Database/jsonIsValid(_:)``
|
||||
@@ -233,7 +233,7 @@ To prevent a migration from committing foreign key violations on disk, you can:
|
||||
}
|
||||
```
|
||||
|
||||
As in the above example, check for foreign key violations with the ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:)`` methods. They throw a nicely detailed ``DatabaseError`` that contains a lot of debugging information:
|
||||
As in the above example, check for foreign key violations with the ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:in:)`` methods. They throw a nicely detailed ``DatabaseError`` that contains a lot of debugging information:
|
||||
|
||||
```swift
|
||||
// SQLite error 19: FOREIGN KEY constraint violation - from book(authorId) to author(id),
|
||||
|
||||
@@ -17,16 +17,22 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R
|
||||
- ``PersistableRecord``
|
||||
- ``TableRecord``
|
||||
|
||||
### Associations
|
||||
### Expressions
|
||||
|
||||
- ``Association``
|
||||
- ``Column``
|
||||
- ``JSONColumn``
|
||||
- ``SQLExpression``
|
||||
|
||||
### Query Interface Requests
|
||||
### Requests
|
||||
|
||||
- ``CommonTableExpression``
|
||||
- ``QueryInterfaceRequest``
|
||||
- ``Table``
|
||||
|
||||
### Associations
|
||||
|
||||
- ``Association``
|
||||
|
||||
### Errors
|
||||
|
||||
- ``RecordError``
|
||||
@@ -34,9 +40,11 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``ColumnExpression``
|
||||
- ``DerivableRequest``
|
||||
- ``SQLExpressible``
|
||||
- ``SQLJSONExpressible``
|
||||
- ``SQLSpecificExpressible``
|
||||
- ``SQLSubqueryable``
|
||||
- ``SQLOrderingTerm``
|
||||
- ``SQLSelectable``
|
||||
- ``SQLSubqueryable``
|
||||
@@ -61,16 +61,16 @@ Thanks to this database schema, the application will always process *consistent
|
||||
|
||||
**Define one record type per database table.** This record type will be responsible for writing in this table.
|
||||
|
||||
**Let's start from regular structs** whose properties match the columns in their database table. Those structs conform to the standard [`Identifiable`] protocol because they have an identifier (the primary key). They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
|
||||
**Let's start from regular structs** whose properties match the columns in their database table. They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
|
||||
|
||||
```swift
|
||||
struct Author: Codable, Identifiable {
|
||||
struct Author: Codable {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var countryCode: String?
|
||||
}
|
||||
|
||||
struct Book: Codable, Identifiable {
|
||||
struct Book: Codable {
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
@@ -129,7 +129,7 @@ let books = try dbQueue.read { db in
|
||||
> t.column("countryCode", .text) // Can be NULL
|
||||
> }
|
||||
>
|
||||
> struct Author: Codable, Identifiable {
|
||||
> struct Author: Codable {
|
||||
> var id: Int64?
|
||||
> var name: String // Not optional
|
||||
> var countryCode: String? // Optional
|
||||
@@ -150,6 +150,25 @@ let books = try dbQueue.read { db in
|
||||
> try Author.find(db, id: authorID)
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> Take care that **`Identifiable` is not a good fit for optional ids**. You will frequently meet optional ids for records with auto-incremented ids:
|
||||
>
|
||||
> ```swift
|
||||
> struct Player: Codable {
|
||||
> var id: Int64? // Optional ids are not suitable for Identifiable
|
||||
> var name: String
|
||||
> var score: Int
|
||||
> }
|
||||
>
|
||||
> extension Player: FetchableRecord, MutablePersistableRecord {
|
||||
> // Update auto-incremented id upon successful insertion
|
||||
> mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
> id = inserted.rowID
|
||||
> }
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> For more details about auto-incremented ids and `Identifiable`, see [issue #1435](https://github.com/groue/GRDB.swift/issues/1435#issuecomment-1740857712).
|
||||
|
||||
### Record Types Hide Intimate Database Details
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ try db.create(table: "player") { t in
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
struct Player: Identifiable {
|
||||
struct Player {
|
||||
var id: Int64?
|
||||
var creationDate: Date?
|
||||
var modificationDate: Date?
|
||||
@@ -156,7 +156,7 @@ When you fetch timestamped records from the database, it may be inconvenient to
|
||||
|
||||
```swift
|
||||
let player = try dbQueue.read { db
|
||||
try Player.find(db, id: 1)
|
||||
try Player.find(db, key: 1)
|
||||
}
|
||||
player.creationDate // optional 😕
|
||||
player.modificationDate // optional 😕
|
||||
@@ -166,7 +166,7 @@ A possible technique is to define two record types: one that deals with players
|
||||
|
||||
```swift
|
||||
/// `Player` deals with unsaved players
|
||||
struct Player: Identifiable {
|
||||
struct Player {
|
||||
var id: Int64? // optional
|
||||
var creationDate: Date? // optional
|
||||
var modificationDate: Date? // optional
|
||||
@@ -244,7 +244,7 @@ You can copy it in your application, or use it as an inspiration. Not all apps h
|
||||
|
||||
```swift
|
||||
// The base Player type
|
||||
struct Player: Identifiable {
|
||||
struct Player {
|
||||
var id: Int64?
|
||||
var creationDate: Date?
|
||||
var modificationDate: Date?
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# Transactions and Savepoints
|
||||
|
||||
Precise transaction handling.
|
||||
|
||||
## Transactions and Safety
|
||||
|
||||
**A transaction is a fundamental tool of SQLite** that guarantees [data consistency](https://www.sqlite.org/transactional.html) as well as [proper isolation](https://sqlite.org/isolation.html) between application threads and database connections. It is at the core of GRDB <doc:Concurrency> guarantees.
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
import Foundation
|
||||
|
||||
// MARK: - Dump
|
||||
|
||||
extension Database {
|
||||
/// Prints the results of all statements in the provided SQL.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// try db.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sql: The executed SQL.
|
||||
/// - format: The output format.
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
/// console by default.
|
||||
public func dumpSQL(
|
||||
_ sql: SQL,
|
||||
format: some DumpFormat = .debug(),
|
||||
to stream: (any TextOutputStream)? = nil)
|
||||
throws
|
||||
{
|
||||
var dumpStream = DumpStream(stream)
|
||||
try _dumpSQL(sql, format: format, to: &dumpStream)
|
||||
}
|
||||
|
||||
/// Prints the results of a request.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// try db.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - request : The executed request.
|
||||
/// - format: The output format.
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
/// console by default.
|
||||
public func dumpRequest(
|
||||
_ request: some FetchRequest,
|
||||
format: some DumpFormat = .debug(),
|
||||
to stream: (any TextOutputStream)? = nil)
|
||||
throws
|
||||
{
|
||||
var dumpStream = DumpStream(stream)
|
||||
try _dumpRequest(request, format: format, to: &dumpStream)
|
||||
}
|
||||
|
||||
/// Prints the contents of the provided tables and views.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// // player
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// //
|
||||
/// // team
|
||||
/// // 1|Red
|
||||
/// // 2|Blue
|
||||
/// try db.dumpTables(["player", "team"])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - tables: The table names.
|
||||
/// - format: The output format.
|
||||
/// - tableHeader: Options for printing table names.
|
||||
/// - stableOrder: A boolean value that controls the ordering of
|
||||
/// rows fetched from views. If false (the default), rows are
|
||||
/// printed in the order specified by the view (which may be
|
||||
/// undefined). It true, outputted rows are always printed in the
|
||||
/// same stable order. The purpose of this stable order is to make
|
||||
/// the output suitable for testing.
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
/// console by default.
|
||||
public func dumpTables(
|
||||
_ tables: [String],
|
||||
format: some DumpFormat = .debug(),
|
||||
tableHeader: DumpTableHeaderOptions = .automatic,
|
||||
stableOrder: Bool = false,
|
||||
to stream: (any TextOutputStream)? = nil)
|
||||
throws
|
||||
{
|
||||
var dumpStream = DumpStream(stream)
|
||||
try _dumpTables(
|
||||
tables,
|
||||
format: format,
|
||||
tableHeader: tableHeader,
|
||||
stableOrder: stableOrder,
|
||||
to: &dumpStream)
|
||||
}
|
||||
|
||||
/// Prints the contents of the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// try db.dumpContent()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This prints the database schema as well as the content of all
|
||||
/// tables. For example:
|
||||
///
|
||||
/// ```
|
||||
/// sqlite_master
|
||||
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
|
||||
///
|
||||
/// player
|
||||
/// 1,'Arthur',500
|
||||
/// 2,'Barbara',1000
|
||||
/// ```
|
||||
///
|
||||
/// > Note: Internal SQLite and GRDB schema objects are not recorded
|
||||
/// > (those with a name that starts with "sqlite_" or "grdb_").
|
||||
/// >
|
||||
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
|
||||
/// > not recorded, starting SQLite 3.37+.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - format: The output format.
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
/// console by default.
|
||||
public func dumpContent(
|
||||
format: some DumpFormat = .debug(),
|
||||
to stream: (any TextOutputStream)? = nil)
|
||||
throws
|
||||
{
|
||||
var dumpStream = DumpStream(stream)
|
||||
try _dumpContent(format: format, to: &dumpStream)
|
||||
}
|
||||
|
||||
/// Prints the schema of the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// try db.dumpSchema()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This prints the database schema. For example:
|
||||
///
|
||||
/// ```
|
||||
/// sqlite_master
|
||||
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
|
||||
/// ```
|
||||
///
|
||||
/// > Note: Internal SQLite and GRDB schema objects are not recorded
|
||||
/// > (those with a name that starts with "sqlite_" or "grdb_").
|
||||
/// >
|
||||
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
|
||||
/// > not recorded, starting SQLite 3.37+.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
/// console by default.
|
||||
public func dumpSchema(
|
||||
to stream: (any TextOutputStream)? = nil)
|
||||
throws
|
||||
{
|
||||
var dumpStream = DumpStream(stream)
|
||||
try _dumpSchema(to: &dumpStream)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension Database {
|
||||
func _dumpStatements(
|
||||
_ statements: some Cursor<Statement>,
|
||||
format: some DumpFormat,
|
||||
to stream: inout DumpStream)
|
||||
throws
|
||||
{
|
||||
while let statement = try statements.next() {
|
||||
var stepFormat = format
|
||||
let cursor = try statement.makeCursor()
|
||||
while try cursor.next() != nil {
|
||||
try stepFormat.writeRow(self, statement: statement, to: &stream)
|
||||
}
|
||||
stepFormat.finalize(self, statement: statement, to: &stream)
|
||||
}
|
||||
}
|
||||
|
||||
func _dumpSQL(
|
||||
_ sql: SQL,
|
||||
format: some DumpFormat,
|
||||
to stream: inout DumpStream)
|
||||
throws
|
||||
{
|
||||
try _dumpStatements(allStatements(literal: sql), format: format, to: &stream)
|
||||
}
|
||||
|
||||
func _dumpRequest(
|
||||
_ request: some FetchRequest,
|
||||
format: some DumpFormat,
|
||||
to stream: inout DumpStream)
|
||||
throws
|
||||
{
|
||||
let preparedRequest = try request.makePreparedRequest(self, forSingleResult: false)
|
||||
try _dumpStatements(AnyCursor([preparedRequest.statement]), format: format, to: &stream)
|
||||
|
||||
if let supplementaryFetch = preparedRequest.supplementaryFetch {
|
||||
let rows = try Row.fetchAll(self, request)
|
||||
try withoutActuallyEscaping(
|
||||
{ request, keyPath in
|
||||
stream.write("\n")
|
||||
stream.writeln(keyPath.joined(separator: "."))
|
||||
try self._dumpRequest(request, format: format, to: &stream)
|
||||
},
|
||||
do: { willExecuteSupplementaryRequest in
|
||||
try supplementaryFetch(self, rows, willExecuteSupplementaryRequest)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func _dumpTables(
|
||||
_ tables: [String],
|
||||
format: some DumpFormat,
|
||||
tableHeader: DumpTableHeaderOptions,
|
||||
stableOrder: Bool,
|
||||
to stream: inout DumpStream)
|
||||
throws
|
||||
{
|
||||
let header: Bool
|
||||
switch tableHeader {
|
||||
case .always: header = true
|
||||
case .automatic: header = tables.count > 1
|
||||
}
|
||||
|
||||
var first = true
|
||||
for table in tables {
|
||||
if first {
|
||||
first = false
|
||||
} else {
|
||||
stream.write("\n")
|
||||
}
|
||||
|
||||
if header {
|
||||
stream.writeln(table)
|
||||
}
|
||||
|
||||
if try tableExists(table) {
|
||||
// Always sort tables by primary key
|
||||
try _dumpRequest(Table(table).orderByPrimaryKey(), format: format, to: &stream)
|
||||
} else if stableOrder {
|
||||
// View with stable order
|
||||
try _dumpRequest(Table(table).all().withStableOrder(), format: format, to: &stream)
|
||||
} else {
|
||||
// Use view ordering, if any (no guarantee of stable order).
|
||||
try _dumpRequest(Table(table).all(), format: format, to: &stream)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func _dumpContent(
|
||||
format: some DumpFormat,
|
||||
to stream: inout DumpStream)
|
||||
throws
|
||||
{
|
||||
try _dumpSchema(to: &stream)
|
||||
stream.margin()
|
||||
|
||||
let tables = try String
|
||||
.fetchAll(self, sql: """
|
||||
SELECT name
|
||||
FROM sqlite_master
|
||||
WHERE type = 'table'
|
||||
ORDER BY name COLLATE NOCASE
|
||||
""")
|
||||
.filter {
|
||||
try !ignoresObject(named: $0)
|
||||
}
|
||||
try _dumpTables(tables, format: format, tableHeader: .always, stableOrder: true, to: &stream)
|
||||
}
|
||||
|
||||
func _dumpSchema(
|
||||
to stream: inout DumpStream)
|
||||
throws
|
||||
{
|
||||
stream.writeln("sqlite_master")
|
||||
let sqlRows = try Row.fetchAll(self, sql: """
|
||||
SELECT sql || ';', name
|
||||
FROM sqlite_master
|
||||
WHERE sql IS NOT NULL
|
||||
ORDER BY
|
||||
tbl_name COLLATE NOCASE,
|
||||
CASE type WHEN 'table' THEN 'a' WHEN 'index' THEN 'aa' ELSE type END,
|
||||
name COLLATE NOCASE,
|
||||
sql
|
||||
""")
|
||||
for row in sqlRows {
|
||||
let name: String = row[1]
|
||||
if try ignoresObject(named: name) {
|
||||
continue
|
||||
}
|
||||
stream.writeln(row[0])
|
||||
}
|
||||
}
|
||||
|
||||
private func ignoresObject(named name: String) throws -> Bool {
|
||||
if Database.isSQLiteInternalTable(name) { return true }
|
||||
if Database.isGRDBInternalTable(name) { return true }
|
||||
if try isShadowTable(name) { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
private func isShadowTable(_ tableName: String) throws -> Bool {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Maybe SQLCipher is too old: check actual version
|
||||
if sqlite3_libversion_number() >= 3037000 {
|
||||
guard let table = try table(tableName) else {
|
||||
// Not a table
|
||||
return false
|
||||
}
|
||||
return table.kind == .shadow
|
||||
}
|
||||
#else
|
||||
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
|
||||
guard let table = try table(tableName) else {
|
||||
// Not a table
|
||||
return false
|
||||
}
|
||||
return table.kind == .shadow
|
||||
}
|
||||
#endif
|
||||
// Don't know
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Options for printing table names.
|
||||
public enum DumpTableHeaderOptions: Sendable {
|
||||
/// Table names are only printed when several tables are printed.
|
||||
case automatic
|
||||
|
||||
/// Table names are always printed.
|
||||
case always
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
extension DatabaseReader {
|
||||
/// Prints the results of all statements in the provided SQL.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// try dbQueue.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sql: The executed SQL.
|
||||
/// - format: The output format.
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
/// console by default.
|
||||
public func dumpSQL(
|
||||
_ sql: SQL,
|
||||
format: some DumpFormat = .debug(),
|
||||
to stream: (any TextOutputStream)? = nil)
|
||||
throws
|
||||
{
|
||||
try unsafeReentrantRead { db in
|
||||
try db.dumpSQL(sql, format: format, to: stream)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints the results of a request.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// try dbQueue.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - request : The executed request.
|
||||
/// - format: The output format.
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
/// console by default.
|
||||
public func dumpRequest(
|
||||
_ request: some FetchRequest,
|
||||
format: some DumpFormat = .debug(),
|
||||
to stream: (any TextOutputStream)? = nil)
|
||||
throws
|
||||
{
|
||||
try unsafeReentrantRead { db in
|
||||
try db.dumpRequest(request, format: format, to: stream)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints the contents of the provided tables and views.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // player
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// //
|
||||
/// // team
|
||||
/// // 1|Red
|
||||
/// // 2|Blue
|
||||
/// try dbQueue.dumpTables(["player", "team"])
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - tables: The table names.
|
||||
/// - format: The output format.
|
||||
/// - tableHeader: Options for printing table names.
|
||||
/// - stableOrder: A boolean value that controls the ordering of
|
||||
/// rows fetched from views. If false (the default), rows are
|
||||
/// printed in the order specified by the view (which may be
|
||||
/// undefined). It true, outputted rows are always printed in the
|
||||
/// same stable order. The purpose of this stable order is to make
|
||||
/// the output suitable for testing.
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
/// console by default.
|
||||
public func dumpTables(
|
||||
_ tables: [String],
|
||||
format: some DumpFormat = .debug(),
|
||||
tableHeader: DumpTableHeaderOptions = .automatic,
|
||||
stableOrder: Bool = false,
|
||||
to stream: (any TextOutputStream)? = nil)
|
||||
throws
|
||||
{
|
||||
try unsafeReentrantRead { db in
|
||||
try db.dumpTables(
|
||||
tables,
|
||||
format: format,
|
||||
tableHeader: tableHeader,
|
||||
stableOrder: stableOrder,
|
||||
to: stream)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints the contents of the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.dumpContent()
|
||||
/// ```
|
||||
///
|
||||
/// This prints the database schema as well as the content of all
|
||||
/// tables. For example:
|
||||
///
|
||||
/// ```
|
||||
/// sqlite_master
|
||||
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
|
||||
///
|
||||
/// player
|
||||
/// 1,'Arthur',500
|
||||
/// 2,'Barbara',1000
|
||||
/// ```
|
||||
///
|
||||
/// > Note: Internal SQLite and GRDB schema objects are not recorded
|
||||
/// > (those with a name that starts with "sqlite_" or "grdb_").
|
||||
/// >
|
||||
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
|
||||
/// > not recorded, starting SQLite 3.37+.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - format: The output format.
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
/// console by default.
|
||||
public func dumpContent(
|
||||
format: some DumpFormat = .debug(),
|
||||
to stream: (any TextOutputStream)? = nil)
|
||||
throws
|
||||
{
|
||||
try unsafeReentrantRead { db in
|
||||
try db.dumpContent(format: format, to: stream)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints the schema of the database.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.dumpSchema()
|
||||
/// ```
|
||||
///
|
||||
/// This prints the database schema. For example:
|
||||
///
|
||||
/// ```
|
||||
/// sqlite_master
|
||||
/// CREATE TABLE player (id INTEGER PRIMARY KEY, name TEXT, score INTEGER)
|
||||
/// ```
|
||||
///
|
||||
/// > Note: Internal SQLite and GRDB schema objects are not recorded
|
||||
/// > (those with a name that starts with "sqlite_" or "grdb_").
|
||||
/// >
|
||||
/// > [Shadow tables](https://www.sqlite.org/vtab.html#xshadowname) are
|
||||
/// > not recorded, starting SQLite 3.37+.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - stream: A stream for text output, which directs output to the
|
||||
/// console by default.
|
||||
public func dumpSchema(
|
||||
to stream: (any TextOutputStream)? = nil)
|
||||
throws
|
||||
{
|
||||
try unsafeReentrantRead { db in
|
||||
try db.dumpSchema(to: stream)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
/// A type that prints database rows.
|
||||
///
|
||||
/// Types that conform to `DumpFormat` feed the printing methods such as
|
||||
/// ``DatabaseReader/dumpContent(format:to:)`` and
|
||||
/// ``Database/dumpSQL(_:format:to:)``.
|
||||
///
|
||||
/// Most built-in formats are inspired from the
|
||||
/// [output formats of the SQLite command line tool](https://sqlite.org/cli.html#changing_output_formats).
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Built-in Formats
|
||||
///
|
||||
/// - ``debug(header:separator:nullValue:)``
|
||||
/// - ``json(encoder:)``
|
||||
/// - ``line(nullValue:)``
|
||||
/// - ``list(header:separator:nullValue:)``
|
||||
/// - ``quote(header:separator:)``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``DebugDumpFormat``
|
||||
/// - ``JSONDumpFormat``
|
||||
/// - ``LineDumpFormat``
|
||||
/// - ``ListDumpFormat``
|
||||
/// - ``QuoteDumpFormat``
|
||||
/// - ``DumpStream``
|
||||
///
|
||||
/// ### Implementing a custom format
|
||||
///
|
||||
/// [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// - ``writeRow(_:statement:to:)``
|
||||
/// - ``finalize(_:statement:to:)``
|
||||
public protocol DumpFormat {
|
||||
/// Writes a row from the given statement.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - db: A connection to the database
|
||||
/// - statement: The iterated statement
|
||||
/// - stream: A stream for text output.
|
||||
mutating func writeRow(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream) throws
|
||||
|
||||
/// All rows from the statement have been printed.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - db: A connection to the database
|
||||
/// - statement: The statement that was iterated.
|
||||
/// - stream: A stream for text output.
|
||||
mutating func finalize(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
}
|
||||
|
||||
/// A TextOutputStream that prints to standard output
|
||||
struct StandardOutputStream: TextOutputStream {
|
||||
func write(_ string: String) {
|
||||
print(string, terminator: "")
|
||||
}
|
||||
}
|
||||
|
||||
/// A text output stream suited for printing database content.
|
||||
///
|
||||
/// [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
public struct DumpStream {
|
||||
var base: any TextOutputStream
|
||||
var needsMarginLine = false
|
||||
|
||||
init(_ base: (any TextOutputStream)?) {
|
||||
self.base = base ?? StandardOutputStream()
|
||||
}
|
||||
|
||||
/// Will write `"\n"` before the next non-empty string.
|
||||
public mutating func margin() {
|
||||
needsMarginLine = true
|
||||
}
|
||||
}
|
||||
|
||||
extension DumpStream: TextOutputStream {
|
||||
public mutating func write(_ string: String) {
|
||||
if needsMarginLine && !string.isEmpty {
|
||||
needsMarginLine = false
|
||||
if string.first != "\n" {
|
||||
base.write("\n")
|
||||
}
|
||||
}
|
||||
base.write(string)
|
||||
}
|
||||
}
|
||||
|
||||
extension TextOutputStream {
|
||||
mutating func writeln(_ string: String) {
|
||||
write(string)
|
||||
write("\n")
|
||||
}
|
||||
}
|
||||
|
||||
extension String {
|
||||
func leftPadding(toLength newLength: Int, withPad padString: String) -> String {
|
||||
precondition(padString.count == 1)
|
||||
if count < newLength {
|
||||
return String(repeating: padString, count: newLength - count) + self
|
||||
} else {
|
||||
let startIndex = index(startIndex, offsetBy: count - newLength)
|
||||
return String(self[startIndex...])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import Foundation
|
||||
|
||||
/// A format that prints one line per database row, suitable
|
||||
/// for debugging.
|
||||
///
|
||||
/// This format may change in future releases. It is not suitable for
|
||||
/// processing by other programs, or testing.
|
||||
///
|
||||
/// On each line, database values are separated by a separator (`|`
|
||||
/// by default).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Arthur|500
|
||||
/// // Barbara|1000
|
||||
/// // Craig|200
|
||||
/// try db.dumpRequest(Player.all(), format: .debug())
|
||||
/// ```
|
||||
public struct DebugDumpFormat: Sendable {
|
||||
/// A boolean value indicating if column labels are printed as the first
|
||||
/// line of output.
|
||||
public var header: Bool
|
||||
|
||||
/// The separator between values.
|
||||
public var separator: String
|
||||
|
||||
/// The string to print for NULL values.
|
||||
public var nullValue: String
|
||||
|
||||
private var firstRow = true
|
||||
|
||||
/// Creates a `DebugDumpFormat`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - header: A boolean value indicating if column labels are printed
|
||||
/// as the first line of output.
|
||||
/// - separator: The separator between values.
|
||||
/// - nullValue: The string to print for NULL values.
|
||||
public init(
|
||||
header: Bool = false,
|
||||
separator: String = "|",
|
||||
nullValue: String = "")
|
||||
{
|
||||
self.header = header
|
||||
self.separator = separator
|
||||
self.nullValue = nullValue
|
||||
}
|
||||
}
|
||||
|
||||
extension DebugDumpFormat: DumpFormat {
|
||||
public mutating func writeRow(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
if firstRow {
|
||||
firstRow = false
|
||||
if header {
|
||||
stream.writeln(statement.columnNames.joined(separator: separator))
|
||||
}
|
||||
}
|
||||
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
var first = true
|
||||
for index in 0..<sqlite3_column_count(sqliteStatement) {
|
||||
// Don't log GRDB columns
|
||||
let column = String(cString: sqlite3_column_name(sqliteStatement, index))
|
||||
if column.starts(with: "grdb_") { continue }
|
||||
|
||||
if first {
|
||||
first = false
|
||||
} else {
|
||||
stream.write(separator)
|
||||
}
|
||||
|
||||
stream.write(formattedValue(db, in: sqliteStatement, at: index))
|
||||
}
|
||||
stream.write("\n")
|
||||
}
|
||||
|
||||
public mutating func finalize(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
firstRow = true
|
||||
}
|
||||
|
||||
private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) -> String {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
return nullValue
|
||||
|
||||
case SQLITE_INTEGER:
|
||||
return Int64(sqliteStatement: sqliteStatement, index: index).description
|
||||
|
||||
case SQLITE_FLOAT:
|
||||
return Double(sqliteStatement: sqliteStatement, index: index).description
|
||||
|
||||
case SQLITE_BLOB:
|
||||
let data = Data(sqliteStatement: sqliteStatement, index: index)
|
||||
if let string = String(data: data, encoding: .utf8) {
|
||||
return string
|
||||
} else if data.count == 16, let blob = sqlite3_column_blob(sqliteStatement, index) {
|
||||
let uuid = UUID(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
|
||||
return uuid.uuidString
|
||||
} else {
|
||||
return try! data.sqlExpression.quotedSQL(db)
|
||||
}
|
||||
|
||||
case SQLITE_TEXT:
|
||||
return String(sqliteStatement: sqliteStatement, index: index)
|
||||
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DumpFormat where Self == DebugDumpFormat {
|
||||
/// A format that prints one line per database row, suitable
|
||||
/// for debugging.
|
||||
///
|
||||
/// This format may change in future releases. It is not suitable for
|
||||
/// processing by other programs, or testing.
|
||||
///
|
||||
/// On each line, database values are separated by a separator (`|`
|
||||
/// by default).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Arthur|500
|
||||
/// // Barbara|1000
|
||||
/// // Craig|200
|
||||
/// try db.dumpRequest(Player.all(), format: .debug())
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - header: A boolean value indicating if column labels are printed
|
||||
/// as the first line of output.
|
||||
/// - separator: The separator between values.
|
||||
/// - nullValue: The string to print for NULL values.
|
||||
public static func debug(
|
||||
header: Bool = false,
|
||||
separator: String = "|",
|
||||
nullValue: String = "")
|
||||
-> Self
|
||||
{
|
||||
DebugDumpFormat(header: header, separator: separator, nullValue: nullValue)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
import Foundation
|
||||
|
||||
/// A format that prints database rows as a JSON array.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // [{"name":"Arthur","score":500},
|
||||
/// // {"name":"Barbara","score":1000}]
|
||||
/// try db.dumpRequest(Player.all(), format: .json())
|
||||
/// ```
|
||||
///
|
||||
/// For a pretty-printed output, customize the JSON encoder:
|
||||
///
|
||||
/// ```swift
|
||||
/// // [
|
||||
/// // {
|
||||
/// // "name": "Arthur",
|
||||
/// // "score": 500
|
||||
/// // },
|
||||
/// // {
|
||||
/// // "name": "Barbara",
|
||||
/// // "score": 1000
|
||||
/// // }
|
||||
/// // ]
|
||||
/// let encoder = JSONDumpFormat.defaultEncoder
|
||||
/// encoder.outputFormatting = .prettyPrinted
|
||||
/// try db.dumpRequest(Player.all(), format: .json(encoder))
|
||||
/// ```
|
||||
public struct JSONDumpFormat: Sendable {
|
||||
/// The default `JSONEncoder` for database values.
|
||||
///
|
||||
/// It is configured so that blob values (`Data`) are encoded in the
|
||||
/// base64 format, and Non-conforming floats are encoded as "inf",
|
||||
/// "-inf" and "nan".
|
||||
///
|
||||
/// It uses the output formatting option
|
||||
/// `JSONEncoder.OutputFormatting.withoutEscapingSlashes` when available.
|
||||
///
|
||||
/// Modifying the returned encoder does not affect any encoder returned
|
||||
/// by future calls to this method. It is always safe to use the
|
||||
/// returned encoder as a starting point for additional customization.
|
||||
public static var defaultEncoder: JSONEncoder {
|
||||
// This encoder MUST NOT CHANGE, because some people rely on this format.
|
||||
let encoder = JSONEncoder()
|
||||
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) {
|
||||
encoder.outputFormatting = .withoutEscapingSlashes
|
||||
}
|
||||
encoder.nonConformingFloatEncodingStrategy = .convertToString(
|
||||
positiveInfinity: "inf",
|
||||
negativeInfinity: "-inf",
|
||||
nan: "nan")
|
||||
encoder.dataEncodingStrategy = .base64
|
||||
return encoder
|
||||
}
|
||||
|
||||
/// The JSONEncoder that formats individual database values.
|
||||
public var encoder: JSONEncoder
|
||||
|
||||
var firstRow = true
|
||||
|
||||
/// Creates a `JSONDumpFormat`.
|
||||
///
|
||||
/// - Parameter encoder: The JSONEncoder that formats individual
|
||||
/// database values. If the outputFormatting` options contain
|
||||
/// `.prettyPrinted`, the printed array has one value per line.
|
||||
public init(encoder: JSONEncoder = JSONDumpFormat.defaultEncoder) {
|
||||
self.encoder = encoder
|
||||
}
|
||||
}
|
||||
|
||||
extension JSONDumpFormat: DumpFormat {
|
||||
public mutating func writeRow(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
throws {
|
||||
if firstRow {
|
||||
firstRow = false
|
||||
stream.write("[")
|
||||
if encoder.outputFormatting.contains(.prettyPrinted) {
|
||||
stream.write("\n")
|
||||
}
|
||||
} else {
|
||||
stream.write(",\n")
|
||||
}
|
||||
|
||||
if encoder.outputFormatting.contains(.prettyPrinted) {
|
||||
stream.write(" ")
|
||||
}
|
||||
stream.write("{")
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
var first = true
|
||||
for index in 0..<sqlite3_column_count(sqliteStatement) {
|
||||
// Don't log GRDB columns
|
||||
let column = String(cString: sqlite3_column_name(sqliteStatement, index))
|
||||
if column.starts(with: "grdb_") {
|
||||
continue
|
||||
}
|
||||
|
||||
if first {
|
||||
first = false
|
||||
} else {
|
||||
stream.write(",")
|
||||
}
|
||||
|
||||
if encoder.outputFormatting.contains(.prettyPrinted) {
|
||||
stream.write("\n ")
|
||||
}
|
||||
try stream.write(formattedValue(column))
|
||||
stream.write(":")
|
||||
try stream.write(formattedValue(db, in: sqliteStatement, at: index))
|
||||
}
|
||||
if encoder.outputFormatting.contains(.prettyPrinted) {
|
||||
stream.write("\n ")
|
||||
}
|
||||
stream.write("}")
|
||||
}
|
||||
|
||||
public mutating func finalize(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
if firstRow {
|
||||
if !statement.columnNames.isEmpty {
|
||||
stream.writeln("[]")
|
||||
}
|
||||
} else {
|
||||
if encoder.outputFormatting.contains(.prettyPrinted) {
|
||||
stream.write("\n")
|
||||
}
|
||||
stream.writeln("]")
|
||||
}
|
||||
firstRow = true
|
||||
}
|
||||
|
||||
private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) throws -> String {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
return "null"
|
||||
|
||||
case SQLITE_INTEGER:
|
||||
return try formattedValue(Int64(sqliteStatement: sqliteStatement, index: index))
|
||||
|
||||
case SQLITE_FLOAT:
|
||||
return try formattedValue(Double(sqliteStatement: sqliteStatement, index: index))
|
||||
|
||||
case SQLITE_BLOB:
|
||||
return try formattedValue(Data(sqliteStatement: sqliteStatement, index: index))
|
||||
|
||||
case SQLITE_TEXT:
|
||||
return try formattedValue(String(sqliteStatement: sqliteStatement, index: index))
|
||||
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
private func formattedValue(_ value: some Encodable) throws -> String {
|
||||
let data = try encoder.encode(value)
|
||||
guard let string = String(data: data, encoding: .utf8) else {
|
||||
throw EncodingError.invalidValue(data, .init(codingPath: [], debugDescription: "Invalid JSON data"))
|
||||
}
|
||||
return string
|
||||
}
|
||||
}
|
||||
|
||||
extension DumpFormat where Self == JSONDumpFormat {
|
||||
/// A format that prints database rows as a JSON array.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // [{"name":"Arthur","score":500},
|
||||
/// // {"name":"Barbara","score":1000}]
|
||||
/// try db.dumpRequest(Player.all(), format: .json())
|
||||
/// ```
|
||||
///
|
||||
/// For a pretty-printed output, customize the JSON encoder:
|
||||
///
|
||||
/// ```swift
|
||||
/// // [
|
||||
/// // {
|
||||
/// // "name": "Arthur",
|
||||
/// // "score": 500
|
||||
/// // },
|
||||
/// // {
|
||||
/// // "name": "Barbara",
|
||||
/// // "score": 1000
|
||||
/// // }
|
||||
/// // ]
|
||||
/// let encoder = JSONDumpFormat.defaultEncoder
|
||||
/// encoder.outputFormatting = .prettyPrinted
|
||||
/// try db.dumpRequest(Player.all(), format: .json(encoder))
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter encoder: The JSONEncoder that formats individual
|
||||
/// database values. If the outputFormatting` options contain
|
||||
/// `.prettyPrinted`, the printed array has one value per line.
|
||||
public static func json(encoder: JSONEncoder = JSONDumpFormat.defaultEncoder) -> Self {
|
||||
JSONDumpFormat(encoder: encoder)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import Foundation
|
||||
|
||||
/// A format that prints one line per database value. All blob values
|
||||
/// are interpreted as strings.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // name = Arthur
|
||||
/// // score = 500
|
||||
/// //
|
||||
/// // name = Barbara
|
||||
/// // score = 1000
|
||||
/// try db.dumpRequest(Player.all(), format: .line())
|
||||
/// ```
|
||||
public struct LineDumpFormat: Sendable {
|
||||
/// The string to print for NULL values.
|
||||
public var nullValue: String
|
||||
|
||||
var firstRow = true
|
||||
|
||||
/// Creates a `LineDumpFormat`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - nullValue: The string to print for NULL values.
|
||||
public init(
|
||||
nullValue: String = "")
|
||||
{
|
||||
self.nullValue = nullValue
|
||||
}
|
||||
}
|
||||
|
||||
extension LineDumpFormat: DumpFormat {
|
||||
public mutating func writeRow(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
var lines: [(column: String, value: String)] = []
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
for index in 0..<sqlite3_column_count(sqliteStatement) {
|
||||
// Don't log GRDB columns
|
||||
let column = String(cString: sqlite3_column_name(sqliteStatement, index))
|
||||
if column.starts(with: "grdb_") { continue }
|
||||
|
||||
lines.append((
|
||||
column: column,
|
||||
value: formattedValue(db, in: sqliteStatement, at: index)))
|
||||
}
|
||||
|
||||
if lines.isEmpty { return }
|
||||
|
||||
if firstRow {
|
||||
firstRow = false
|
||||
} else {
|
||||
stream.write("\n")
|
||||
}
|
||||
|
||||
let columnWidth = lines.map(\.column.count).max()!
|
||||
for line in lines {
|
||||
stream.write(line.column.leftPadding(toLength: columnWidth, withPad: " "))
|
||||
stream.write(" = ")
|
||||
stream.writeln(line.value)
|
||||
}
|
||||
}
|
||||
|
||||
public mutating func finalize(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
if firstRow == false {
|
||||
stream.margin()
|
||||
}
|
||||
firstRow = true
|
||||
}
|
||||
|
||||
func formattedValue(
|
||||
_ db: Database,
|
||||
in sqliteStatement: SQLiteStatement,
|
||||
at index: CInt)
|
||||
-> String
|
||||
{
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
return nullValue
|
||||
|
||||
case SQLITE_INTEGER:
|
||||
return Int64(sqliteStatement: sqliteStatement, index: index).description
|
||||
|
||||
case SQLITE_FLOAT:
|
||||
return Double(sqliteStatement: sqliteStatement, index: index).description
|
||||
|
||||
case SQLITE_BLOB, SQLITE_TEXT:
|
||||
return String(sqliteStatement: sqliteStatement, index: index)
|
||||
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DumpFormat where Self == LineDumpFormat {
|
||||
/// A format that prints one line per database value. All blob values
|
||||
/// are interpreted as strings.
|
||||
///
|
||||
/// On each line, database values are separated by a separator (`|`
|
||||
/// by default). Blob values are interpreted as UTF8 strings.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // name = Arthur
|
||||
/// // score = 500
|
||||
/// //
|
||||
/// // name = Barbara
|
||||
/// // score = 1000
|
||||
/// try db.dumpRequest(Player.all(), format: .line())
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - nullValue: The string to print for NULL values.
|
||||
public static func line(
|
||||
nullValue: String = "")
|
||||
-> Self
|
||||
{
|
||||
LineDumpFormat(nullValue: nullValue)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import Foundation
|
||||
|
||||
/// A format that prints one line per database row. All blob values
|
||||
/// are interpreted as strings.
|
||||
///
|
||||
/// On each line, database values are separated by a separator (`|`
|
||||
/// by default). Blob values are interpreted as UTF8 strings.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Arthur|500
|
||||
/// // Barbara|1000
|
||||
/// // Craig|200
|
||||
/// try db.dumpRequest(Player.all(), format: .list())
|
||||
/// ```
|
||||
public struct ListDumpFormat: Sendable {
|
||||
/// A boolean value indicating if column labels are printed as the first
|
||||
/// line of output.
|
||||
public var header: Bool
|
||||
|
||||
/// The separator between values.
|
||||
public var separator: String
|
||||
|
||||
/// The string to print for NULL values.
|
||||
public var nullValue: String
|
||||
|
||||
private var firstRow = true
|
||||
|
||||
/// Creates a `ListDumpFormat`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - header: A boolean value indicating if column labels are printed
|
||||
/// as the first line of output.
|
||||
/// - separator: The separator between values.
|
||||
/// - nullValue: The string to print for NULL values.
|
||||
public init(
|
||||
header: Bool = false,
|
||||
separator: String = "|",
|
||||
nullValue: String = "")
|
||||
{
|
||||
self.header = header
|
||||
self.separator = separator
|
||||
self.nullValue = nullValue
|
||||
}
|
||||
}
|
||||
|
||||
extension ListDumpFormat: DumpFormat {
|
||||
public mutating func writeRow(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
if firstRow {
|
||||
firstRow = false
|
||||
if header {
|
||||
stream.writeln(statement.columnNames.joined(separator: separator))
|
||||
}
|
||||
}
|
||||
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
var first = true
|
||||
for index in 0..<sqlite3_column_count(sqliteStatement) {
|
||||
// Don't log GRDB columns
|
||||
let column = String(cString: sqlite3_column_name(sqliteStatement, index))
|
||||
if column.starts(with: "grdb_") { continue }
|
||||
|
||||
if first {
|
||||
first = false
|
||||
} else {
|
||||
stream.write(separator)
|
||||
}
|
||||
|
||||
stream.write(formattedValue(db, in: sqliteStatement, at: index))
|
||||
}
|
||||
stream.write("\n")
|
||||
}
|
||||
|
||||
public mutating func finalize(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
firstRow = true
|
||||
}
|
||||
|
||||
func formattedValue(
|
||||
_ db: Database,
|
||||
in sqliteStatement: SQLiteStatement,
|
||||
at index: CInt)
|
||||
-> String
|
||||
{
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
return nullValue
|
||||
|
||||
case SQLITE_INTEGER:
|
||||
return Int64(sqliteStatement: sqliteStatement, index: index).description
|
||||
|
||||
case SQLITE_FLOAT:
|
||||
return Double(sqliteStatement: sqliteStatement, index: index).description
|
||||
|
||||
case SQLITE_BLOB, SQLITE_TEXT:
|
||||
return String(sqliteStatement: sqliteStatement, index: index)
|
||||
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DumpFormat where Self == ListDumpFormat {
|
||||
/// A format that prints one line per database row. All blob values
|
||||
/// are interpreted as strings.
|
||||
///
|
||||
/// On each line, database values are separated by a separator (`|`
|
||||
/// by default). Blob values are interpreted as UTF8 strings.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Arthur|500
|
||||
/// // Barbara|1000
|
||||
/// // Craig|200
|
||||
/// try db.dumpRequest(Player.all(), format: .list())
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - header: A boolean value indicating if column labels are printed
|
||||
/// as the first line of output.
|
||||
/// - separator: The separator between values.
|
||||
/// - nullValue: The string to print for NULL values.
|
||||
public static func list(
|
||||
header: Bool = false,
|
||||
separator: String = "|",
|
||||
nullValue: String = "")
|
||||
-> Self
|
||||
{
|
||||
ListDumpFormat(header: header, separator: separator, nullValue: nullValue)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/// A format that prints one line per database row, formatting values
|
||||
/// as SQL literals.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // 'Arthur',500
|
||||
/// // 'Barbara',1000
|
||||
/// // 'Craig',200
|
||||
/// try db.dumpRequest(Player.all(), format: .quote())
|
||||
/// ```
|
||||
public struct QuoteDumpFormat: Sendable {
|
||||
/// A boolean value indicating if column labels are printed as the first
|
||||
/// line of output.
|
||||
public var header: Bool
|
||||
|
||||
/// The separator between values.
|
||||
public var separator: String
|
||||
|
||||
var firstRow = true
|
||||
|
||||
/// Creates a `QuoteDumpFormat`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - header: A boolean value indicating if column labels are printed
|
||||
/// as the first line of output.
|
||||
/// - separator: The separator between values.
|
||||
public init(
|
||||
header: Bool = false,
|
||||
separator: String = ",")
|
||||
{
|
||||
self.header = header
|
||||
self.separator = separator
|
||||
}
|
||||
}
|
||||
|
||||
extension QuoteDumpFormat: DumpFormat {
|
||||
public mutating func writeRow(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
if firstRow {
|
||||
firstRow = false
|
||||
if header {
|
||||
stream.writeln(statement.columnNames
|
||||
.map { try! $0.sqlExpression.quotedSQL(db) }
|
||||
.joined(separator: separator))
|
||||
}
|
||||
}
|
||||
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
var first = true
|
||||
for index in 0..<sqlite3_column_count(sqliteStatement) {
|
||||
// Don't log GRDB columns
|
||||
let column = String(cString: sqlite3_column_name(sqliteStatement, index))
|
||||
if column.starts(with: "grdb_") { continue }
|
||||
|
||||
if first {
|
||||
first = false
|
||||
} else {
|
||||
stream.write(separator)
|
||||
}
|
||||
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
try! stream.write(dbValue.sqlExpression.quotedSQL(db))
|
||||
}
|
||||
|
||||
stream.write("\n")
|
||||
}
|
||||
|
||||
public mutating func finalize(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
firstRow = true
|
||||
}
|
||||
}
|
||||
|
||||
extension DumpFormat where Self == QuoteDumpFormat {
|
||||
/// A format that prints one line per database row, formatting values
|
||||
/// as SQL literals.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // 'Arthur',500
|
||||
/// // 'Barbara',1000
|
||||
/// // 'Craig',200
|
||||
/// try db.dumpRequest(Player.all(), format: .quote())
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - header: A boolean value indicating if column labels are printed
|
||||
/// as the first line of output.
|
||||
/// - separator: The separator between values.
|
||||
public static func quote(header: Bool = false, separator: String = ",") -> Self {
|
||||
QuoteDumpFormat(header: header, separator: separator)
|
||||
}
|
||||
}
|
||||
+6
-1
@@ -29,7 +29,7 @@
|
||||
/// - ``tokenize(_:withTokenizer:)``
|
||||
public struct FTS3 {
|
||||
/// Options for Latin script characters.
|
||||
public enum Diacritics {
|
||||
public enum Diacritics: Sendable {
|
||||
/// Do not remove diacritics from Latin script characters. This option
|
||||
/// matches the `remove_diacritics=0` tokenizer argument.
|
||||
///
|
||||
@@ -183,3 +183,8 @@ public final class FTS3TableDefinition {
|
||||
columns.append(name)
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `FTS3TableDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FTS3TableDefinition: Sendable { }
|
||||
@@ -16,7 +16,7 @@
|
||||
/// - ``init(matchingAllTokensIn:)``
|
||||
/// - ``init(matchingAnyTokenIn:)``
|
||||
/// - ``init(matchingPhrase:)``
|
||||
public struct FTS3Pattern {
|
||||
public struct FTS3Pattern: Sendable {
|
||||
/// The raw pattern string.
|
||||
///
|
||||
/// It is guaranteed to be a valid FTS3/4 pattern.
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
/// - ``simple``
|
||||
/// - ``unicode61(diacritics:separators:tokenCharacters:)``
|
||||
/// - ``FTS3/Diacritics``
|
||||
public struct FTS3TokenizerDescriptor {
|
||||
public struct FTS3TokenizerDescriptor: Sendable {
|
||||
let name: String
|
||||
let arguments: [String]
|
||||
|
||||
|
||||
@@ -313,6 +313,11 @@ public final class FTS4TableDefinition {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `FTS4TableDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FTS4TableDefinition: Sendable { }
|
||||
|
||||
/// Describes a column in an ``FTS4`` virtual table.
|
||||
///
|
||||
/// You get instances of `FTS4ColumnDefinition` when you create an ``FTS4``
|
||||
@@ -377,6 +382,11 @@ public final class FTS4ColumnDefinition {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `FTS4ColumnDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FTS4ColumnDefinition: Sendable { }
|
||||
|
||||
extension Database {
|
||||
/// Deletes the synchronization triggers for a synchronized FTS4 table.
|
||||
///
|
||||
|
||||
+11
-1
@@ -44,7 +44,7 @@ public struct FTS5 {
|
||||
/// tokenizer argument.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#unicode61_tokenizer>
|
||||
public enum Diacritics {
|
||||
public enum Diacritics: Sendable {
|
||||
/// Do not remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=0" tokenizer argument.
|
||||
case keep
|
||||
@@ -492,6 +492,11 @@ public final class FTS5TableDefinition {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `FTS5TableDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FTS5TableDefinition: Sendable { }
|
||||
|
||||
/// Describes a column in an ``FTS5`` virtual table.
|
||||
///
|
||||
/// You get instances of `FTS5ColumnDefinition` when you create an ``FTS5``
|
||||
@@ -534,6 +539,11 @@ public final class FTS5ColumnDefinition {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `FTS5ColumnDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FTS5ColumnDefinition: Sendable { }
|
||||
|
||||
extension Column {
|
||||
/// The ``FTS5`` rank column.
|
||||
public static let rank = Column("rank")
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
/// - ``init(matchingAnyTokenIn:)``
|
||||
/// - ``init(matchingPhrase:)``
|
||||
/// - ``init(matchingPrefixPhrase:)``
|
||||
public struct FTS5Pattern {
|
||||
public struct FTS5Pattern: Sendable {
|
||||
|
||||
/// The raw pattern string.
|
||||
///
|
||||
|
||||
@@ -16,7 +16,7 @@ public typealias FTS5TokenCallback = @convention(c) (
|
||||
/// The reason why FTS5 is requesting tokenization.
|
||||
///
|
||||
/// See the `FTS5_TOKENIZE_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
|
||||
public struct FTS5Tokenization: OptionSet {
|
||||
public struct FTS5Tokenization: OptionSet, Sendable {
|
||||
public let rawValue: CInt
|
||||
|
||||
public init(rawValue: CInt) {
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
/// ### Instantiating Tokenizers
|
||||
///
|
||||
/// - ``Database/makeTokenizer(_:)``
|
||||
public struct FTS5TokenizerDescriptor {
|
||||
public struct FTS5TokenizerDescriptor: Sendable {
|
||||
/// The tokenizer components.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -4,7 +4,7 @@ import Foundation
|
||||
/// Flags that tell SQLite how to register a token.
|
||||
///
|
||||
/// See the `FTS5_TOKEN_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
|
||||
public struct FTS5TokenFlags: OptionSet {
|
||||
public struct FTS5TokenFlags: OptionSet, Sendable {
|
||||
public let rawValue: CInt
|
||||
|
||||
public init(rawValue: CInt) {
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
/// A JSON column in a database table.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// `JSONColumn` has benefits over ``Column`` for database columns that
|
||||
/// contain JSON strings.
|
||||
///
|
||||
/// It behaves like a regular `Column`, with all extra conveniences and
|
||||
/// behaviors of ``SQLJSONExpressible``.
|
||||
///
|
||||
/// For example, the sample code below directly accesses the "countryCode"
|
||||
/// key of the "address" JSON column:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: Codable {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var address: Address
|
||||
/// }
|
||||
///
|
||||
/// struct Address: Codable {
|
||||
/// var street: String
|
||||
/// var city: String
|
||||
/// var countryCode: String
|
||||
/// }
|
||||
///
|
||||
/// extension Player: FetchableRecord, PersistableRecord {
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let address = JSONColumn(CodingKeys.address) // JSONColumn!
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // In a real app, table creation should happen in a migration.
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.autoIncrementedPrimaryKey("id")
|
||||
/// t.column("name", .text).notNull()
|
||||
/// t.column("address", .jsonText).notNull()
|
||||
/// }
|
||||
///
|
||||
/// // Fetch all country codes
|
||||
/// // SELECT DISTINCT address ->> 'countryCode' FROM player
|
||||
/// let countryCodes: [String] = try Player
|
||||
/// .select(Player.Columns.address["countryCode"], as: String.self)
|
||||
/// .distinct()
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// > Tip: When you can not create a `JSONColumn`, you'll get the same
|
||||
/// > convenient access to JSON subcomponents
|
||||
/// > with ``SQLSpecificExpressible/asJSON``.
|
||||
/// >
|
||||
/// > For example, the above sample can be adapted as below:
|
||||
/// >
|
||||
/// > ```swift
|
||||
/// > extension Player: FetchableRecord, PersistableRecord {
|
||||
/// > // That's another valid way to define columns.
|
||||
/// > // But we don't have any JSONColumn this time.
|
||||
/// > enum Columns: String, ColumnExpression {
|
||||
/// > case id, name, address
|
||||
/// > }
|
||||
/// > }
|
||||
/// >
|
||||
/// > try dbQueue.write { db in
|
||||
/// > // Fetch all country codes
|
||||
/// > // SELECT DISTINCT address ->> 'countryCode' FROM player
|
||||
/// > let countryCodes: [String] = try Player
|
||||
/// > .select(Player.Columns.address.asJSON["countryCode"], as: String.self)
|
||||
/// > .distinct()
|
||||
/// > .fetchAll(db)
|
||||
/// > }
|
||||
/// > ```
|
||||
public struct JSONColumn: ColumnExpression, SQLJSONExpressible, Sendable {
|
||||
public var name: String
|
||||
|
||||
/// Creates a `JSONColumn` given its name.
|
||||
///
|
||||
/// The name should be unqualified, such as `"score"`. Qualified name such
|
||||
/// as `"player.score"` are unsupported.
|
||||
public init(_ name: String) {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
/// Creates a `JSONColumn` given a `CodingKey`.
|
||||
public init(_ codingKey: some CodingKey) {
|
||||
self.name = codingKey.stringValue
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
/// A type of SQL expression that is interpreted as a JSON value.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// JSON values that conform to `SQLJSONExpressible` have two purposes:
|
||||
///
|
||||
/// - They provide Swift APIs for accessing their JSON subcomponents at
|
||||
/// the SQL level.
|
||||
///
|
||||
/// - When used in a JSON-building function such as
|
||||
/// ``Database/jsonArray(_:)-8xxe3`` or ``Database/jsonObject(_:)``,
|
||||
/// they are parsed and interpreted as JSON, not as plain strings.
|
||||
///
|
||||
/// To build a JSON value, create a ``JSONColumn``, or call the
|
||||
/// ``SQLSpecificExpressible/asJSON`` property of any
|
||||
/// other expression.
|
||||
///
|
||||
/// For example, here are some JSON values:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON columns:
|
||||
/// JSONColumn("info")
|
||||
/// Column("info").asJSON
|
||||
///
|
||||
/// // The JSON array [1, 2, 3]:
|
||||
/// "[1, 2, 3]".databaseValue.asJSON
|
||||
///
|
||||
/// // A JSON value that will trigger a
|
||||
/// // "malformed JSON" SQLite error when
|
||||
/// // parsed by SQLite:
|
||||
/// "{foo".databaseValue.asJSON
|
||||
/// ```
|
||||
///
|
||||
/// The expressions below are not JSON values:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A plain column:
|
||||
/// Column("info")
|
||||
///
|
||||
/// // Plain strings:
|
||||
/// "[1, 2, 3]"
|
||||
/// "{foo"
|
||||
/// ```
|
||||
///
|
||||
/// ## Access JSON subcomponents
|
||||
///
|
||||
/// JSON values provide access to the [`->` and `->>` SQL operators](https://www.sqlite.org/json1.html)
|
||||
/// and other SQLite JSON functions:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT info ->> 'firstName' FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select(info["firstName"], as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT info ->> 'address' FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let address = try Player
|
||||
/// .select(info["address"], as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
/// ## Build JSON objects and arrays from JSON values
|
||||
///
|
||||
/// When used in a JSON-building function such as
|
||||
/// ``Database/jsonArray(_:)-8xxe3`` or ``Database/jsonObject(_:)-5iswr``,
|
||||
/// JSON values are parsed and interpreted as JSON, not as plain strings.
|
||||
///
|
||||
/// In the example below, we can see how the `JSONColumn` is interpreted as
|
||||
/// JSON, while the `Column` with the same name is interpreted as a
|
||||
/// plain string:
|
||||
///
|
||||
/// ```swift
|
||||
/// let elements: [any SQLExpressible] = [
|
||||
/// JSONColumn("address"),
|
||||
/// Column("address"),
|
||||
/// ]
|
||||
///
|
||||
/// let array = Database.jsonArray(elements)
|
||||
///
|
||||
/// // SELECT JSON_ARRAY(JSON(address), address) FROM player
|
||||
/// // → '[{"country":"FR"},"{\"country\":\"FR\"}"]'
|
||||
/// // <--- object ---> <------ string ------>
|
||||
/// let json = try Player
|
||||
/// .select(array, as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Accessing JSON subcomponents
|
||||
///
|
||||
/// - ``subscript(_:)``
|
||||
/// - ``jsonExtract(atPath:)``
|
||||
/// - ``jsonExtract(atPaths:)``
|
||||
/// - ``jsonRepresentation(atPath:)``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnySQLJSONExpressible``
|
||||
public protocol SQLJSONExpressible: SQLSpecificExpressible { }
|
||||
|
||||
extension ColumnExpression where Self: SQLJSONExpressible {
|
||||
/// Returns an SQL column that is interpreted as a JSON value.
|
||||
public var sqlExpression: SQLExpression {
|
||||
.column(name).withPreferredJSONInterpretation(.jsonValue)
|
||||
}
|
||||
}
|
||||
|
||||
// This type only grants access to `SQLJSONExpressible` apis. The fact that
|
||||
// it is a JSON value is embedded in its
|
||||
// `sqlExpression.preferredJSONInterpretation`.
|
||||
/// A type-erased ``SQLJSONExpressible``.
|
||||
public struct AnySQLJSONExpressible: SQLJSONExpressible {
|
||||
/// An SQL expression that is interpreted as a JSON value.
|
||||
public let sqlExpression: SQLExpression
|
||||
|
||||
public init(_ base: some SQLJSONExpressible) {
|
||||
self.init(sqlExpression: base.sqlExpression)
|
||||
}
|
||||
|
||||
/// - Precondition: `sqlExpression` is a JSON value
|
||||
init(sqlExpression: SQLExpression) {
|
||||
assert(sqlExpression.preferredJSONInterpretation == .jsonValue)
|
||||
self.sqlExpression = sqlExpression
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLSpecificExpressible {
|
||||
/// Returns an expression that is interpreted as a JSON value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = Column("info").asJSON
|
||||
///
|
||||
/// // SELECT info ->> 'firstName' FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select(info["firstName"], as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
/// For more information, see ``SQLJSONExpressible``.
|
||||
public var asJSON: AnySQLJSONExpressible {
|
||||
AnySQLJSONExpressible(sqlExpression: sqlExpression.withPreferredJSONInterpretation(.jsonValue))
|
||||
}
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
extension SQLJSONExpressible {
|
||||
/// The `->>` SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT info ->> 'firstName' FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select(info["firstName"], as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT info ->> 'address' FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let address = try Player
|
||||
/// .select(info["address"], as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
|
||||
///
|
||||
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
|
||||
/// or an JSON object field label, or an array index.
|
||||
public subscript(_ path: some SQLExpressible) -> SQLExpression {
|
||||
.binary(.jsonExtractSQL, sqlExpression, path.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `JSON_EXTRACT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.address') FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let address = try Player
|
||||
/// .select(info.jsonExtract(atPath: "$.address"), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
|
||||
///
|
||||
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public func jsonExtract(atPath path: some SQLExpressible) -> SQLExpression {
|
||||
Database.jsonExtract(self, atPath: path)
|
||||
}
|
||||
|
||||
/// The `JSON_EXTRACT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player
|
||||
/// // → '["Arthur","Miller"]'
|
||||
/// let nameComponents = try Player
|
||||
/// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
|
||||
///
|
||||
/// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public func jsonExtract<C>(atPaths paths: C) -> SQLExpression
|
||||
where C: Collection, C.Element: SQLExpressible
|
||||
{
|
||||
Database.jsonExtract(self, atPaths: paths)
|
||||
}
|
||||
|
||||
/// Returns a valid JSON string with the `->` SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT info -> 'firstName' FROM player
|
||||
/// // → '"Arthur"'
|
||||
/// let name = try Player
|
||||
/// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT info -> 'address' FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let name = try Player
|
||||
/// .select(info.jsonRepresentation(atPath: "address"), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
|
||||
///
|
||||
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
|
||||
/// or an JSON object field label, or an array index.
|
||||
public func jsonRepresentation(atPath path: some SQLExpressible) -> SQLExpression {
|
||||
.binary(.jsonExtractJSON, sqlExpression, path.sqlExpression)
|
||||
}
|
||||
}
|
||||
#else
|
||||
extension SQLJSONExpressible {
|
||||
/// The `->>` SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT info ->> 'firstName' FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select(info["firstName"], as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT info ->> 'address' FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let address = try Player
|
||||
/// .select(info["address"], as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
|
||||
///
|
||||
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
|
||||
/// or an JSON object field label, or an array index.
|
||||
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
|
||||
public subscript(_ path: some SQLExpressible) -> SQLExpression {
|
||||
.binary(.jsonExtractSQL, sqlExpression, path.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `JSON_EXTRACT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.address') FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let address = try Player
|
||||
/// .select(info.jsonExtract(atPath: "$.address"), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
|
||||
///
|
||||
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public func jsonExtract(atPath path: some SQLExpressible) -> SQLExpression {
|
||||
Database.jsonExtract(self, atPath: path)
|
||||
}
|
||||
|
||||
/// The `JSON_EXTRACT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player
|
||||
/// // → '["Arthur","Miller"]'
|
||||
/// let nameComponents = try Player
|
||||
/// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
|
||||
///
|
||||
/// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public func jsonExtract<C>(atPaths paths: C) -> SQLExpression
|
||||
where C: Collection, C.Element: SQLExpressible
|
||||
{
|
||||
Database.jsonExtract(self, atPaths: paths)
|
||||
}
|
||||
|
||||
/// Returns a valid JSON string with the `->` SQL operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT info -> 'firstName' FROM player
|
||||
/// // → '"Arthur"'
|
||||
/// let name = try Player
|
||||
/// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT info -> 'address' FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let name = try Player
|
||||
/// .select(info.jsonRepresentation(atPath: "address"), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jptr>
|
||||
///
|
||||
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
|
||||
/// or an JSON object field label, or an array index.
|
||||
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
|
||||
public func jsonRepresentation(atPath path: some SQLExpressible) -> SQLExpression {
|
||||
.binary(.jsonExtractJSON, sqlExpression, path.sqlExpression)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Enable when those apis are ready.
|
||||
// extension ColumnExpression where Self: SQLJSONExpressible {
|
||||
// /// Updates a columns with the `JSON_PATCH` SQL function.
|
||||
// ///
|
||||
// /// For example:
|
||||
// ///
|
||||
// /// ```swift
|
||||
// /// // UPDATE player SET address = JSON_PATCH(address, '{"country": "FR"}')
|
||||
// /// try Player.updateAll(db, [
|
||||
// /// JSONColumn("address").jsonPatch(#"{"country": "FR"}"#)
|
||||
// /// ])
|
||||
// /// ```
|
||||
// ///
|
||||
// /// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
|
||||
// @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
// public func jsonPatch(
|
||||
// with patch: some SQLExpressible)
|
||||
// -> ColumnAssignment
|
||||
// {
|
||||
// .init(columnName: name, value: Database.jsonPatch(self, with: patch))
|
||||
// }
|
||||
//
|
||||
// /// Updates a columns with the `JSON_REMOVE` SQL function.
|
||||
// ///
|
||||
// /// For example:
|
||||
// ///
|
||||
// /// ```swift
|
||||
// /// // UPDATE player SET address = JSON_REMOVE(address, '$.country')
|
||||
// /// try Player.updateAll(db, [
|
||||
// /// JSONColumn("address").jsonRemove(atPath: "$.country")
|
||||
// /// ])
|
||||
// /// ```
|
||||
// ///
|
||||
// /// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
|
||||
// ///
|
||||
// /// - Parameters:
|
||||
// /// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
// @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
// public func jsonRemove(atPath path: some SQLExpressible) -> ColumnAssignment {
|
||||
// .init(columnName: name, value: Database.jsonRemove(self, atPath: path))
|
||||
// }
|
||||
//
|
||||
// /// Updates a columns with the `JSON_REMOVE` SQL function.
|
||||
// ///
|
||||
// /// For example:
|
||||
// ///
|
||||
// /// ```swift
|
||||
// /// // UPDATE player SET address = JSON_REMOVE(address, '$.country', '$.city')
|
||||
// /// try Player.updateAll(db, [
|
||||
// /// JSONColumn("address").jsonRemove(atPatsh: ["$.country", "$.city"])
|
||||
// /// ])
|
||||
// /// ```
|
||||
// ///
|
||||
// /// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
|
||||
// ///
|
||||
// /// - Parameters:
|
||||
// /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
// @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
// public func jsonRemove<C>(atPaths paths: C)
|
||||
// -> ColumnAssignment
|
||||
// where C: Collection, C.Element: SQLExpressible
|
||||
// {
|
||||
// .init(columnName: name, value: Database.jsonRemove(self, atPaths: paths))
|
||||
// }
|
||||
//
|
||||
// }
|
||||
#endif
|
||||
@@ -0,0 +1,881 @@
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
extension Database {
|
||||
/// Validates and minifies a JSON string, with the `JSON` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON(' { "a": [ "test" ] } ') → '{"a":["test"]}'
|
||||
/// Database.json(#" { "a": [ "test" ] } "#)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jmini>
|
||||
public static func json(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// Creates a JSON array with the `JSON_ARRAY` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ARRAY(1, 2, 3, 4) → '[1,2,3,4]'
|
||||
/// Database.jsonArray(1...4)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
|
||||
public static func jsonArray<C>(_ values: C) -> SQLExpression
|
||||
where C: Collection, C.Element: SQLExpressible
|
||||
{
|
||||
.function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
|
||||
}
|
||||
|
||||
/// Creates a JSON array with the `JSON_ARRAY` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ARRAY(1, 2, '3', 4) → '[1,2,"3",4]'
|
||||
/// Database.jsonArray([1, 2, "3", 4])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
|
||||
public static func jsonArray<C>(_ values: C) -> SQLExpression
|
||||
where C: Collection, C.Element == any SQLExpressible
|
||||
{
|
||||
.function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
|
||||
}
|
||||
|
||||
/// The number of elements in a JSON array, as returned by the
|
||||
/// `JSON_ARRAY_LENGTH` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ARRAY_LENGTH('[1,2,3,4]') → 4
|
||||
/// Database.jsonArrayLength("[1,2,3,4]")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
|
||||
public static func jsonArrayLength(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_ARRAY_LENGTH", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// The number of elements in a JSON array, as returned by the
|
||||
/// `JSON_ARRAY_LENGTH` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ARRAY_LENGTH('{"one":[1,2,3]}', '$.one') → 3
|
||||
/// Database.jsonArrayLength(#"{"one":[1,2,3]}"#, atPath: "$.one")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON array.
|
||||
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonArrayLength(
|
||||
_ value: some SQLExpressible,
|
||||
atPath path: some SQLExpressible)
|
||||
-> SQLExpression
|
||||
{
|
||||
.function("JSON_ARRAY_LENGTH", [value.sqlExpression, path.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_ERROR_POSITION` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ERROR_POSITION(info)
|
||||
/// Database.jsonErrorPosition(Column("info"))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jerr>
|
||||
public static func jsonErrorPosition(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_ERROR_POSITION", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_EXTRACT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_EXTRACT('{"a":123}', '$.a') → 123
|
||||
/// Database.jsonExtract(#"{"a":123}"#, atPath: "$.a")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_EXTRACT", [value.sqlExpression, path.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_EXTRACT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_EXTRACT('{"a":2,"c":[4,5]}','$.c','$.a') → '[[4,5],2]'
|
||||
/// Database.jsonExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonExtract<C>(_ value: some SQLExpressible, atPaths paths: C)
|
||||
-> SQLExpression
|
||||
where C: Collection, C.Element: SQLExpressible
|
||||
{
|
||||
.function("JSON_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
/// The `JSON_INSERT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_INSERT('[1,2,3,4]','$[#]',99) → '[1,2,3,4,99]'
|
||||
/// Database.jsonInsert("[1,2,3,4]", ["$[#]": value: 99])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - assignments: A collection of key/value pairs, where keys are
|
||||
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonInsert<C>(
|
||||
_ value: some SQLExpressible,
|
||||
_ assignments: C)
|
||||
-> SQLExpression
|
||||
where C: Collection,
|
||||
C.Element == (key: String, value: any SQLExpressible)
|
||||
{
|
||||
.function("JSON_INSERT", [value.sqlExpression] + assignments.flatMap {
|
||||
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
|
||||
})
|
||||
}
|
||||
|
||||
/// The `JSON_REPLACE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_REPLACE('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
|
||||
/// Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": 99])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - assignments: A collection of key/value pairs, where keys are
|
||||
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonReplace<C>(
|
||||
_ value: some SQLExpressible,
|
||||
_ assignments: C)
|
||||
-> SQLExpression
|
||||
where C: Collection,
|
||||
C.Element == (key: String, value: any SQLExpressible)
|
||||
{
|
||||
.function("JSON_REPLACE", [value.sqlExpression] + assignments.flatMap {
|
||||
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
|
||||
})
|
||||
}
|
||||
|
||||
/// The `JSON_SET` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_SET('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
|
||||
/// Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": 99]])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - assignments: A collection of key/value pairs, where keys are
|
||||
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonSet<C>(
|
||||
_ value: some SQLExpressible,
|
||||
_ assignments: C)
|
||||
-> SQLExpression
|
||||
where C: Collection,
|
||||
C.Element == (key: String, value: any SQLExpressible)
|
||||
{
|
||||
.function("JSON_SET", [value.sqlExpression] + assignments.flatMap {
|
||||
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a JSON object with the `JSON_OBJECT` SQL function. Pass
|
||||
/// key/value pairs with a Swift collection such as a `Dictionary`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_OBJECT('c', '{"e":5}') → '{"c":"{\"e\":5}"}'
|
||||
/// Database.jsonObject([
|
||||
/// "c": #"{"e":5}"#,
|
||||
/// ])
|
||||
///
|
||||
/// // JSON_OBJECT('c', JSON_OBJECT('e', 5)) → '{"c":{"e":5}}'
|
||||
/// Database.jsonObject([
|
||||
/// "c": Database.jsonObject(["e": 5])),
|
||||
/// ])
|
||||
///
|
||||
/// // JSON_OBJECT('c', JSON('{"e":5}')) → '{"c":{"e":5}}'
|
||||
/// Database.jsonObject([
|
||||
/// "c": Database.json(#"{"e":5}"#),
|
||||
/// ])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jobj>
|
||||
public static func jsonObject<C>(_ elements: C)
|
||||
-> SQLExpression
|
||||
where C: Collection,
|
||||
C.Element == (key: String, value: any SQLExpressible)
|
||||
{
|
||||
.function("JSON_OBJECT", elements.flatMap {
|
||||
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
|
||||
})
|
||||
}
|
||||
|
||||
/// The `JSON_PATCH` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_PATCH('{"a":1,"b":2}','{"c":3,"d":4}') → '{"a":1,"b":2,"c":3,"d":4}'
|
||||
/// Database.jsonPatch(#"{"a":1,"b":2}"#, #"{"c":3,"d":4}"#)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
|
||||
public static func jsonPatch(
|
||||
_ value: some SQLExpressible,
|
||||
with patch: some SQLExpressible)
|
||||
-> SQLExpression
|
||||
{
|
||||
.function("JSON_PATCH", [value.sqlExpression, patch.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_REMOVE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_REMOVE('[0,1,2,3,4]', '$[2]') → '[0,1,3,4]'
|
||||
/// Database.jsonRemove("[0,1,2,3,4]", atPath: "$[2]")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_REMOVE", [value.sqlExpression, path.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_REMOVE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_REMOVE('[0,1,2,3,4]', '$[2]','$[0]') → '[1,3,4]'
|
||||
/// Database.jsonRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonRemove<C>(_ value: some SQLExpressible, atPaths paths: C)
|
||||
-> SQLExpression
|
||||
where C: Collection, C.Element: SQLExpressible
|
||||
{
|
||||
.function("JSON_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
/// The `JSON_TYPE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}') → 'object'
|
||||
/// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
|
||||
public static func jsonType(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_TYPE", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_TYPE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}', '$.a') → 'object'
|
||||
/// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#, atPath: "$.a")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonType(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_TYPE", [value.sqlExpression, path.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_VALID` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_VALID('{"x":35') → 0
|
||||
/// Database.jsonIsValid(#"{"x":35"#)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jvalid>
|
||||
public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_VALID", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_QUOTE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_QUOTE('[1]') → '"[1]"'
|
||||
/// Database.jsonQuote("[1]")
|
||||
///
|
||||
/// // JSON_QUOTE(JSON('[1]')) → '[1]'
|
||||
/// Database.jsonQuote(Database.json("[1]"))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jquote>
|
||||
public static func jsonQuote(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_QUOTE", [value.sqlExpression.jsonBuilderExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_GROUP_ARRAY` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name")))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name ORDER BY name) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name"), orderBy: Column("name")))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
public static func jsonGroupArray(
|
||||
_ value: some SQLExpressible,
|
||||
orderBy ordering: (any SQLOrderingTerm)? = nil,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"JSON_GROUP_ARRAY",
|
||||
[value.sqlExpression.jsonBuilderExpression],
|
||||
ordering: ordering?.sqlOrdering,
|
||||
filter: filter?.sqlExpression,
|
||||
isJSONValue: true)
|
||||
}
|
||||
|
||||
/// The `JSON_GROUP_OBJECT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FROM player
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score")))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score"),
|
||||
/// filter: Column("score") > 0))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
public static func jsonGroupObject(
|
||||
key: some SQLExpressible,
|
||||
value: some SQLExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil
|
||||
) -> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"JSON_GROUP_OBJECT",
|
||||
[key.sqlExpression, value.sqlExpression.jsonBuilderExpression],
|
||||
filter: filter?.sqlExpression,
|
||||
isJSONValue: true)
|
||||
}
|
||||
}
|
||||
#else
|
||||
extension Database {
|
||||
/// Validates and minifies a JSON string, with the `JSON` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON(' { "a": [ "test" ] } ') → '{"a":["test"]}'
|
||||
/// Database.json(#" { "a": [ "test" ] } "#)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jmini>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func json(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// Creates a JSON array with the `JSON_ARRAY` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ARRAY(1, 2, 3, 4) → '[1,2,3,4]'
|
||||
/// Database.jsonArray(1...4)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonArray<C>(_ values: C) -> SQLExpression
|
||||
where C: Collection, C.Element: SQLExpressible
|
||||
{
|
||||
.function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
|
||||
}
|
||||
|
||||
/// Creates a JSON array with the `JSON_ARRAY` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ARRAY(1, 2, '3', 4) → '[1,2,"3",4]'
|
||||
/// Database.jsonArray([1, 2, "3", 4])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonArray<C>(_ values: C) -> SQLExpression
|
||||
where C: Collection, C.Element == any SQLExpressible
|
||||
{
|
||||
.function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
|
||||
}
|
||||
|
||||
/// The number of elements in a JSON array, as returned by the
|
||||
/// `JSON_ARRAY_LENGTH` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ARRAY_LENGTH('[1,2,3,4]') → 4
|
||||
/// Database.jsonArrayLength("[1,2,3,4]")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonArrayLength(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_ARRAY_LENGTH", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// The number of elements in a JSON array, as returned by the
|
||||
/// `JSON_ARRAY_LENGTH` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ARRAY_LENGTH('{"one":[1,2,3]}', '$.one') → 3
|
||||
/// Database.jsonArrayLength(#"{"one":[1,2,3]}"#, atPath: "$.one")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON array.
|
||||
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonArrayLength(
|
||||
_ value: some SQLExpressible,
|
||||
atPath path: some SQLExpressible)
|
||||
-> SQLExpression
|
||||
{
|
||||
.function("JSON_ARRAY_LENGTH", [value.sqlExpression, path.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_ERROR_POSITION` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ERROR_POSITION(info)
|
||||
/// Database.jsonErrorPosition(Column("info"))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jerr>
|
||||
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *)
|
||||
public static func jsonErrorPosition(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_ERROR_POSITION", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_EXTRACT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_EXTRACT('{"a":123}', '$.a') → 123
|
||||
/// Database.jsonExtract(#"{"a":123}"#, atPath: "$.a")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_EXTRACT", [value.sqlExpression, path.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_EXTRACT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_EXTRACT('{"a":2,"c":[4,5]}','$.c','$.a') → '[[4,5],2]'
|
||||
/// Database.jsonExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonExtract<C>(_ value: some SQLExpressible, atPaths paths: C)
|
||||
-> SQLExpression
|
||||
where C: Collection, C.Element: SQLExpressible
|
||||
{
|
||||
.function("JSON_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
/// The `JSON_INSERT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_INSERT('[1,2,3,4]','$[#]',99) → '[1,2,3,4,99]'
|
||||
/// Database.jsonInsert("[1,2,3,4]", ["$[#]": value: 99])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - assignments: A collection of key/value pairs, where keys are
|
||||
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonInsert<C>(
|
||||
_ value: some SQLExpressible,
|
||||
_ assignments: C)
|
||||
-> SQLExpression
|
||||
where C: Collection,
|
||||
C.Element == (key: String, value: any SQLExpressible)
|
||||
{
|
||||
.function("JSON_INSERT", [value.sqlExpression] + assignments.flatMap {
|
||||
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
|
||||
})
|
||||
}
|
||||
|
||||
/// The `JSON_REPLACE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_REPLACE('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
|
||||
/// Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": 99])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - assignments: A collection of key/value pairs, where keys are
|
||||
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonReplace<C>(
|
||||
_ value: some SQLExpressible,
|
||||
_ assignments: C)
|
||||
-> SQLExpression
|
||||
where C: Collection,
|
||||
C.Element == (key: String, value: any SQLExpressible)
|
||||
{
|
||||
.function("JSON_REPLACE", [value.sqlExpression] + assignments.flatMap {
|
||||
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
|
||||
})
|
||||
}
|
||||
|
||||
/// The `JSON_SET` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_SET('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
|
||||
/// Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": 99]])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jins>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - assignments: A collection of key/value pairs, where keys are
|
||||
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonSet<C>(
|
||||
_ value: some SQLExpressible,
|
||||
_ assignments: C)
|
||||
-> SQLExpression
|
||||
where C: Collection,
|
||||
C.Element == (key: String, value: any SQLExpressible)
|
||||
{
|
||||
.function("JSON_SET", [value.sqlExpression] + assignments.flatMap {
|
||||
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a JSON object with the `JSON_OBJECT` SQL function. Pass
|
||||
/// key/value pairs with a Swift collection such as a `Dictionary`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_OBJECT('c', '{"e":5}') → '{"c":"{\"e\":5}"}'
|
||||
/// Database.jsonObject([
|
||||
/// "c": #"{"e":5}"#,
|
||||
/// ])
|
||||
///
|
||||
/// // JSON_OBJECT('c', JSON_OBJECT('e', 5)) → '{"c":{"e":5}}'
|
||||
/// Database.jsonObject([
|
||||
/// "c": Database.jsonObject(["e": 5])),
|
||||
/// ])
|
||||
///
|
||||
/// // JSON_OBJECT('c', JSON('{"e":5}')) → '{"c":{"e":5}}'
|
||||
/// Database.jsonObject([
|
||||
/// "c": Database.json(#"{"e":5}"#),
|
||||
/// ])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jobj>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonObject<C>(_ elements: C)
|
||||
-> SQLExpression
|
||||
where C: Collection,
|
||||
C.Element == (key: String, value: any SQLExpressible)
|
||||
{
|
||||
.function("JSON_OBJECT", elements.flatMap {
|
||||
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
|
||||
})
|
||||
}
|
||||
|
||||
/// The `JSON_PATCH` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_PATCH('{"a":1,"b":2}','{"c":3,"d":4}') → '{"a":1,"b":2,"c":3,"d":4}'
|
||||
/// Database.jsonPatch(#"{"a":1,"b":2}"#, #"{"c":3,"d":4}"#)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonPatch(
|
||||
_ value: some SQLExpressible,
|
||||
with patch: some SQLExpressible)
|
||||
-> SQLExpression
|
||||
{
|
||||
.function("JSON_PATCH", [value.sqlExpression, patch.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_REMOVE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_REMOVE('[0,1,2,3,4]', '$[2]') → '[0,1,3,4]'
|
||||
/// Database.jsonRemove("[0,1,2,3,4]", atPath: "$[2]")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_REMOVE", [value.sqlExpression, path.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_REMOVE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_REMOVE('[0,1,2,3,4]', '$[2]','$[0]') → '[1,3,4]'
|
||||
/// Database.jsonRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonRemove<C>(_ value: some SQLExpressible, atPaths paths: C)
|
||||
-> SQLExpression
|
||||
where C: Collection, C.Element: SQLExpressible
|
||||
{
|
||||
.function("JSON_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
/// The `JSON_TYPE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}') → 'object'
|
||||
/// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonType(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_TYPE", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_TYPE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_TYPE('{"a":[2,3.5,true,false,null,"x"]}', '$.a') → 'object'
|
||||
/// Database.jsonType(#"{"a":[2,3.5,true,false,null,"x"]}"#, atPath: "$.a")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonType(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_TYPE", [value.sqlExpression, path.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_VALID` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_VALID('{"x":35') → 0
|
||||
/// Database.jsonIsValid(#"{"x":35"#)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jvalid>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_VALID", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// Returns a valid JSON string with the `JSON_QUOTE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_QUOTE('[1]') → '"[1]"'
|
||||
/// Database.jsonQuote("[1]")
|
||||
///
|
||||
/// // JSON_QUOTE(JSON('[1]')) → '[1]'
|
||||
/// Database.jsonQuote(Database.json("[1]"))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jquote>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonQuote(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_QUOTE", [value.sqlExpression.jsonBuilderExpression])
|
||||
}
|
||||
|
||||
/// The `JSON_GROUP_ARRAY` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name")))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonGroupArray(
|
||||
_ value: some SQLExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"JSON_GROUP_ARRAY",
|
||||
[value.sqlExpression.jsonBuilderExpression],
|
||||
filter: filter?.sqlExpression,
|
||||
isJSONValue: true)
|
||||
}
|
||||
|
||||
/// The `JSON_GROUP_OBJECT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FROM player
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score")))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score"),
|
||||
/// filter: Column("score") > 0))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
public static func jsonGroupObject(
|
||||
key: some SQLExpressible,
|
||||
value: some SQLExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil
|
||||
) -> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"JSON_GROUP_OBJECT",
|
||||
[key.sqlExpression, value.sqlExpression.jsonBuilderExpression],
|
||||
filter: filter?.sqlExpression,
|
||||
isJSONValue: true)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -42,7 +42,7 @@ import Foundation
|
||||
/// - ``hasCompletedMigrations(_:)``
|
||||
public struct DatabaseMigrator {
|
||||
/// Controls how a migration handle foreign keys constraints.
|
||||
public enum ForeignKeyChecks {
|
||||
public enum ForeignKeyChecks: Sendable {
|
||||
/// The migration runs with disabled foreign keys.
|
||||
///
|
||||
/// Foreign keys are checked right before changes are committed on disk,
|
||||
@@ -50,7 +50,7 @@ public struct DatabaseMigrator {
|
||||
/// ``DatabaseMigrator/disablingDeferredForeignKeyChecks()``.
|
||||
///
|
||||
/// In this case, you can perform your own deferred foreign key checks
|
||||
/// with ``Database/checkForeignKeys(in:)`` or
|
||||
/// with ``Database/checkForeignKeys(in:in:)`` or
|
||||
/// ``Database/checkForeignKeys()``:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -118,7 +118,7 @@ public struct DatabaseMigrator {
|
||||
/// The returned migrator is _unsafe_, because it no longer guarantees the
|
||||
/// integrity of the database. It is now _your_ responsibility to register
|
||||
/// migrations that do not break foreign key constraints. See
|
||||
/// ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:)``.
|
||||
/// ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:in:)``.
|
||||
///
|
||||
/// Running migrations without foreign key checks can improve migration
|
||||
/// performance on huge databases.
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>NSPrivacyTracking</key>
|
||||
<false/>
|
||||
<key>NSPrivacyCollectedDataTypes</key>
|
||||
<array/>
|
||||
<key>NSPrivacyTrackingDomains</key>
|
||||
<array/>
|
||||
<key>NSPrivacyAccessedAPITypes</key>
|
||||
<array/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -80,7 +80,7 @@
|
||||
/// using: Book.translatorForeignKey)
|
||||
/// }
|
||||
/// ```
|
||||
public struct ForeignKey: Equatable {
|
||||
public struct ForeignKey: Equatable, Sendable {
|
||||
var originColumns: [String]
|
||||
var destinationColumns: [String]?
|
||||
|
||||
|
||||
@@ -222,6 +222,12 @@ extension Association {
|
||||
relation = relation.unordered()
|
||||
}
|
||||
}
|
||||
|
||||
public func withStableOrder() -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.withStableOrder()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TableRequest conformance
|
||||
|
||||
@@ -127,7 +127,7 @@ extension AssociationToMany {
|
||||
/// }
|
||||
/// ```
|
||||
public func average(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression]))
|
||||
let aggregate = makeAggregate(.function("AVG", [expression.sqlExpression]))
|
||||
if let column = expression as? any ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
@@ -174,7 +174,7 @@ extension AssociationToMany {
|
||||
/// }
|
||||
/// ```
|
||||
public func max(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression]))
|
||||
let aggregate = makeAggregate(.function("MAX", [expression.sqlExpression]))
|
||||
if let column = expression as? any ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
@@ -221,7 +221,7 @@ extension AssociationToMany {
|
||||
/// }
|
||||
/// ```
|
||||
public func min(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression]))
|
||||
let aggregate = makeAggregate(.function("MIN", [expression.sqlExpression]))
|
||||
if let column = expression as? any ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
@@ -271,7 +271,7 @@ extension AssociationToMany {
|
||||
/// }
|
||||
/// ```
|
||||
public func sum(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression]))
|
||||
let aggregate = makeAggregate(.function("SUM", [expression.sqlExpression]))
|
||||
if let column = expression as? any ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum")
|
||||
@@ -321,7 +321,7 @@ extension AssociationToMany {
|
||||
/// }
|
||||
/// ```
|
||||
public func total(_ expression: some SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("TOTAL", [expression.sqlExpression]))
|
||||
let aggregate = makeAggregate(.function("TOTAL", [expression.sqlExpression]))
|
||||
if let column = expression as? any ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
// Yes we use the `Sum` suffix instead of `Total`. Both `total(_:)`
|
||||
|
||||
@@ -100,8 +100,13 @@ extension QueryInterfaceRequest: FetchRequest {
|
||||
let associations = relation.prefetchedAssociations
|
||||
if associations.isEmpty == false {
|
||||
// Eager loading of prefetched associations
|
||||
preparedRequest.supplementaryFetch = { [relation] db, rows in
|
||||
try prefetch(db, associations: associations, from: relation, into: rows)
|
||||
preparedRequest.supplementaryFetch = { [relation] db, rows, willExecuteSupplementaryRequest in
|
||||
try prefetch(
|
||||
db,
|
||||
associations: associations,
|
||||
from: relation,
|
||||
into: rows,
|
||||
willExecuteSupplementaryRequest: willExecuteSupplementaryRequest)
|
||||
}
|
||||
}
|
||||
return preparedRequest
|
||||
@@ -339,6 +344,12 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
$0.relation = $0.relation.unordered()
|
||||
}
|
||||
}
|
||||
|
||||
public func withStableOrder() -> QueryInterfaceRequest<RowDecoder> {
|
||||
with {
|
||||
$0.relation = $0.relation.withStableOrder()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: AggregatingRequest {
|
||||
@@ -1374,11 +1385,14 @@ extension ColumnExpression {
|
||||
/// - parameter associations: Prefetched associations.
|
||||
/// - parameter originRows: The rows that need to be extended with prefetched rows.
|
||||
/// - parameter originQuery: The query that was used to fetch `originRows`.
|
||||
/// - parameter willExecuteSupplementaryRequest: A closure executed before a
|
||||
/// supplementary fetch is performed.
|
||||
private func prefetch(
|
||||
_ db: Database,
|
||||
associations: [_SQLAssociation],
|
||||
from originRelation: SQLRelation,
|
||||
into originRows: [Row]) throws
|
||||
into originRows: [Row],
|
||||
willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?) throws
|
||||
{
|
||||
guard let firstOriginRow = originRows.first else {
|
||||
// No rows -> no prefetch
|
||||
@@ -1473,6 +1487,10 @@ private func prefetch(
|
||||
annotatedWith: pivotColumns)
|
||||
}
|
||||
|
||||
if let willExecuteSupplementaryRequest {
|
||||
// Support for `Database.dumpRequest`
|
||||
try willExecuteSupplementaryRequest(.init(prefetchRequest), association.keyPath)
|
||||
}
|
||||
let prefetchedRows = try prefetchRequest.fetchAll(db)
|
||||
let prefetchedGroups = prefetchedRows.grouped(byDatabaseValuesOnColumns: pivotColumns.map { "grdb_\($0)" })
|
||||
let groupingIndexes = firstOriginRow.indexes(forColumns: leftColumns)
|
||||
|
||||
@@ -442,7 +442,11 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
// make it impractical to define `filter(id:)`, `fetchOne(_:key:)`,
|
||||
// `deleteAll(_:ids:)` etc.
|
||||
if let recordType = RowDecoder.self as? any EncodableRecord.Type {
|
||||
if Sequence.Element.self == Date.self || Sequence.Element.self == Optional<Date>.self {
|
||||
if Sequence.Element.self == Data.self || Sequence.Element.self == Optional<Data>.self {
|
||||
let strategy = recordType.databaseDataEncodingStrategy
|
||||
let keys = keys.compactMap { ($0 as! Data?).flatMap(strategy.encode)?.databaseValue }
|
||||
return filter(rawKeys: keys)
|
||||
} else if Sequence.Element.self == Date.self || Sequence.Element.self == Optional<Date>.self {
|
||||
let strategy = recordType.databaseDateEncodingStrategy
|
||||
let keys = keys.compactMap { ($0 as! Date?).flatMap(strategy.encode)?.databaseValue }
|
||||
return filter(rawKeys: keys)
|
||||
@@ -901,6 +905,7 @@ extension AggregatingRequest {
|
||||
/// - ``orderWhenConnected(_:)``
|
||||
/// - ``reversed()``
|
||||
/// - ``unordered()``
|
||||
/// - ``withStableOrder()``
|
||||
public protocol OrderedRequest {
|
||||
/// Sorts the fetched rows according to the given SQL ordering terms.
|
||||
///
|
||||
@@ -961,6 +966,14 @@ public protocol OrderedRequest {
|
||||
/// .unordered()
|
||||
/// ```
|
||||
func unordered() -> Self
|
||||
|
||||
/// Returns a request with a stable order.
|
||||
///
|
||||
/// The returned request lifts ordering ambiguities and always return
|
||||
/// its results in the same order.
|
||||
///
|
||||
/// The purpose of this method is to make requests testable.
|
||||
func withStableOrder() -> Self
|
||||
}
|
||||
|
||||
extension OrderedRequest {
|
||||
@@ -1374,6 +1387,7 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
/// - ``TableRequest/orderByPrimaryKey()``
|
||||
/// - ``OrderedRequest/reversed()``
|
||||
/// - ``OrderedRequest/unordered()``
|
||||
/// - ``OrderedRequest/withStableOrder()``
|
||||
///
|
||||
/// ### Associations
|
||||
///
|
||||
|
||||
@@ -27,6 +27,7 @@ public protocol ColumnExpression: SQLSpecificExpressible {
|
||||
}
|
||||
|
||||
extension ColumnExpression {
|
||||
/// Returns an SQL column.
|
||||
public var sqlExpression: SQLExpression {
|
||||
.column(name)
|
||||
}
|
||||
@@ -65,17 +66,33 @@ extension ColumnExpression where Self == Column {
|
||||
|
||||
/// A column in a database table.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// var score: Int
|
||||
/// }
|
||||
///
|
||||
/// let maximumScore = try dbQueue.read { db in
|
||||
/// // SELECT MAX(score) FROM player
|
||||
/// try Player
|
||||
/// .select(max(Column("score")), as: Int.self)
|
||||
/// .fetchOne(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Standard Columns
|
||||
///
|
||||
/// - ``rowID-3bn70``
|
||||
/// - ``rank``
|
||||
///
|
||||
/// ### Creating A Column
|
||||
///
|
||||
/// - ``init(_:)-5grmu``
|
||||
/// - ``init(_:)-7xc4z``
|
||||
public struct Column {
|
||||
public struct Column: Sendable {
|
||||
/// The hidden rowID column.
|
||||
public static let rowID = Column("rowid")
|
||||
|
||||
|
||||
@@ -37,6 +37,25 @@
|
||||
public struct SQLExpression {
|
||||
private var impl: Impl
|
||||
|
||||
/// The preferred interpretation of the expression in JSON
|
||||
/// building contexts (see `jsonBuilderExpression`).
|
||||
///
|
||||
/// ```swift
|
||||
/// // Considering:
|
||||
/// // JSON_ARRAY('[1, 2, 3]') → '["[1, 2, 3]"]'
|
||||
/// // JSON_ARRAY(JSON('[1, 2, 3]')) → [[1,2,3]]
|
||||
///
|
||||
/// // Compare an expression with preferredJSONInterpretation = .unspecified:
|
||||
/// // JSON_ARRAY("info")
|
||||
/// Database.jsonArray([Column("info")])
|
||||
///
|
||||
/// // ...with an expression with preferredJSONInterpretation = .jsonValue:
|
||||
/// // JSON_ARRAY(JSON("info"))
|
||||
/// Database.jsonArray([Column("info").jsonValue])
|
||||
/// Database.jsonArray([JSONColumn("info")])
|
||||
/// ```
|
||||
var preferredJSONInterpretation = JSONInterpretation.deferredToSQLite
|
||||
|
||||
/// The private implementation of the public `SQLExpression`.
|
||||
private enum Impl {
|
||||
/// A column.
|
||||
@@ -146,8 +165,14 @@ public struct SQLExpression {
|
||||
///
|
||||
/// <function>(<argument>, ...)
|
||||
/// <function>(DISTINCT <argument>)
|
||||
case function(String, aggregate: Bool, distinct: Bool, arguments: [SQLExpression])
|
||||
indirect case simpleFunction(SQLSimpleFunctionInvocation)
|
||||
|
||||
/// An aggregate function call.
|
||||
///
|
||||
/// <function>(<argument>, ...)
|
||||
/// <function>(DISTINCT <argument>)
|
||||
indirect case aggregateFunction(SQLAggregateFunctionInvocation)
|
||||
|
||||
/// An expression that checks for zero or positive values.
|
||||
///
|
||||
/// <expression> = 0
|
||||
@@ -178,6 +203,90 @@ public struct SQLExpression {
|
||||
/// - For views, it is true iff any column is not null.
|
||||
/// - For CTEs, it is not implemented yet.
|
||||
case qualifiedExists(TableAlias, isNegated: Bool)
|
||||
|
||||
/// Returns a qualified expression
|
||||
func qualified(with alias: TableAlias) -> Impl {
|
||||
switch self {
|
||||
case .databaseValue,
|
||||
.qualifiedColumn,
|
||||
.qualifiedFastPrimaryKey,
|
||||
.qualifiedExists,
|
||||
.subquery,
|
||||
.exists:
|
||||
return self
|
||||
|
||||
case let .column(name):
|
||||
return .qualifiedColumn(name, alias)
|
||||
|
||||
case let .rowValue(expressions):
|
||||
return .rowValue(expressions.map { $0.qualified(with: alias) })
|
||||
|
||||
case let .literal(sqlLiteral):
|
||||
return .literal(sqlLiteral.qualified(with: alias))
|
||||
|
||||
case let .between(
|
||||
expression: expression,
|
||||
lowerBound: lowerBound,
|
||||
upperBound: upperBound,
|
||||
isNegated: isNegated):
|
||||
|
||||
return .between(
|
||||
expression: expression.qualified(with: alias),
|
||||
lowerBound: lowerBound.qualified(with: alias),
|
||||
upperBound: upperBound.qualified(with: alias),
|
||||
isNegated: isNegated)
|
||||
|
||||
case let .binary(op, lhs, rhs):
|
||||
return .binary(op, lhs.qualified(with: alias), rhs.qualified(with: alias))
|
||||
|
||||
case let .escapableBinary(op, lhs, rhs, escape):
|
||||
return .escapableBinary(
|
||||
op,
|
||||
lhs.qualified(with: alias),
|
||||
rhs.qualified(with: alias),
|
||||
escape: escape?.qualified(with: alias))
|
||||
|
||||
case let .associativeBinary(op, expressions):
|
||||
return .associativeBinary(op, expressions.map { $0.qualified(with: alias) })
|
||||
|
||||
case let .in(expression, collection, isNegated: isNegated):
|
||||
return .in(
|
||||
expression.qualified(with: alias),
|
||||
collection.qualified(with: alias),
|
||||
isNegated: isNegated
|
||||
)
|
||||
|
||||
case let .unary(op, expression):
|
||||
return .unary(op, expression.qualified(with: alias))
|
||||
|
||||
case let .compare(op, lhs, rhs):
|
||||
return .compare(op, lhs.qualified(with: alias), rhs.qualified(with: alias))
|
||||
|
||||
case let .tableMatch(a, expression):
|
||||
return .tableMatch(a, expression.qualified(with: alias))
|
||||
|
||||
case let .not(expression):
|
||||
return .not(expression.qualified(with: alias))
|
||||
|
||||
case let .collated(expression, collationName):
|
||||
return .collated(expression.qualified(with: alias), collationName)
|
||||
|
||||
case .countAll:
|
||||
return .countAll
|
||||
|
||||
case let .simpleFunction(invocation):
|
||||
return .simpleFunction(invocation.qualified(with: alias))
|
||||
|
||||
case let .aggregateFunction(invocation):
|
||||
return .aggregateFunction(invocation.qualified(with: alias))
|
||||
|
||||
case let .isEmpty(expression, isNegated: isNegated):
|
||||
return .isEmpty(expression.qualified(with: alias), isNegated: isNegated)
|
||||
|
||||
case .fastPrimaryKey:
|
||||
return .qualifiedFastPrimaryKey(alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `BooleanTest` supports truthiness tests.
|
||||
@@ -206,7 +315,7 @@ public struct SQLExpression {
|
||||
/// 1000.databaseValue]
|
||||
/// let request = Player.select(values.joined(operator: .add))
|
||||
/// ```
|
||||
public struct AssociativeBinaryOperator: Hashable {
|
||||
public struct AssociativeBinaryOperator: Hashable, Sendable {
|
||||
/// The SQL operator
|
||||
let sql: String
|
||||
|
||||
@@ -344,11 +453,22 @@ public struct SQLExpression {
|
||||
/// The SQL operator
|
||||
let sql: String
|
||||
|
||||
/// Creates a binary operator
|
||||
/// A boolean value indicating if the operator is known to return a
|
||||
/// JSON value.
|
||||
///
|
||||
/// BinaryOperator("-")
|
||||
init(_ sql: String) {
|
||||
/// A false value does not provide any information.
|
||||
let isJSONValue: Bool
|
||||
|
||||
/// Creates a binary operator.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```
|
||||
/// BinaryOperator("-")
|
||||
/// ```
|
||||
init(_ sql: String, isJSONValue: Bool = false) {
|
||||
self.sql = sql
|
||||
self.isJSONValue = isJSONValue
|
||||
}
|
||||
|
||||
/// The `<` binary operator
|
||||
@@ -377,6 +497,22 @@ public struct SQLExpression {
|
||||
|
||||
/// The `>>` bitwise right shift operator
|
||||
static let rightShift = BinaryOperator(">>")
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `->` SQL operator
|
||||
static let jsonExtractJSON = BinaryOperator("->", isJSONValue: true)
|
||||
|
||||
/// The `->>` SQL operator
|
||||
static let jsonExtractSQL = BinaryOperator("->>")
|
||||
#else
|
||||
/// The `->` SQL operator
|
||||
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
|
||||
static let jsonExtractJSON = BinaryOperator("->", isJSONValue: true)
|
||||
|
||||
/// The `->>` SQL operator
|
||||
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
|
||||
static let jsonExtractSQL = BinaryOperator("->>")
|
||||
#endif
|
||||
}
|
||||
|
||||
/// `EscapableBinaryOperator` is an SQLite binary operator that accepts an
|
||||
@@ -444,6 +580,36 @@ public struct SQLExpression {
|
||||
/// The `~` unary operator
|
||||
static let bitwiseNot = UnaryOperator("~")
|
||||
}
|
||||
|
||||
/// Describes the interpretation of an expression in a JSON
|
||||
/// building context.
|
||||
enum JSONInterpretation {
|
||||
/// JSON interpretation is deferred to SQLite:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ARRAY('[1, 2, 3]') → '["[1, 2, 3]"]'
|
||||
/// Database.jsonArray(["[1, 2, 3]"])
|
||||
///
|
||||
/// // JSON_ARRAY(JSON('[1, 2, 3]')) → '[[1, 2, 3]]'
|
||||
/// Database.jsonArray([Database.json("[1, 2, 3]")])
|
||||
///
|
||||
/// // JSON_ARRAY("info")
|
||||
/// Database.jsonArray([Column("info")])
|
||||
/// ```
|
||||
case deferredToSQLite
|
||||
|
||||
/// Expression is interpreted as a JSON value:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSON_ARRAY(JSON('[1, 2, 3]')) → '[[1, 2, 3]]'
|
||||
/// Database.jsonArray(["[1, 2, 3]"].jsonValue)
|
||||
///
|
||||
/// // JSON_ARRAY(JSON("info"))
|
||||
/// Database.jsonArray([Column("info").jsonValue])
|
||||
/// Database.jsonArray([JSONColumn("info")])
|
||||
/// ```
|
||||
case jsonValue
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Creating Expressions
|
||||
@@ -756,48 +922,166 @@ extension SQLExpression {
|
||||
|
||||
// MARK: Functions
|
||||
|
||||
// TODO: add missing pure functions:
|
||||
// https://www.sqlite.org/lang_aggfunc.html
|
||||
// https://www.sqlite.org/lang_datefunc.html
|
||||
// https://www.sqlite.org/lang_mathfunc.html
|
||||
private static let knownPureFunctions: Set<String> = [
|
||||
"ABS",
|
||||
"CHAR",
|
||||
"COALESCE",
|
||||
"GLOB",
|
||||
"HEX",
|
||||
"IFNULL",
|
||||
"IIF",
|
||||
"INSTR",
|
||||
"JSON",
|
||||
"JSON_ARRAY",
|
||||
"JSON_GROUP_ARRAY",
|
||||
"JSON_GROUP_OBJECT",
|
||||
"JSON_INSERT",
|
||||
"JSON_OBJECT",
|
||||
"JSON_PATCH",
|
||||
"JSON_REMOVE",
|
||||
"JSON_REPLACE",
|
||||
"JSON_SET",
|
||||
"JSON_QUOTE",
|
||||
"LENGTH",
|
||||
"LIKE",
|
||||
"LIKELIHOOD",
|
||||
"LIKELY",
|
||||
"LOAD_EXTENSION",
|
||||
"LOWER",
|
||||
"LTRIM",
|
||||
"NULLIF",
|
||||
"PRINTF",
|
||||
"QUOTE",
|
||||
"REPLACE",
|
||||
"ROUND",
|
||||
"RTRIM",
|
||||
"SOUNDEX",
|
||||
"SQLITE_COMPILEOPTION_GET",
|
||||
"SQLITE_COMPILEOPTION_USED",
|
||||
"SQLITE_SOURCE_ID",
|
||||
"SQLITE_VERSION",
|
||||
"SUBSTR",
|
||||
"TRIM",
|
||||
"TYPEOF",
|
||||
"UNICODE",
|
||||
"UNLIKELY",
|
||||
"UPPER",
|
||||
"ZEROBLOB",
|
||||
]
|
||||
|
||||
private static let knownAggregateFunctions: Set<String> = [
|
||||
"AVG",
|
||||
"COUNT",
|
||||
"GROUP_CONCAT",
|
||||
"JSON_GROUP_ARRAY",
|
||||
"JSON_GROUP_OBJECT",
|
||||
"MAX", // when single argument
|
||||
"MIN", // when single argument
|
||||
"SUM",
|
||||
"TOTAL",
|
||||
]
|
||||
|
||||
private static let knownFunctionsReturningJSONValue: Set<String> = [
|
||||
"JSON",
|
||||
"JSON_ARRAY",
|
||||
"JSON_GROUP_ARRAY",
|
||||
"JSON_GROUP_OBJECT",
|
||||
"JSON_INSERT",
|
||||
"JSON_OBJECT",
|
||||
"JSON_PATCH",
|
||||
"JSON_REMOVE",
|
||||
"JSON_REPLACE",
|
||||
"JSON_SET",
|
||||
"JSON_QUOTE",
|
||||
]
|
||||
|
||||
/// The `COUNT(*)` expression.
|
||||
static let countAll = SQLExpression(impl: .countAll)
|
||||
|
||||
/// A function call.
|
||||
static func function(_ functionName: String, _ arguments: [SQLExpression]) -> Self {
|
||||
let name = functionName.uppercased()
|
||||
|
||||
if (name == "MAX" || name == "MIN") && arguments.count > 1 {
|
||||
return .simpleFunction(
|
||||
functionName,
|
||||
arguments,
|
||||
isPure: true,
|
||||
isJSONValue: false)
|
||||
|
||||
} else if Self.knownAggregateFunctions.contains(name) {
|
||||
return .aggregateFunction(
|
||||
functionName,
|
||||
arguments,
|
||||
isJSONValue: Self.knownFunctionsReturningJSONValue.contains(name))
|
||||
|
||||
} else {
|
||||
let isJSONValue: Bool
|
||||
if name == "JSON_EXTRACT" && arguments.count > 2 {
|
||||
isJSONValue = true
|
||||
} else {
|
||||
isJSONValue = Self.knownFunctionsReturningJSONValue.contains(name)
|
||||
}
|
||||
|
||||
return .simpleFunction(
|
||||
functionName, arguments,
|
||||
isPure: Self.knownPureFunctions.contains(name),
|
||||
isJSONValue: isJSONValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// A simple function call.
|
||||
///
|
||||
/// - warning: Don't use this method for aggregate functions!
|
||||
static func simpleFunction(
|
||||
_ name: String,
|
||||
_ arguments: [SQLExpression],
|
||||
isPure: Bool = false,
|
||||
isJSONValue: Bool = false)
|
||||
-> Self
|
||||
{
|
||||
.init(impl: .simpleFunction(SQLSimpleFunctionInvocation(
|
||||
name: name,
|
||||
arguments: arguments,
|
||||
isPure: isPure,
|
||||
isJSONValue: isJSONValue)))
|
||||
}
|
||||
|
||||
/// An aggregate function call.
|
||||
static func aggregateFunction(
|
||||
_ name: String,
|
||||
_ arguments: [SQLExpression],
|
||||
isDistinct: Bool = false,
|
||||
ordering: SQLOrdering? = nil,
|
||||
filter: SQLExpression? = nil,
|
||||
isJSONValue: Bool = false)
|
||||
-> Self
|
||||
{
|
||||
.init(impl: .aggregateFunction(.init(
|
||||
name: name,
|
||||
arguments: arguments,
|
||||
isDistinct: isDistinct,
|
||||
ordering: ordering,
|
||||
filter: filter,
|
||||
isJSONValue: isJSONValue)))
|
||||
}
|
||||
|
||||
/// The `COUNT` function.
|
||||
///
|
||||
/// COUNT(<expression>)
|
||||
static func count(_ expression: SQLExpression) -> Self {
|
||||
aggregate("COUNT", [expression])
|
||||
function("COUNT", [expression])
|
||||
}
|
||||
|
||||
/// The `COUNT(DISTINCT)` function.
|
||||
///
|
||||
/// COUNT(DISTINCT <expression>)
|
||||
static func countDistinct(_ expression: SQLExpression) -> Self {
|
||||
distinctAggregate("COUNT", expression)
|
||||
}
|
||||
|
||||
/// A function call.
|
||||
///
|
||||
/// <function>(<argument>, ...)
|
||||
///
|
||||
/// - warning: for aggregate functions, call one of:
|
||||
/// - `SQLExpression.aggregate(_:_:)`,
|
||||
/// - `SQLExpression.distinctAggregate(_:_:)`,
|
||||
/// - `SQLExpression.countDistinct(_:)`
|
||||
/// - `SQLExpression.countAll`.
|
||||
static func function(_ name: String, _ arguments: [SQLExpression]) -> Self {
|
||||
self.init(impl: .function(name, aggregate: false, distinct: false, arguments: arguments))
|
||||
}
|
||||
|
||||
/// An aggregate function call.
|
||||
///
|
||||
/// <aggregate>(<argument>, ...)
|
||||
static func aggregate(_ name: String, _ arguments: [SQLExpression]) -> Self {
|
||||
self.init(impl: .function(name, aggregate: true, distinct: false, arguments: arguments))
|
||||
}
|
||||
|
||||
/// A distinct aggregate function call.
|
||||
///
|
||||
/// <aggregate>(DISTINCT <argument>)
|
||||
static func distinctAggregate(_ name: String, _ argument: SQLExpression) -> Self {
|
||||
self.init(impl: .function(name, aggregate: true, distinct: true, arguments: [argument]))
|
||||
aggregateFunction("COUNT", [expression], isDistinct: true)
|
||||
}
|
||||
|
||||
/// An expression that checks for zero or positive values.
|
||||
@@ -843,6 +1127,21 @@ extension SQLExpression {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Deriving Expressions
|
||||
|
||||
extension SQLExpression {
|
||||
/// Returns a qualified expression
|
||||
func qualified(with alias: TableAlias) -> Self {
|
||||
.init(impl: impl.qualified(with: alias), preferredJSONInterpretation: preferredJSONInterpretation)
|
||||
}
|
||||
|
||||
func withPreferredJSONInterpretation(_ interpretation: JSONInterpretation) -> Self {
|
||||
.init(impl: impl, preferredJSONInterpretation: interpretation)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Expressions Information
|
||||
|
||||
extension SQLExpression {
|
||||
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
|
||||
///
|
||||
@@ -906,18 +1205,8 @@ extension SQLExpression {
|
||||
case let .collated(expression, _):
|
||||
return try expression.column(db, for: alias, acceptsBijection: acceptsBijection)
|
||||
|
||||
case let .function(name, aggregate: false, distinct: false, arguments: arguments):
|
||||
guard acceptsBijection else {
|
||||
return nil
|
||||
}
|
||||
let name = name.uppercased()
|
||||
if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 {
|
||||
return try arguments[0].column(db, for: alias, acceptsBijection: acceptsBijection)
|
||||
} else if name == "IFNULL" && arguments.count == 2 && arguments[1].isConstantInRequest {
|
||||
return try arguments[0].column(db, for: alias, acceptsBijection: acceptsBijection)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
case let .simpleFunction(invocation) where acceptsBijection:
|
||||
return try invocation.column(db, for: alias)
|
||||
|
||||
case let .qualifiedFastPrimaryKey(a):
|
||||
if alias == a {
|
||||
@@ -1101,13 +1390,11 @@ extension SQLExpression {
|
||||
case .countAll:
|
||||
return "COUNT(*)"
|
||||
|
||||
case let .function(name, aggregate: aggregate, distinct: distinct, arguments: arguments):
|
||||
assert(!distinct || aggregate, "distinct requires aggregate")
|
||||
assert(!distinct || arguments.count == 1, "distinct requires a single argument")
|
||||
return try name
|
||||
+ (distinct ? "(DISTINCT " : "(")
|
||||
+ arguments.map { try $0.sql(context) }.joined(separator: ", ")
|
||||
+ ")"
|
||||
case let .simpleFunction(invocation):
|
||||
return try invocation.sql(context)
|
||||
|
||||
case let .aggregateFunction(invocation):
|
||||
return try invocation.sql(context, wrappedInParenthesis: wrappedInParenthesis)
|
||||
|
||||
case let .isEmpty(expression, isNegated: isNegated):
|
||||
var resultSQL = try """
|
||||
@@ -1516,17 +1803,6 @@ extension SQLExpression {
|
||||
}
|
||||
}
|
||||
|
||||
private static let knownPureFunctions = [
|
||||
"ABS", "CHAR", "COALESCE", "GLOB", "HEX", "IFNULL",
|
||||
"IIF", "INSTR", "LENGTH", "LIKE", "LIKELIHOOD",
|
||||
"LIKELY", "LOAD_EXTENSION", "LOWER", "LTRIM",
|
||||
"NULLIF", "PRINTF", "QUOTE", "REPLACE", "ROUND",
|
||||
"RTRIM", "SOUNDEX", "SQLITE_COMPILEOPTION_GET",
|
||||
"SQLITE_COMPILEOPTION_USED", "SQLITE_SOURCE_ID",
|
||||
"SQLITE_VERSION", "SUBSTR", "TRIM", "TRIM",
|
||||
"TYPEOF", "UNICODE", "UNLIKELY", "UPPER", "ZEROBLOB",
|
||||
]
|
||||
|
||||
/// Returns true if the expression has a unique value when SQLite runs
|
||||
/// a request.
|
||||
///
|
||||
@@ -1567,99 +1843,14 @@ extension SQLExpression {
|
||||
let .collated(expression, _):
|
||||
return expression.isConstantInRequest
|
||||
|
||||
case let .function(name, aggregate: false, distinct: false, arguments: arguments):
|
||||
let name = name.uppercased()
|
||||
guard ((name == "MAX" || name == "MIN") && arguments.count > 1)
|
||||
|| Self.knownPureFunctions.contains(name)
|
||||
else {
|
||||
return false // Don't know - assume not constant
|
||||
}
|
||||
|
||||
return arguments.allSatisfy(\.isConstantInRequest)
|
||||
case let .simpleFunction(invocation):
|
||||
return invocation.isConstantInRequest
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a qualified expression
|
||||
func qualified(with alias: TableAlias) -> SQLExpression {
|
||||
switch impl {
|
||||
case .databaseValue,
|
||||
.qualifiedColumn,
|
||||
.qualifiedFastPrimaryKey,
|
||||
.qualifiedExists,
|
||||
.subquery,
|
||||
.exists:
|
||||
return self
|
||||
|
||||
case let .column(name):
|
||||
return .qualifiedColumn(name, alias)
|
||||
|
||||
case let .rowValue(expressions):
|
||||
assert(!expressions.isEmpty)
|
||||
return .rowValue(expressions.map { $0.qualified(with: alias) })!
|
||||
|
||||
case let .literal(sqlLiteral):
|
||||
return .literal(sqlLiteral.qualified(with: alias))
|
||||
|
||||
case let .between(expression: expression, lowerBound: lowerBound, upperBound: upperBound, isNegated: isNegated):
|
||||
return .between(
|
||||
expression: expression.qualified(with: alias),
|
||||
lowerBound: lowerBound.qualified(with: alias),
|
||||
upperBound: upperBound.qualified(with: alias),
|
||||
isNegated: isNegated)
|
||||
|
||||
case let .binary(op, lhs, rhs):
|
||||
return .binary(op, lhs.qualified(with: alias), rhs.qualified(with: alias))
|
||||
|
||||
case let .escapableBinary(op, lhs, rhs, escape):
|
||||
return .escapableBinary(
|
||||
op,
|
||||
lhs.qualified(with: alias),
|
||||
rhs.qualified(with: alias),
|
||||
escape: escape?.qualified(with: alias))
|
||||
|
||||
case let .associativeBinary(op, expressions):
|
||||
return .associativeBinary(op, expressions.map { $0.qualified(with: alias) })
|
||||
|
||||
case let .in(expression, collection, isNegated: isNegated):
|
||||
return .in(
|
||||
expression.qualified(with: alias),
|
||||
collection.qualified(with: alias),
|
||||
isNegated: isNegated
|
||||
)
|
||||
|
||||
case let .unary(op, expression):
|
||||
return .unary(op, expression.qualified(with: alias))
|
||||
|
||||
case let .compare(op, lhs, rhs):
|
||||
return .compare(op, lhs.qualified(with: alias), rhs.qualified(with: alias))
|
||||
|
||||
case let .tableMatch(a, expression):
|
||||
return .tableMatch(a, expression.qualified(with: alias))
|
||||
|
||||
case let .not(expression):
|
||||
return .not(expression.qualified(with: alias))
|
||||
|
||||
case let .collated(expression, collationName):
|
||||
return .collated(expression.qualified(with: alias), collationName)
|
||||
|
||||
case .countAll:
|
||||
return .countAll
|
||||
|
||||
case let .function(name, aggregate: aggregate, distinct: distinct, arguments: arguments):
|
||||
return SQLExpression(impl: .function(name, aggregate: aggregate, distinct: distinct,
|
||||
arguments: arguments.map { $0.qualified(with: alias) }))
|
||||
|
||||
case let .isEmpty(expression, isNegated: isNegated):
|
||||
return .isEmpty(expression.qualified(with: alias), isNegated: isNegated)
|
||||
|
||||
case .fastPrimaryKey:
|
||||
return .qualifiedFastPrimaryKey(alias)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if the expression is an aggregate.
|
||||
///
|
||||
/// When in doubt, returns false.
|
||||
@@ -1709,8 +1900,10 @@ extension SQLExpression {
|
||||
|
||||
return false
|
||||
|
||||
case .countAll,
|
||||
.function(_, aggregate: true, distinct: _, arguments: _):
|
||||
case .countAll:
|
||||
return true
|
||||
|
||||
case .aggregateFunction:
|
||||
return true
|
||||
|
||||
default:
|
||||
@@ -1719,17 +1912,203 @@ extension SQLExpression {
|
||||
}
|
||||
}
|
||||
|
||||
/// https://www.sqlite.org/syntax/simple-function-invocation.html
|
||||
struct SQLSimpleFunctionInvocation {
|
||||
var name: String
|
||||
var arguments: [SQLExpression]
|
||||
|
||||
/// A boolean value indicating if a function is known to be pure.
|
||||
///
|
||||
/// A false value does not provide any information.
|
||||
var isPure: Bool
|
||||
|
||||
/// A boolean value indicating if a function is known to return a
|
||||
/// JSON value.
|
||||
///
|
||||
/// A false value does not provide any information.
|
||||
var isJSONValue: Bool
|
||||
|
||||
var isConstantInRequest: Bool {
|
||||
isPure && arguments.allSatisfy(\.isConstantInRequest)
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAlias) -> Self {
|
||||
SQLSimpleFunctionInvocation(
|
||||
name: name,
|
||||
arguments: arguments.map { $0.qualified(with: alias) },
|
||||
isPure: isPure,
|
||||
isJSONValue: isJSONValue)
|
||||
}
|
||||
|
||||
func column(_ db: Database, for alias: TableAlias) throws -> String? {
|
||||
let name = name.uppercased()
|
||||
if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 {
|
||||
return try arguments[0].column(db, for: alias, acceptsBijection: true)
|
||||
} else if name == "IFNULL" && arguments.count == 2 && arguments[1].isConstantInRequest {
|
||||
return try arguments[0].column(db, for: alias, acceptsBijection: true)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
var sql = name
|
||||
sql += "("
|
||||
sql += try arguments
|
||||
.map { try $0.sql(context) }
|
||||
.joined(separator: ", ")
|
||||
sql += ")"
|
||||
return sql
|
||||
}
|
||||
}
|
||||
|
||||
/// https://www.sqlite.org/syntax/aggregate-function-invocation.html
|
||||
struct SQLAggregateFunctionInvocation {
|
||||
var name: String
|
||||
var arguments: [SQLExpression]
|
||||
var isDistinct = false
|
||||
var ordering: SQLOrdering? = nil // SQLite 3.44.0+
|
||||
var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) SQLite 3.30+
|
||||
|
||||
/// A boolean value indicating if a function is known to return a
|
||||
/// JSON value.
|
||||
///
|
||||
/// A false value does not provide any information.
|
||||
var isJSONValue: Bool
|
||||
|
||||
func qualified(with alias: TableAlias) -> Self {
|
||||
SQLAggregateFunctionInvocation(
|
||||
name: name,
|
||||
arguments: arguments.map { $0.qualified(with: alias) },
|
||||
isDistinct: isDistinct,
|
||||
ordering: ordering?.qualified(with: alias),
|
||||
filter: filter?.qualified(with: alias),
|
||||
isJSONValue: isJSONValue)
|
||||
}
|
||||
|
||||
func sql(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
var sql = name
|
||||
|
||||
if isDistinct {
|
||||
sql += "(DISTINCT "
|
||||
} else {
|
||||
sql += "("
|
||||
}
|
||||
|
||||
sql += try arguments
|
||||
.map { try $0.sql(context) }
|
||||
.joined(separator: ", ")
|
||||
|
||||
if let ordering {
|
||||
sql += try " ORDER BY \(ordering.sql(context))"
|
||||
}
|
||||
|
||||
sql += ")"
|
||||
|
||||
if let filter {
|
||||
sql += try " FILTER (WHERE \(filter.sql(context)))"
|
||||
}
|
||||
|
||||
if wrappedInParenthesis && filter != nil {
|
||||
return "(\(sql))"
|
||||
} else {
|
||||
return sql
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - JSON
|
||||
|
||||
extension SQLExpression {
|
||||
/// A boolean value indicating if the expression is known to be a
|
||||
/// JSON value.
|
||||
///
|
||||
/// A false value does not provide any information.
|
||||
///
|
||||
/// For examples:
|
||||
///
|
||||
/// ```swift
|
||||
/// // isJSONValue is true:
|
||||
/// //
|
||||
/// // NULL
|
||||
/// // JSON('[1, 2, 3]')
|
||||
/// // info -> 'address'
|
||||
/// DatabaseValue.null
|
||||
/// Database.json("[1, 2, 3]")
|
||||
/// JSONColumn("info").jsonRepresentation(forKey: "address")
|
||||
///
|
||||
/// // isJSONValue is false
|
||||
/// //
|
||||
/// // '[1, 2, 3]'
|
||||
/// // info
|
||||
/// // info ->> 'address'
|
||||
/// [1, 2, 3].databaseValue
|
||||
/// JSONColumn("info")
|
||||
/// JSONColumn("info")["address"]
|
||||
/// ```
|
||||
var isJSONValue: Bool {
|
||||
switch impl {
|
||||
case .databaseValue(.null):
|
||||
return true
|
||||
|
||||
case let .binary(op, _, _):
|
||||
return op.isJSONValue
|
||||
|
||||
case let .collated(expression, _):
|
||||
return expression.isJSONValue
|
||||
|
||||
case let .simpleFunction(invocation):
|
||||
return invocation.isJSONValue
|
||||
|
||||
case let .aggregateFunction(invocation):
|
||||
return invocation.isJSONValue
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Returns an expression suitable in JSON building contexts.
|
||||
var jsonBuilderExpression: SQLExpression {
|
||||
switch preferredJSONInterpretation {
|
||||
case .deferredToSQLite:
|
||||
return self
|
||||
|
||||
case .jsonValue:
|
||||
if isJSONValue {
|
||||
return self
|
||||
} else {
|
||||
// Needs explicit call to JSON()
|
||||
return .function("JSON", [self])
|
||||
}
|
||||
}
|
||||
}
|
||||
#else
|
||||
@available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
|
||||
/// Returns an expression suitable in JSON building contexts.
|
||||
var jsonBuilderExpression: SQLExpression {
|
||||
switch preferredJSONInterpretation {
|
||||
case .deferredToSQLite:
|
||||
return self
|
||||
|
||||
case .jsonValue:
|
||||
if isJSONValue {
|
||||
return self
|
||||
} else {
|
||||
// Needs explicit call to JSON()
|
||||
return .function("JSON", [self])
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressible
|
||||
|
||||
/// A type that can be used as an SQL expression.
|
||||
///
|
||||
/// Related SQLite documentation <https://www.sqlite.org/syntax/expr.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Supporting Type
|
||||
///
|
||||
/// - ``SQLExpression``
|
||||
public protocol SQLExpressible {
|
||||
/// Returns an SQL expression.
|
||||
var sqlExpression: SQLExpression { get }
|
||||
@@ -1754,11 +2133,6 @@ extension SQLExpressible where Self == Column {
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Column Expressions
|
||||
///
|
||||
/// - ``Column``
|
||||
/// - ``ColumnExpression``
|
||||
///
|
||||
/// ### Applying a Collation
|
||||
///
|
||||
/// - ``collating(_:)-2mr78``
|
||||
@@ -1766,8 +2140,11 @@ extension SQLExpressible where Self == Column {
|
||||
///
|
||||
/// ### SQL Functions & Operators
|
||||
///
|
||||
/// See also JSON functions in <doc:JSON>.
|
||||
///
|
||||
/// - ``abs(_:)-5l6xp``
|
||||
/// - ``average(_:)``
|
||||
/// - ``average(_:filter:)``
|
||||
/// - ``capitalized``
|
||||
/// - ``count(_:)``
|
||||
/// - ``count(distinct:)``
|
||||
@@ -1780,12 +2157,20 @@ extension SQLExpressible where Self == Column {
|
||||
/// - ``localizedUppercased``
|
||||
/// - ``lowercased``
|
||||
/// - ``min(_:)``
|
||||
/// - ``min(_:filter:)``
|
||||
/// - ``max(_:)``
|
||||
/// - ``max(_:filter:)``
|
||||
/// - ``sum(_:)``
|
||||
/// - ``sum(_:filter:)``
|
||||
/// - ``total(_:)``
|
||||
/// - ``total(_:filter:)``
|
||||
/// - ``uppercased``
|
||||
/// - ``SQLDateModifier``
|
||||
///
|
||||
/// ### Interpreting an expression as JSON
|
||||
///
|
||||
/// - ``asJSON``
|
||||
///
|
||||
/// ### Creating Ordering Terms
|
||||
///
|
||||
/// - ``asc``
|
||||
|
||||
@@ -32,41 +32,76 @@ struct SQLForeignKeyRequest {
|
||||
}
|
||||
|
||||
// Incomplete information: let's look for schema foreign keys
|
||||
let foreignKeys = try db.foreignKeys(on: originTable).filter { foreignKey in
|
||||
if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() {
|
||||
return false
|
||||
}
|
||||
if let originColumns {
|
||||
let originColumns = Set(originColumns.lazy.map { $0.lowercased() })
|
||||
let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.origin.lowercased() })
|
||||
if originColumns != foreignKeyColumns {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if let destinationColumns {
|
||||
// TODO: test
|
||||
let destinationColumns = Set(destinationColumns.lazy.map { $0.lowercased() })
|
||||
let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.destination.lowercased() })
|
||||
if destinationColumns != foreignKeyColumns {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
//
|
||||
// But maybe the tables are views. In this case, don't throw
|
||||
// "no such table" error, because this is confusing for the user,
|
||||
// as discovered in <https://github.com/groue/GRDB.swift/discussions/1481>.
|
||||
// Instead, we'll crash with a clear message.
|
||||
|
||||
guard let originType = try tableType(db, for: originTable) else {
|
||||
throw DatabaseError.noSuchTable(originTable)
|
||||
}
|
||||
|
||||
// Matching foreign key(s) found
|
||||
if let foreignKey = foreignKeys.first {
|
||||
if foreignKeys.count == 1 {
|
||||
// Non-ambiguous
|
||||
return foreignKey.mapping
|
||||
} else {
|
||||
// Ambiguous: can't choose
|
||||
fatalError("Ambiguous foreign key from \(originTable) to \(destinationTable)")
|
||||
if originType.isView {
|
||||
if originColumns == nil {
|
||||
fatalError("""
|
||||
Could not infer foreign key from '\(originTable)' \
|
||||
to '\(destinationTable)'. To fix this error, provide an \
|
||||
explicit `ForeignKey` in the association definition.
|
||||
""")
|
||||
}
|
||||
} else {
|
||||
let foreignKeys = try db.foreignKeys(on: originTable).filter { foreignKey in
|
||||
if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() {
|
||||
return false
|
||||
}
|
||||
if let originColumns {
|
||||
let originColumns = Set(originColumns.lazy.map { $0.lowercased() })
|
||||
let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.origin.lowercased() })
|
||||
if originColumns != foreignKeyColumns {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if let destinationColumns {
|
||||
// TODO: test
|
||||
let destinationColumns = Set(destinationColumns.lazy.map { $0.lowercased() })
|
||||
let foreignKeyColumns = Set(foreignKey.mapping.lazy.map { $0.destination.lowercased() })
|
||||
if destinationColumns != foreignKeyColumns {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Matching foreign key(s) found
|
||||
if let foreignKey = foreignKeys.first {
|
||||
if foreignKeys.count == 1 {
|
||||
// Non-ambiguous
|
||||
return foreignKey.mapping
|
||||
} else {
|
||||
// Ambiguous: can't choose
|
||||
fatalError("""
|
||||
Ambiguous foreign key from '\(originTable)' to \
|
||||
'\(destinationTable)'. To fix this error, provide an \
|
||||
explicit `ForeignKey` in the association definition.
|
||||
""")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// No matching foreign key found: use the destination primary key
|
||||
if let originColumns {
|
||||
guard let destinationType = try tableType(db, for: destinationTable) else {
|
||||
throw DatabaseError.noSuchTable(destinationTable)
|
||||
}
|
||||
if destinationType.isView {
|
||||
fatalError("""
|
||||
Could not infer foreign key from '\(originTable)' \
|
||||
to '\(destinationTable)'. To fix this error, provide an \
|
||||
explicit `ForeignKey` in the association definition, \
|
||||
with both origin and destination columns.
|
||||
""")
|
||||
}
|
||||
let destinationColumns = try db.primaryKey(destinationTable).columns
|
||||
if originColumns.count == destinationColumns.count {
|
||||
let mapping = zip(originColumns, destinationColumns).map {
|
||||
@@ -76,7 +111,28 @@ struct SQLForeignKeyRequest {
|
||||
}
|
||||
}
|
||||
|
||||
fatalError("Could not infer foreign key from \(originTable) to \(destinationTable)")
|
||||
fatalError("""
|
||||
Could not infer foreign key from '\(originTable)' to \
|
||||
'\(destinationTable)'. To fix this error, provide an \
|
||||
explicit `ForeignKey` in the association definition.
|
||||
""")
|
||||
}
|
||||
|
||||
private struct TableType {
|
||||
var isView: Bool
|
||||
}
|
||||
|
||||
private func tableType(_ db: Database, for name: String) throws -> TableType? {
|
||||
for schemaID in try db.schemaIdentifiers() {
|
||||
if try db.schema(schemaID).containsObjectNamed(name, ofType: .table) {
|
||||
return TableType(isView: false)
|
||||
}
|
||||
if try db.schema(schemaID).containsObjectNamed(name, ofType: .view) {
|
||||
return TableType(isView: true)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,40 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.function("ABS", [value.sqlExpression])
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `AVG` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // AVG(length)
|
||||
/// average(Column("length"))
|
||||
/// ```
|
||||
public func average(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction("AVG", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `AVG` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // AVG(length) FILTER (WHERE length > 0)
|
||||
/// average(Column("length"), filter: Column("length") > 0)
|
||||
/// ```
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
|
||||
public func average(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: some SQLSpecificExpressible)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"AVG", [value.sqlExpression],
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `AVG` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
@@ -19,8 +53,9 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
/// average(Column("length"))
|
||||
/// ```
|
||||
public func average(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.aggregate("AVG", [value.sqlExpression])
|
||||
.aggregateFunction("AVG", [value.sqlExpression])
|
||||
}
|
||||
#endif
|
||||
|
||||
/// The `COUNT` SQL function.
|
||||
///
|
||||
@@ -72,6 +107,38 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.function("LENGTH", [value.sqlExpression])
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `MAX` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // MAX(score)
|
||||
/// max(Column("score"))
|
||||
/// ```
|
||||
public func max(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction("MAX", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `MAX` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // MAX(score) FILTER (WHERE score < 0)
|
||||
/// max(Column("score"), filter: Column("score") < 0)
|
||||
/// ```
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
|
||||
public func max(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: some SQLSpecificExpressible)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction("MAX", [value.sqlExpression], filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `MAX` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
@@ -81,7 +148,40 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
/// max(Column("score"))
|
||||
/// ```
|
||||
public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.aggregate("MAX", [value.sqlExpression])
|
||||
.aggregateFunction("MAX", [value.sqlExpression])
|
||||
}
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `MIN` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // MIN(score)
|
||||
/// min(Column("score"))
|
||||
/// ```
|
||||
public func min(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction("MIN", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `MIN` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // MIN(score) FILTER (WHERE score > 0)
|
||||
/// min(Column("score"), filter: Column("score") > 0)
|
||||
/// ```
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
|
||||
public func min(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: some SQLSpecificExpressible)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction("MIN", [value.sqlExpression], filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `MIN` SQL function.
|
||||
@@ -93,7 +193,55 @@ public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
/// min(Column("score"))
|
||||
/// ```
|
||||
public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.aggregate("MIN", [value.sqlExpression])
|
||||
.aggregateFunction("MIN", [value.sqlExpression])
|
||||
}
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `SUM` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SUM(amount)
|
||||
/// sum(Column("amount"))
|
||||
/// ```
|
||||
///
|
||||
/// See also ``total(_:)``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
public func sum(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
orderBy ordering: (any SQLOrderingTerm)? = nil,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression
|
||||
{
|
||||
.aggregateFunction(
|
||||
"SUM", [value.sqlExpression],
|
||||
ordering: ordering?.sqlOrdering,
|
||||
filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `SUM` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SUM(amount) FILTER (WHERE amount > 0)
|
||||
/// sum(Column("amount"), filter: Column("amount") > 0)
|
||||
/// ```
|
||||
///
|
||||
/// See also ``total(_:)``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
|
||||
public func sum(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: some SQLSpecificExpressible)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"SUM", [value.sqlExpression],
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `SUM` SQL function.
|
||||
@@ -109,7 +257,55 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.aggregate("SUM", [value.sqlExpression])
|
||||
.aggregateFunction("SUM", [value.sqlExpression])
|
||||
}
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `TOTAL` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // TOTAL(amount)
|
||||
/// total(Column("amount"))
|
||||
/// ```
|
||||
///
|
||||
/// See also ``sum(_:)``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
public func total(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
orderBy ordering: (any SQLOrderingTerm)? = nil,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression
|
||||
{
|
||||
.aggregateFunction(
|
||||
"TOTAL", [value.sqlExpression],
|
||||
ordering: ordering?.sqlOrdering,
|
||||
filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `TOTAL` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // TOTAL(amount) FILTER (WHERE amount > 0)
|
||||
/// total(Column("amount"), filter: Column("amount") > 0)
|
||||
/// ```
|
||||
///
|
||||
/// See also ``total(_:)``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+
|
||||
public func total(
|
||||
_ value: some SQLSpecificExpressible,
|
||||
filter: some SQLSpecificExpressible)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"TOTAL", [value.sqlExpression],
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `TOTAL` SQL function.
|
||||
@@ -125,8 +321,9 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
public func total(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.aggregate("TOTAL", [value.sqlExpression])
|
||||
.aggregateFunction("TOTAL", [value.sqlExpression])
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - String functions
|
||||
|
||||
@@ -211,7 +408,7 @@ extension SQLSpecificExpressible {
|
||||
/// A date modifier for SQLite date functions.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_datefunc.html>
|
||||
public enum SQLDateModifier: SQLSpecificExpressible {
|
||||
public enum SQLDateModifier: SQLSpecificExpressible, Sendable {
|
||||
/// Adds the specified amount of seconds
|
||||
case second(Double)
|
||||
|
||||
|
||||
@@ -282,6 +282,28 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
func withStableOrder() -> Self {
|
||||
with { relation in
|
||||
relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in
|
||||
if try db.tableExists(source.tableName) {
|
||||
// Order by primary key. Don't order by rowid because those are
|
||||
// not stable: rowids can change after a vacuum.
|
||||
return try db.primaryKey(source.tableName).columns.map { SQLExpression.column($0).sqlOrdering }
|
||||
} else {
|
||||
// Support for views: create a stable order from all columns:
|
||||
// ORDER BY 1, 2, 3, ...
|
||||
let columnCount = try SQLQueryGenerator(relation: relation).columnCount(db)
|
||||
return (1...columnCount).map { SQL(sql: $0.description).sqlOrdering }
|
||||
}
|
||||
}))
|
||||
relation.children = children.mapValues { child in
|
||||
child.with {
|
||||
$0.relation = $0.relation.withStableOrder()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove ordering iff relation has no LIMIT clause
|
||||
func unorderedUnlessLimited() -> Self {
|
||||
if limit != nil {
|
||||
|
||||
@@ -324,7 +324,7 @@ extension SQLSelection: SQLSelectable {
|
||||
/// let players = try Player.select(AllColumns()).fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public struct AllColumns {
|
||||
public struct AllColumns: Sendable {
|
||||
/// The `*` selection.
|
||||
public init() { }
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@
|
||||
/// ### Database Observation Support
|
||||
///
|
||||
/// - ``databaseRegion(_:)``
|
||||
public struct Table<RowDecoder> {
|
||||
public struct Table<RowDecoder>: Sendable {
|
||||
/// The table name.
|
||||
public var tableName: String
|
||||
|
||||
|
||||
@@ -431,6 +431,15 @@ public class TableAlias {
|
||||
expression.sqlExpression.qualified(with: self)
|
||||
}
|
||||
|
||||
public subscript(_ expression: some SQLJSONExpressible &
|
||||
SQLSpecificExpressible &
|
||||
SQLSelectable &
|
||||
SQLOrderingTerm)
|
||||
-> AnySQLJSONExpressible
|
||||
{
|
||||
AnySQLJSONExpressible(sqlExpression: expression.sqlExpression.qualified(with: self))
|
||||
}
|
||||
|
||||
/// Returns an SQL ordering term that refers to the aliased table.
|
||||
///
|
||||
/// For example, let's sort books by author name first, and then by title:
|
||||
|
||||
@@ -1,31 +1,33 @@
|
||||
struct SQLIndexGenerator {
|
||||
let name: String
|
||||
let table: String
|
||||
let columns: [String]
|
||||
let expressions: [SQLExpression]
|
||||
let options: IndexOptions
|
||||
let condition: SQLExpression?
|
||||
|
||||
func sql(_ db: Database) throws -> String {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CREATE")
|
||||
var sql: SQL = "CREATE"
|
||||
|
||||
if options.contains(.unique) {
|
||||
chunks.append("UNIQUE")
|
||||
sql += " UNIQUE"
|
||||
}
|
||||
chunks.append("INDEX")
|
||||
|
||||
sql += " INDEX"
|
||||
|
||||
if options.contains(.ifNotExists) {
|
||||
chunks.append("IF NOT EXISTS")
|
||||
sql += " IF NOT EXISTS"
|
||||
}
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
chunks.append("ON")
|
||||
chunks.append("""
|
||||
\(table.quotedDatabaseIdentifier)(\
|
||||
\(columns.map(\.quotedDatabaseIdentifier).joined(separator: ", "))\
|
||||
)
|
||||
""")
|
||||
|
||||
sql += " \(identifier: name) ON \(identifier: table)("
|
||||
sql += expressions.map { SQL($0) }.joined(separator: ", ")
|
||||
sql += ")"
|
||||
|
||||
if let condition {
|
||||
try chunks.append("WHERE \(condition.quotedSQL(db))")
|
||||
sql += " WHERE \(condition)"
|
||||
}
|
||||
return chunks.joined(separator: " ")
|
||||
|
||||
let context = SQLGenerationContext(db, argumentsSink: .literalValues)
|
||||
return try sql.sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +35,7 @@ extension SQLIndexGenerator {
|
||||
init(index: IndexDefinition) {
|
||||
name = index.name
|
||||
table = index.table
|
||||
columns = index.columns
|
||||
expressions = index.expressions
|
||||
options = index.options
|
||||
condition = index.condition
|
||||
}
|
||||
|
||||
@@ -406,14 +406,14 @@ extension SQLTableGenerator {
|
||||
indexGenerator = SQLIndexGenerator(
|
||||
name: Database.defaultIndexName(on: originTable, columns: columnNames),
|
||||
table: originTable,
|
||||
columns: columnNames,
|
||||
expressions: columnNames.map { .column($0) },
|
||||
options: indexOptions,
|
||||
condition: nil)
|
||||
case .unique:
|
||||
indexGenerator = SQLIndexGenerator(
|
||||
name: Database.defaultIndexName(on: originTable, columns: columnNames),
|
||||
table: originTable,
|
||||
columns: columnNames,
|
||||
expressions: columnNames.map { .column($0) },
|
||||
options: indexOptions.union([.unique]),
|
||||
condition: nil)
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ public final class ColumnDefinition {
|
||||
/// The kind of a generated column.
|
||||
///
|
||||
/// Related SQLite documentation: <https://sqlite.org/gencol.html#virtual_versus_stored_columns>
|
||||
public enum GeneratedColumnQualification {
|
||||
public enum GeneratedColumnQualification: Sendable {
|
||||
/// A `VIRTUAL` generated column.
|
||||
case virtual
|
||||
/// A `STORED` generated column.
|
||||
@@ -559,9 +559,14 @@ public final class ColumnDefinition {
|
||||
return IndexDefinition(
|
||||
name: "\(table)_on_\(name)",
|
||||
table: table,
|
||||
columns: [name],
|
||||
expressions: [.column(name)],
|
||||
options: options,
|
||||
condition: nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `ColumnDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension ColumnDefinition: Sendable { }
|
||||
@@ -433,7 +433,7 @@ extension Database {
|
||||
try execute(sql: "DROP VIEW \(name.quotedDatabaseIdentifier)")
|
||||
}
|
||||
|
||||
/// Creates an index.
|
||||
/// Creates an index on the specified table and columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -443,12 +443,8 @@ extension Database {
|
||||
/// ```
|
||||
///
|
||||
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
|
||||
/// and use specific collations. To create such an index, use a raw SQL
|
||||
/// query:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.execute(sql: "CREATE INDEX ...")
|
||||
/// ```
|
||||
/// and use specific collations. To create such an index, use
|
||||
/// ``create(index:on:expressions:options:condition:)``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
|
||||
///
|
||||
@@ -481,7 +477,7 @@ extension Database {
|
||||
try create(index: name, on: table, columns: columns, options: options, condition: condition)
|
||||
}
|
||||
|
||||
/// Creates an index.
|
||||
/// Creates an index on the specified table and columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -526,7 +522,7 @@ extension Database {
|
||||
let index = IndexDefinition(
|
||||
name: name,
|
||||
table: table,
|
||||
columns: columns,
|
||||
expressions: columns.map { .column($0) },
|
||||
options: options,
|
||||
condition: condition?.sqlExpression)
|
||||
let generator = SQLIndexGenerator(index: index)
|
||||
@@ -534,7 +530,58 @@ extension Database {
|
||||
try execute(sql: sql)
|
||||
}
|
||||
|
||||
/// Creates an index on the specified table and columns.
|
||||
/// Creates an index on the specified table and expressions.
|
||||
///
|
||||
/// This method can generally create indexes on expressions (see
|
||||
/// <https://www.sqlite.org/expridx.html>):
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE INDEX txy ON t(x+y)
|
||||
/// try db.create(
|
||||
/// index: "txy",
|
||||
/// on: "t",
|
||||
/// expressions: [Column("x") + Column("y")])
|
||||
/// ```
|
||||
///
|
||||
/// In particular, you can specify the collation on indexed
|
||||
/// columns (see <https://www.sqlite.org/lang_createindex.html#collations>):
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE INDEX index_player_name ON player(name COLLATE NOCASE)
|
||||
/// try db.create(
|
||||
/// index: "index_player_name",
|
||||
/// on: "player",
|
||||
/// expressions: [Column("name").collating(.nocase)])
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The index name.
|
||||
/// - table: The name of the indexed table.
|
||||
/// - expressions: The indexed expressions.
|
||||
/// - options: Index creation options.
|
||||
/// - condition: If not nil, creates a partial index
|
||||
/// (see <https://www.sqlite.org/partialindex.html>).
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func create(
|
||||
index name: String,
|
||||
on table: String,
|
||||
expressions: [any SQLExpressible],
|
||||
options: IndexOptions = [],
|
||||
condition: (any SQLExpressible)? = nil)
|
||||
throws
|
||||
{
|
||||
let index = IndexDefinition(
|
||||
name: name,
|
||||
table: table,
|
||||
expressions: expressions.map { $0.sqlExpression },
|
||||
options: options,
|
||||
condition: condition?.sqlExpression)
|
||||
let generator = SQLIndexGenerator(index: index)
|
||||
let sql = try generator.sql(self)
|
||||
try execute(sql: sql)
|
||||
}
|
||||
|
||||
/// Creates an index with a default name on the specified table and columns.
|
||||
///
|
||||
/// The created index is named after the table and the column name(s):
|
||||
///
|
||||
@@ -554,12 +601,8 @@ extension Database {
|
||||
/// ``create(index:on:columns:options:condition:)`` instead.
|
||||
///
|
||||
/// SQLite can also index expressions (<https://www.sqlite.org/expridx.html>)
|
||||
/// and use specific collations. To create such an index, use a raw SQL
|
||||
/// query:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.execute(sql: "CREATE INDEX ...")
|
||||
/// ```
|
||||
/// and use specific collations. To create such an index, use
|
||||
/// ``create(index:on:expressions:options:condition:)``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createindex.html>
|
||||
///
|
||||
@@ -638,7 +681,7 @@ extension Database {
|
||||
}
|
||||
|
||||
/// View creation options
|
||||
public struct ViewOptions: OptionSet {
|
||||
public struct ViewOptions: OptionSet, Sendable {
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
|
||||
@@ -104,3 +104,8 @@ public final class ForeignKeyDefinition {
|
||||
throw DatabaseError.noSuchTable(name)
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `ForeignKeyDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension ForeignKeyDefinition: Sendable { }
|
||||
@@ -1,13 +1,13 @@
|
||||
struct IndexDefinition {
|
||||
let name: String
|
||||
let table: String
|
||||
let columns: [String]
|
||||
let expressions: [SQLExpression]
|
||||
let options: IndexOptions
|
||||
let condition: SQLExpression?
|
||||
}
|
||||
|
||||
/// Index creation options
|
||||
public struct IndexOptions: OptionSet {
|
||||
public struct IndexOptions: OptionSet, Sendable {
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
|
||||
@@ -161,3 +161,8 @@ public final class TableAlteration {
|
||||
alterations.append(.drop(name))
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `TableAlteration` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension TableAlteration: Sendable { }
|
||||
@@ -1,5 +1,5 @@
|
||||
/// Table creation options.
|
||||
public struct TableOptions: OptionSet {
|
||||
public struct TableOptions: OptionSet, Sendable {
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
@@ -753,3 +753,8 @@ public final class TableDefinition {
|
||||
literalConstraints.append(literal)
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `TableDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension TableDefinition: Sendable { }
|
||||
Loaded 100 of 168 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user