mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-04 05:08:44 +00:00
Compare commits
89
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 |
No files matched your search
@@ -28,7 +28,6 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
permissions:
|
||||
contents: read
|
||||
checks: write
|
||||
|
||||
jobs:
|
||||
Framework:
|
||||
@@ -80,13 +79,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" -resultBundlePath TestResults.xcresult 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
|
||||
- uses: kishikawakatsumi/xcresulttool@v1
|
||||
with:
|
||||
path: TestResults.xcresult
|
||||
show-passed-tests: false
|
||||
show-code-coverage: false
|
||||
if: success() || failure()
|
||||
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
|
||||
SPM:
|
||||
name: SPM
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
@@ -133,12 +126,6 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher3Encrypted
|
||||
- uses: kishikawakatsumi/xcresulttool@v1
|
||||
with:
|
||||
path: Tests/CocoaPods/SQLCipher3/TestResults_encrypted.xcresult
|
||||
show-passed-tests: false
|
||||
show-code-coverage: false
|
||||
if: success() || failure()
|
||||
SQLCipher4:
|
||||
name: SQLCipher4
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
@@ -159,12 +146,6 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher4Encrypted
|
||||
- uses: kishikawakatsumi/xcresulttool@v1
|
||||
with:
|
||||
path: Tests/CocoaPods/SQLCipher4/TestResults_encrypted.xcresult
|
||||
show-passed-tests: false
|
||||
show-code-coverage: false
|
||||
if: success() || failure()
|
||||
CustomSQLite:
|
||||
name: CustomSQLite
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
@@ -185,12 +166,6 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBCustomSQLiteOSX
|
||||
- uses: kishikawakatsumi/xcresulttool@v1
|
||||
with:
|
||||
path: TestResults.xcresult
|
||||
show-passed-tests: false
|
||||
show-code-coverage: false
|
||||
if: success() || failure()
|
||||
XCFramework:
|
||||
name: XCFramework
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
|
||||
@@ -115,6 +115,3 @@ Tests/SPM/Packages
|
||||
|
||||
# Test products
|
||||
Tests/products
|
||||
|
||||
# CI
|
||||
*.xcresult
|
||||
@@ -7,6 +7,10 @@ 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)
|
||||
@@ -121,7 +125,51 @@ 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
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.21.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.'
|
||||
|
||||
@@ -157,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 */; };
|
||||
@@ -852,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>"; };
|
||||
@@ -1737,6 +1739,7 @@
|
||||
children = (
|
||||
56A2FA3524424D2A00E97D23 /* Export.swift */,
|
||||
566DDE0C288D763C0000DCFB /* Fixits.swift */,
|
||||
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */,
|
||||
56A2386F1B9C75030082EB20 /* Core */,
|
||||
567B5BDF2AD3284100629622 /* Dump */,
|
||||
5698AC291D9E5A480056AF8C /* FTS */,
|
||||
@@ -1873,6 +1876,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
|
||||
@@ -186,7 +186,7 @@ public struct Configuration {
|
||||
|
||||
// MARK: - Managing SQLite Connections
|
||||
|
||||
private var setups: [@Sendable (Database) throws -> Void] = []
|
||||
private var setups: [(Database) throws -> Void] = []
|
||||
|
||||
/// Defines a function to run whenever an SQLite connection is opened.
|
||||
///
|
||||
@@ -223,7 +223,7 @@ public struct Configuration {
|
||||
///
|
||||
/// On newly created databases files, ``DatabasePool`` activates the WAL
|
||||
/// mode after the preparation functions have run.
|
||||
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
|
||||
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
|
||||
setups.append(setup)
|
||||
}
|
||||
|
||||
|
||||
@@ -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() {
|
||||
|
||||
+189
-39
@@ -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,7 +990,7 @@ 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:
|
||||
@@ -926,14 +1076,14 @@ public struct ColumnInfo: FetchableRecord, Sendable {
|
||||
|
||||
/// 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: Sendable {
|
||||
public struct IndexInfo: Sendable{
|
||||
/// The origin of an index.
|
||||
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible, Sendable {
|
||||
public var rawValue: String
|
||||
@@ -969,7 +1119,7 @@ public struct IndexInfo: Sendable {
|
||||
///
|
||||
/// You get instances of `ForeignKeyViolation` from the `Database` methods
|
||||
/// ``Database/foreignKeyViolations()`` and
|
||||
/// ``Database/foreignKeyViolations(in:)`` methods.
|
||||
/// ``Database/foreignKeyViolations(in:in:)`` methods.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -1023,7 +1173,7 @@ public struct ForeignKeyViolation: Sendable {
|
||||
/// 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:
|
||||
@@ -1279,7 +1429,7 @@ public struct PrimaryKeyInfo: Sendable {
|
||||
|
||||
/// 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).
|
||||
@@ -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 {
|
||||
|
||||
+110
-6
@@ -60,6 +60,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``inSavepoint(_:)``
|
||||
/// - ``inTransaction(_:_:)``
|
||||
/// - ``isInsideTransaction``
|
||||
/// - ``readOnly(_:)``
|
||||
/// - ``rollback()``
|
||||
/// - ``transactionDate``
|
||||
/// - ``TransactionCompletion``
|
||||
@@ -69,6 +70,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
///
|
||||
/// - ``dumpContent(format:to:)``
|
||||
/// - ``dumpRequest(_:format:to:)``
|
||||
/// - ``dumpSchema(to:)``
|
||||
/// - ``dumpSQL(_:format:to:)``
|
||||
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
|
||||
/// - ``DumpFormat``
|
||||
@@ -79,6 +81,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``add(transactionObserver:extent:)``
|
||||
/// - ``remove(transactionObserver:)``
|
||||
/// - ``afterNextTransaction(onCommit:onRollback:)``
|
||||
/// - ``notifyChanges(in:)``
|
||||
/// - ``registerAccess(to:)``
|
||||
///
|
||||
/// ### Collations
|
||||
@@ -771,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)
|
||||
}
|
||||
|
||||
@@ -820,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.
|
||||
@@ -1165,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
|
||||
@@ -1641,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 {
|
||||
|
||||
@@ -1720,7 +1814,7 @@ extension Database {
|
||||
// MARK: - Database-Related Types
|
||||
|
||||
/// See BusyMode and <https://www.sqlite.org/c3ref/busy_handler.html>
|
||||
public typealias BusyCallback = @Sendable (_ numberOfTries: Int) -> Bool
|
||||
public typealias BusyCallback = (_ numberOfTries: Int) -> Bool
|
||||
|
||||
/// When there are several connections to a database, a connection may try
|
||||
/// to access the database while it is locked by another connection.
|
||||
@@ -1748,7 +1842,7 @@ extension Database {
|
||||
/// - <https://www.sqlite.org/c3ref/busy_handler.html>
|
||||
/// - <https://www.sqlite.org/lang_transaction.html>
|
||||
/// - <https://www.sqlite.org/wal.html>
|
||||
public enum BusyMode: Sendable {
|
||||
public enum BusyMode {
|
||||
/// The `SQLITE_BUSY` error is immediately returned to the connection
|
||||
/// that tries to access the locked database.
|
||||
case immediateError
|
||||
@@ -2091,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 { }
|
||||
@@ -3,7 +3,7 @@ import Foundation
|
||||
/// An SQLite result code.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
public struct ResultCode: RawRepresentable, Equatable, Sendable {
|
||||
public struct ResultCode: RawRepresentable, Equatable {
|
||||
/// The raw SQLite result code.
|
||||
public let rawValue: CInt
|
||||
|
||||
@@ -206,6 +206,8 @@ extension ResultCode: CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension ResultCode: Sendable { }
|
||||
|
||||
/// A `DatabaseError` describes an SQLite error.
|
||||
///
|
||||
/// For example:
|
||||
@@ -394,16 +396,16 @@ 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 {
|
||||
static func connectionIsClosed() -> Self {
|
||||
DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")
|
||||
}
|
||||
|
||||
static func snapshotIsLost() -> Self {
|
||||
DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
|
||||
}
|
||||
}
|
||||
|
||||
// Support for `catch DatabaseError.SQLITE_XXX`
|
||||
|
||||
@@ -257,9 +257,7 @@ extension DatabasePool {
|
||||
// has freed its memory. That's better than nothing.
|
||||
releaseMemoryEventually()
|
||||
writer.async { _ in
|
||||
DispatchQueue.main.async {
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -359,7 +357,7 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -403,7 +401,7 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -448,22 +446,25 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
let builder = UnsafeDatabaseFutureBuilder<T>()
|
||||
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
// The semaphore that blocks until futureResult is defined:
|
||||
let futureSemaphore = DispatchSemaphore(value: 0)
|
||||
var futureResult: Result<T, Error>? = nil
|
||||
|
||||
asyncConcurrentRead { dbResult in
|
||||
let result = dbResult.flatMap { db in
|
||||
Result {
|
||||
try value(db)
|
||||
}
|
||||
}
|
||||
builder.setResultAndReleaseFuture(result)
|
||||
// Fetch and release the future
|
||||
futureResult = dbResult.flatMap { db in Result { try value(db) } }
|
||||
futureSemaphore.signal()
|
||||
}
|
||||
|
||||
return builder.makeFuture()
|
||||
return DatabaseFuture {
|
||||
// Block the future until results are fetched
|
||||
_ = futureSemaphore.wait(timeout: .distantFuture)
|
||||
return try futureResult!.get()
|
||||
}
|
||||
}
|
||||
|
||||
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
asyncConcurrentRead(value)
|
||||
}
|
||||
|
||||
@@ -504,7 +505,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// ```
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
public func asyncConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
@@ -664,9 +665,7 @@ extension DatabasePool: DatabaseReader {
|
||||
///
|
||||
/// - important: The `completion` argument is executed in a serial
|
||||
/// dispatch queue, so make sure you use the transaction asynchronously.
|
||||
func asyncWALSnapshotTransaction(
|
||||
_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, Error>) -> Void)
|
||||
{
|
||||
func asyncWALSnapshotTransaction(_ completion: @escaping (Result<WALSnapshotTransaction, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
completion(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -692,7 +691,7 @@ extension DatabasePool: DatabaseReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
@@ -723,7 +722,7 @@ extension DatabasePool: DatabaseReader {
|
||||
private func _addConcurrent<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
@@ -757,7 +756,7 @@ extension DatabasePool: DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
updates(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -810,7 +809,7 @@ extension DatabasePool: DatabaseWriter {
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,9 +169,7 @@ extension DatabaseQueue {
|
||||
// Release memory asynchronously
|
||||
writer.async { db in
|
||||
db.releaseMemory()
|
||||
DispatchQueue.main.async {
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -235,7 +233,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
writer.async { db in
|
||||
defer {
|
||||
// Ignore error because we can not notify it.
|
||||
@@ -260,7 +258,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
try writer.sync(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
writer.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
@@ -268,7 +266,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
try writer.reentrantSync(value)
|
||||
}
|
||||
|
||||
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
// DatabaseQueue can't perform parallel reads.
|
||||
// Perform a blocking read instead.
|
||||
return DatabaseFuture(Result {
|
||||
@@ -311,7 +309,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
@@ -381,7 +379,7 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
writer.async { updates(.success($0)) }
|
||||
}
|
||||
|
||||
@@ -427,7 +425,7 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ import Dispatch
|
||||
///
|
||||
/// - ``dumpContent(format:to:)``
|
||||
/// - ``dumpRequest(_:format:to:)``
|
||||
/// - ``dumpSchema(to:)``
|
||||
/// - ``dumpSQL(_:format:to:)``
|
||||
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
|
||||
/// - ``DumpFormat``
|
||||
@@ -213,7 +214,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// - parameter value: A closure which accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the read access to the database.
|
||||
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
|
||||
func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void)
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
@@ -284,7 +285,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// - parameter value: A closure which accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the read access to the database.
|
||||
func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
|
||||
func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void)
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
@@ -342,7 +343,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
}
|
||||
|
||||
@@ -551,7 +552,7 @@ extension DatabaseReader {
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func readPublisher<Output>(
|
||||
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
|
||||
value: @escaping @Sendable (Database) throws -> Output)
|
||||
value: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Read<Output>
|
||||
{
|
||||
Deferred {
|
||||
@@ -601,7 +602,7 @@ extension DatabaseReader {
|
||||
func _addReadOnly<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if scheduler.immediateInitialValue() {
|
||||
@@ -619,16 +620,16 @@ extension DatabaseReader {
|
||||
}
|
||||
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
|
||||
} else {
|
||||
let cancellable = AnyDatabaseCancellable { }
|
||||
var isCancelled = false
|
||||
asyncRead { dbResult in
|
||||
if cancellable.isCancelled { return }
|
||||
guard !isCancelled else { return }
|
||||
|
||||
let result = dbResult.flatMap { db in
|
||||
Result { try observation.fetchInitialValue(db) }
|
||||
}
|
||||
|
||||
scheduler.schedule {
|
||||
if cancellable.isCancelled { return }
|
||||
guard !isCancelled else { return }
|
||||
do {
|
||||
try onChange(result.get())
|
||||
} catch {
|
||||
@@ -636,7 +637,7 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
}
|
||||
return cancellable
|
||||
return AnyDatabaseCancellable(cancel: { isCancelled = true })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -677,7 +678,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
try base.read(value)
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.asyncRead(value)
|
||||
}
|
||||
|
||||
@@ -686,7 +687,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
try base.unsafeRead(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.asyncUnsafeRead(value)
|
||||
}
|
||||
|
||||
@@ -697,7 +698,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
@@ -757,7 +758,7 @@ extension DatabaseSnapshotReader {
|
||||
}
|
||||
|
||||
// There is no such thing as an unsafe access to a snapshot.
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
asyncRead(value)
|
||||
}
|
||||
}
|
||||
@@ -169,16 +169,16 @@ public struct DatabaseRegion: Sendable {
|
||||
// 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
|
||||
|
||||
@@ -154,7 +154,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
try reader.sync(block)
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
reader.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
try reader.sync(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
reader.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
_addReadOnly(
|
||||
|
||||
@@ -292,7 +292,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -317,7 +317,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
return try reader.reentrantSync { db in
|
||||
let result = try value(db)
|
||||
if snapshotIsLost(db) {
|
||||
throw DatabaseError.snapshotIsLost()
|
||||
throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.")
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -330,7 +330,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
public func _add<Reducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable where Reducer: ValueReducer
|
||||
{
|
||||
_addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange)
|
||||
|
||||
@@ -52,7 +52,7 @@ import Foundation
|
||||
/// - ``isNull``
|
||||
/// - ``storage-swift.property``
|
||||
/// - ``Storage-swift.enum``
|
||||
public struct DatabaseValue: Hashable, Sendable {
|
||||
public struct DatabaseValue: Hashable {
|
||||
/// The SQLite storage.
|
||||
public let storage: Storage
|
||||
|
||||
@@ -219,6 +219,8 @@ extension DatabaseValue: StatementBinding {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue: Sendable { }
|
||||
|
||||
// @unchecked Sendable because Data is not Sendable in all target OS
|
||||
extension DatabaseValue.Storage: @unchecked Sendable { }
|
||||
|
||||
|
||||
@@ -222,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:
|
||||
///
|
||||
@@ -301,7 +306,7 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(
|
||||
public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -335,7 +340,7 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(
|
||||
public static func fetchOne(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -370,7 +375,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(
|
||||
public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -447,7 +452,7 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(
|
||||
public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -482,7 +487,7 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(
|
||||
public static func fetchOne(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -516,7 +521,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(
|
||||
public static func fetchSet(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -603,7 +608,7 @@ extension DatabaseValueConvertible {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -640,7 +645,7 @@ extension DatabaseValueConvertible {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
return try fetchOne(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -676,7 +681,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A set.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchSet(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -753,7 +758,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
@@ -787,7 +792,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
@@ -820,7 +825,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
try RowDecoder.fetchSet(db, self)
|
||||
}
|
||||
}
|
||||
@@ -181,7 +181,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// - parameter updates: A closure which accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the barrier access to the database.
|
||||
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void)
|
||||
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void)
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
///
|
||||
@@ -213,7 +213,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// <doc:Concurrency#Rule-2:-Mind-your-transactions> for more information.
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void)
|
||||
func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
@@ -292,7 +292,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// returned ``DatabaseFuture`` blocks a thread. You may prefer
|
||||
/// ``spawnConcurrentRead(_:)`` instead.
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T>
|
||||
func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T>
|
||||
|
||||
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
|
||||
/// Schedules read-only database operations for execution.
|
||||
@@ -340,7 +340,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// - parameter value: A closure which accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the read access to the database.
|
||||
func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void)
|
||||
func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void)
|
||||
}
|
||||
|
||||
extension DatabaseWriter {
|
||||
@@ -426,8 +426,8 @@ extension DatabaseWriter {
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - parameter completion: A closure called with the transaction result.
|
||||
public func asyncWrite<T>(
|
||||
_ updates: @escaping @Sendable (Database) throws -> T,
|
||||
completion: @escaping @Sendable (Database, Result<T, Error>) -> Void)
|
||||
_ updates: @escaping (Database) throws -> T,
|
||||
completion: @escaping (Database, Result<T, Error>) -> Void)
|
||||
{
|
||||
asyncWriteWithoutTransaction { db in
|
||||
do {
|
||||
@@ -557,7 +557,7 @@ extension DatabaseWriter {
|
||||
func _addWriteOnly<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
@@ -803,7 +803,7 @@ extension DatabaseWriter {
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<Output>(
|
||||
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
|
||||
updates: @escaping @Sendable (Database) throws -> Output)
|
||||
updates: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
{
|
||||
OnDemandFuture { fulfill in
|
||||
@@ -868,8 +868,8 @@ extension DatabaseWriter {
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<S, T, Output>(
|
||||
receiveOn scheduler: S = DispatchQueue.main,
|
||||
updates: @escaping @Sendable (Database) throws -> T,
|
||||
thenRead value: @escaping @Sendable (Database, T) throws -> Output)
|
||||
updates: @escaping (Database) throws -> T,
|
||||
thenRead value: @escaping (Database, T) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
@@ -885,7 +885,7 @@ extension DatabaseWriter {
|
||||
fulfill(.failure(error))
|
||||
return
|
||||
}
|
||||
self.spawnConcurrentRead { [updatesValue] dbResult in
|
||||
self.spawnConcurrentRead { dbResult in
|
||||
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
|
||||
}
|
||||
}
|
||||
@@ -1003,7 +1003,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
try base.read(value)
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.asyncRead(value)
|
||||
}
|
||||
|
||||
@@ -1012,7 +1012,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
try base.unsafeRead(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.asyncUnsafeRead(value)
|
||||
}
|
||||
|
||||
@@ -1023,7 +1023,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
@@ -1044,11 +1044,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
|
||||
try base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.asyncBarrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
base.asyncWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
@@ -1056,11 +1056,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
|
||||
try base.unsafeReentrantWrite(updates)
|
||||
}
|
||||
|
||||
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
base.concurrentRead(value)
|
||||
}
|
||||
|
||||
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.spawnConcurrentRead(value)
|
||||
}
|
||||
}
|
||||
@@ -152,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
|
||||
@@ -166,10 +171,7 @@ extension FetchRequest {
|
||||
///
|
||||
/// - parameter adapter: A closure that accepts a database connection and
|
||||
/// returns a row adapter.
|
||||
public func adapted(
|
||||
_ adapter: @escaping @Sendable (Database) throws -> any RowAdapter)
|
||||
-> AdaptedFetchRequest<Self>
|
||||
{
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
AdaptedFetchRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
@@ -179,11 +181,11 @@ extension FetchRequest {
|
||||
/// See ``FetchRequest/adapted(_:)``.
|
||||
public struct AdaptedFetchRequest<Base: FetchRequest> {
|
||||
let base: Base
|
||||
let adapter: @Sendable (Database) throws -> any RowAdapter
|
||||
let adapter: (Database) throws -> any RowAdapter
|
||||
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) {
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> any RowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
+23
-12
@@ -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
|
||||
@@ -1447,7 +1458,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(
|
||||
public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -1476,7 +1487,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(
|
||||
public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -1505,7 +1516,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(
|
||||
public static func fetchOne(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -1589,7 +1600,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(
|
||||
public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -1618,7 +1629,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(
|
||||
public static func fetchSet(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -1647,7 +1658,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(
|
||||
public static func fetchOne(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -1736,7 +1747,7 @@ extension Row {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [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, nil)
|
||||
@@ -1768,7 +1779,7 @@ extension Row {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A set of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Row> {
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Row> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
if let supplementaryFetch = request.supplementaryFetch {
|
||||
let rows = try fetchAll(request.statement, adapter: request.adapter)
|
||||
@@ -1804,7 +1815,7 @@ extension Row {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? {
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
guard let row = try fetchOne(request.statement, adapter: request.adapter) else {
|
||||
return nil
|
||||
@@ -1874,7 +1885,7 @@ extension FetchRequest<Row> {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of fetched rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
try Row.fetchAll(db, self)
|
||||
}
|
||||
|
||||
@@ -1895,7 +1906,7 @@ extension FetchRequest<Row> {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of fetched rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchSet(_ db: Database) throws -> Set<Row> {
|
||||
public func fetchSet(_ db: Database) throws -> Set<Row> {
|
||||
try Row.fetchSet(db, self)
|
||||
}
|
||||
|
||||
@@ -1916,7 +1927,7 @@ extension FetchRequest<Row> {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchOne(_ db: Database) throws -> Row? {
|
||||
public func fetchOne(_ db: Database) throws -> Row? {
|
||||
try Row.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -656,11 +656,11 @@ struct ChainedAdapter: RowAdapter {
|
||||
/// print(Array(adaptedRow.columnNames))
|
||||
/// ```
|
||||
public struct RenameColumnAdapter: RowAdapter {
|
||||
let transform: @Sendable (String) -> String
|
||||
let transform: (String) -> String
|
||||
|
||||
/// Creates a `RenameColumnAdapter` adapter that renames columns according to the
|
||||
/// provided transform function.
|
||||
public init(_ transform: @escaping @Sendable (String) -> String) {
|
||||
public init(_ transform: @escaping (String) -> String) {
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
|
||||
@@ -223,7 +223,7 @@ final class SerializedDatabase {
|
||||
}
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
func async(_ block: @escaping @Sendable (Database) -> Void) {
|
||||
func async(_ block: @escaping (Database) -> Void) {
|
||||
queue.async {
|
||||
block(self.db)
|
||||
self.preconditionNoUnsafeTransactionLeft(self.db)
|
||||
|
||||
@@ -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.
|
||||
@@ -312,7 +317,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(
|
||||
public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -346,7 +351,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(
|
||||
public static func fetchOne(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -384,7 +389,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(
|
||||
public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -461,7 +466,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(
|
||||
public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -496,7 +501,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(
|
||||
public static func fetchOne(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -530,7 +535,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(
|
||||
public static func fetchSet(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -619,7 +624,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -656,7 +661,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
return try fetchOne(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -692,7 +697,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchSet(request.statement, adapter: request.adapter)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import Foundation
|
||||
///
|
||||
/// - ``DefaultTransactionClock``
|
||||
/// - ``CustomTransactionClock``
|
||||
public protocol TransactionClock: Sendable {
|
||||
public protocol TransactionClock {
|
||||
/// Returns the date of the current transaction.
|
||||
///
|
||||
/// This function is called whenever a transaction starts - precisely
|
||||
@@ -36,7 +36,7 @@ extension TransactionClock where Self == CustomTransactionClock {
|
||||
///
|
||||
/// It is also called when the ``Database/transactionDate`` property is
|
||||
/// called, and the database connection is not in a transaction.
|
||||
public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
|
||||
public static func custom(_ now: @escaping (Database) throws -> Date) -> Self {
|
||||
CustomTransactionClock(now)
|
||||
}
|
||||
}
|
||||
@@ -53,9 +53,9 @@ public struct DefaultTransactionClock: TransactionClock {
|
||||
|
||||
/// A custom transaction clock.
|
||||
public struct CustomTransactionClock: TransactionClock {
|
||||
let _now: @Sendable (Database) throws -> Date
|
||||
let _now: (Database) throws -> Date
|
||||
|
||||
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
|
||||
public init(_ now: @escaping (Database) throws -> Date) {
|
||||
self._now = now
|
||||
}
|
||||
|
||||
|
||||
@@ -282,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
|
||||
@@ -566,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()
|
||||
@@ -782,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.
|
||||
///
|
||||
@@ -857,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:
|
||||
///
|
||||
@@ -874,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
|
||||
///
|
||||
@@ -884,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)
|
||||
@@ -942,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)
|
||||
@@ -1011,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)
|
||||
|
||||
@@ -1128,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)
|
||||
@@ -1182,7 +1232,7 @@ private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
|
||||
public struct DatabasePreUpdateEvent {
|
||||
|
||||
/// An event kind
|
||||
public enum Kind: CInt, Sendable {
|
||||
public enum Kind: CInt {
|
||||
/// SQLITE_INSERT
|
||||
case insert = 18
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -5,10 +5,8 @@
|
||||
/// `WALSnapshotTransaction` **takes ownership** of its reader
|
||||
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
|
||||
class WALSnapshotTransaction {
|
||||
// nil when closed
|
||||
private var reader: SerializedDatabase?
|
||||
// nil when closed
|
||||
private var release: ((_ isInsideTransaction: Bool) -> Void)?
|
||||
private let reader: SerializedDatabase
|
||||
private let release: (_ isInsideTransaction: Bool) -> Void
|
||||
|
||||
/// The state of the database at the beginning of the transaction.
|
||||
let walSnapshot: WALSnapshot
|
||||
@@ -48,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
|
||||
@@ -61,39 +61,21 @@ class WALSnapshotTransaction {
|
||||
}
|
||||
|
||||
deinit {
|
||||
close()
|
||||
Self.commitAndRelease(reader: reader, release: release)
|
||||
}
|
||||
|
||||
/// Executes database operations in the snapshot transaction, and
|
||||
/// returns their result after they have finished executing.
|
||||
func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
guard let reader else {
|
||||
throw DatabaseError.snapshotIsLost()
|
||||
}
|
||||
|
||||
func read<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
|
||||
return try reader.sync(value)
|
||||
try reader.sync(value)
|
||||
}
|
||||
|
||||
/// Schedules database operations for execution, and
|
||||
/// returns immediately.
|
||||
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
guard let reader else {
|
||||
value(.failure(DatabaseError.snapshotIsLost()))
|
||||
return
|
||||
}
|
||||
|
||||
func asyncRead(_ value: @escaping (Database) -> Void) {
|
||||
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
|
||||
reader.async { db in
|
||||
value(.success(db))
|
||||
}
|
||||
}
|
||||
|
||||
func close() {
|
||||
guard let reader, let release else { return }
|
||||
self.reader = nil
|
||||
self.release = nil
|
||||
Self.commitAndRelease(reader: reader, release: release)
|
||||
reader.async(value)
|
||||
}
|
||||
|
||||
private static func commitAndRelease(
|
||||
|
||||
@@ -391,17 +391,17 @@ extension Team: TableRecord {
|
||||
|
||||
### 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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -12,7 +12,7 @@ extension Database {
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// db.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// try db.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -40,7 +40,7 @@ extension Database {
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// db.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// try db.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -72,7 +72,7 @@ extension Database {
|
||||
/// // team
|
||||
/// // 1|Red
|
||||
/// // 2|Blue
|
||||
/// db.dumpTables(["player", "team"])
|
||||
/// try db.dumpTables(["player", "team"])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -111,7 +111,7 @@ extension Database {
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// db.dumpContent()
|
||||
/// try db.dumpContent()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -129,6 +129,9 @@ extension Database {
|
||||
///
|
||||
/// > 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.
|
||||
@@ -142,6 +145,40 @@ extension Database {
|
||||
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: -
|
||||
@@ -238,6 +275,26 @@ extension Database {
|
||||
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: """
|
||||
@@ -252,30 +309,46 @@ extension Database {
|
||||
""")
|
||||
for row in sqlRows {
|
||||
let name: String = row[1]
|
||||
if Database.isSQLiteInternalTable(name) || Database.isGRDBInternalTable(name) {
|
||||
if try ignoresObject(named: name) {
|
||||
continue
|
||||
}
|
||||
stream.writeln(row[0])
|
||||
}
|
||||
|
||||
let tables = try String
|
||||
.fetchAll(self, sql: """
|
||||
SELECT name
|
||||
FROM sqlite_master
|
||||
WHERE type = 'table'
|
||||
ORDER BY name COLLATE NOCASE
|
||||
""")
|
||||
.filter {
|
||||
!(Database.isSQLiteInternalTable($0) || Database.isGRDBInternalTable($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
|
||||
}
|
||||
if tables.isEmpty { return }
|
||||
stream.write("\n")
|
||||
try _dumpTables(tables, format: format, tableHeader: .always, stableOrder: true, to: &stream)
|
||||
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 {
|
||||
public enum DumpTableHeaderOptions: Sendable {
|
||||
/// Table names are only printed when several tables are printed.
|
||||
case automatic
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ extension DatabaseReader {
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// dbQueue.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// try dbQueue.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -34,7 +34,7 @@ extension DatabaseReader {
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// dbQueue.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// try dbQueue.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -65,7 +65,7 @@ extension DatabaseReader {
|
||||
/// // team
|
||||
/// // 1|Red
|
||||
/// // 2|Blue
|
||||
/// dbQueue.dumpTables(["player", "team"])
|
||||
/// try dbQueue.dumpTables(["player", "team"])
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -103,7 +103,7 @@ extension DatabaseReader {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// dbQueue.dumpContent()
|
||||
/// try dbQueue.dumpContent()
|
||||
/// ```
|
||||
///
|
||||
/// This prints the database schema as well as the content of all
|
||||
@@ -120,6 +120,9 @@ extension DatabaseReader {
|
||||
///
|
||||
/// > 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.
|
||||
@@ -134,4 +137,37 @@ extension DatabaseReader {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ import Foundation
|
||||
/// // Craig|200
|
||||
/// try db.dumpRequest(Player.all(), format: .debug())
|
||||
/// ```
|
||||
public struct DebugDumpFormat {
|
||||
public struct DebugDumpFormat: Sendable {
|
||||
/// A boolean value indicating if column labels are printed as the first
|
||||
/// line of output.
|
||||
public var header: Bool
|
||||
|
||||
@@ -27,7 +27,7 @@ import Foundation
|
||||
/// encoder.outputFormatting = .prettyPrinted
|
||||
/// try db.dumpRequest(Player.all(), format: .json(encoder))
|
||||
/// ```
|
||||
public struct JSONDumpFormat {
|
||||
public struct JSONDumpFormat: Sendable {
|
||||
/// The default `JSONEncoder` for database values.
|
||||
///
|
||||
/// It is configured so that blob values (`Data`) are encoded in the
|
||||
|
||||
@@ -13,7 +13,7 @@ import Foundation
|
||||
/// // score = 1000
|
||||
/// try db.dumpRequest(Player.all(), format: .line())
|
||||
/// ```
|
||||
public struct LineDumpFormat {
|
||||
public struct LineDumpFormat: Sendable {
|
||||
/// The string to print for NULL values.
|
||||
public var nullValue: String
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import Foundation
|
||||
/// // Craig|200
|
||||
/// try db.dumpRequest(Player.all(), format: .list())
|
||||
/// ```
|
||||
public struct ListDumpFormat {
|
||||
public struct ListDumpFormat: Sendable {
|
||||
/// A boolean value indicating if column labels are printed as the first
|
||||
/// line of output.
|
||||
public var header: Bool
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
/// // 'Craig',200
|
||||
/// try db.dumpRequest(Player.all(), format: .quote())
|
||||
/// ```
|
||||
public struct QuoteDumpFormat {
|
||||
public struct QuoteDumpFormat: Sendable {
|
||||
/// A boolean value indicating if column labels are printed as the first
|
||||
/// line of output.
|
||||
public var header: Bool
|
||||
|
||||
+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 { }
|
||||
@@ -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")
|
||||
|
||||
@@ -40,9 +40,9 @@ import Foundation
|
||||
/// - ``completedMigrations(_:)``
|
||||
/// - ``hasBeenSuperseded(_:)``
|
||||
/// - ``hasCompletedMigrations(_:)``
|
||||
public struct DatabaseMigrator: Sendable {
|
||||
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: Sendable {
|
||||
/// ``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: Sendable {
|
||||
/// 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.
|
||||
@@ -207,7 +207,7 @@ public struct DatabaseMigrator: Sendable {
|
||||
public mutating func registerMigration(
|
||||
_ identifier: String,
|
||||
foreignKeyChecks: ForeignKeyChecks = .deferred,
|
||||
migrate: @escaping @Sendable (Database) throws -> Void)
|
||||
migrate: @escaping (Database) throws -> Void)
|
||||
{
|
||||
let migrationChecks: Migration.ForeignKeyChecks
|
||||
switch foreignKeyChecks {
|
||||
@@ -264,7 +264,7 @@ public struct DatabaseMigrator: Sendable {
|
||||
/// from succeeding.
|
||||
public func asyncMigrate(
|
||||
_ writer: some DatabaseWriter,
|
||||
completion: @escaping @Sendable (Result<Database, Error>) -> Void)
|
||||
completion: @escaping (Result<Database, Error>) -> Void)
|
||||
{
|
||||
writer.asyncBarrierWriteWithoutTransaction { dbResult in
|
||||
do {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/// An internal struct that defines a migration.
|
||||
struct Migration: Sendable {
|
||||
struct Migration {
|
||||
enum ForeignKeyChecks {
|
||||
case deferred
|
||||
case immediate
|
||||
@@ -8,7 +8,7 @@ struct Migration: Sendable {
|
||||
|
||||
let identifier: String
|
||||
var foreignKeyChecks: ForeignKeyChecks
|
||||
let migrate: @Sendable (Database) throws -> Void
|
||||
let migrate: (Database) throws -> Void
|
||||
|
||||
func run(_ db: Database) throws {
|
||||
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
|
||||
|
||||
@@ -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>
|
||||
@@ -173,10 +173,7 @@ extension Association {
|
||||
|
||||
// SelectionRequest conformance
|
||||
extension Association {
|
||||
public func selectWhenConnected(
|
||||
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
|
||||
-> Self
|
||||
{
|
||||
public func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.selectWhenConnected { db in
|
||||
try selection(db).map(\.sqlSelection)
|
||||
@@ -184,10 +181,7 @@ extension Association {
|
||||
}
|
||||
}
|
||||
|
||||
public func annotatedWhenConnected(
|
||||
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
|
||||
-> Self
|
||||
{
|
||||
public func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.annotatedWhenConnected { db in
|
||||
try selection(db).map(\.sqlSelection)
|
||||
@@ -198,10 +192,7 @@ extension Association {
|
||||
|
||||
// FilteredRequest conformance
|
||||
extension Association {
|
||||
public func filterWhenConnected(
|
||||
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
|
||||
-> Self
|
||||
{
|
||||
public func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.filterWhenConnected { db in
|
||||
try predicate(db).sqlExpression
|
||||
@@ -212,10 +203,7 @@ extension Association {
|
||||
|
||||
// OrderedRequest conformance
|
||||
extension Association {
|
||||
public func orderWhenConnected(
|
||||
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm])
|
||||
-> Self
|
||||
{
|
||||
public func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.orderWhenConnected { db in
|
||||
try orderings(db).map(\.sqlOrdering)
|
||||
@@ -251,10 +239,7 @@ extension Association {
|
||||
|
||||
// AggregatingRequest conformance
|
||||
extension Association {
|
||||
public func groupWhenConnected(
|
||||
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible])
|
||||
-> Self
|
||||
{
|
||||
public func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.groupWhenConnected { db in
|
||||
try expressions(db).map(\.sqlExpression)
|
||||
@@ -262,10 +247,7 @@ extension Association {
|
||||
}
|
||||
}
|
||||
|
||||
public func havingWhenConnected(
|
||||
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
|
||||
-> Self
|
||||
{
|
||||
public func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.havingWhenConnected { db in
|
||||
try predicate(db).sqlExpression
|
||||
|
||||
@@ -117,7 +117,7 @@ extension QueryInterfaceRequest: FetchRequest {
|
||||
|
||||
extension QueryInterfaceRequest: SelectionRequest {
|
||||
public func selectWhenConnected(
|
||||
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
|
||||
_ selection: @escaping (Database) throws -> [any SQLSelectable])
|
||||
-> Self
|
||||
{
|
||||
with {
|
||||
@@ -281,7 +281,7 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
}
|
||||
|
||||
public func annotatedWhenConnected(
|
||||
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
|
||||
with selection: @escaping (Database) throws -> [any SQLSelectable])
|
||||
-> Self
|
||||
{
|
||||
with {
|
||||
@@ -294,7 +294,7 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
|
||||
extension QueryInterfaceRequest: FilteredRequest {
|
||||
public func filterWhenConnected(
|
||||
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
|
||||
_ predicate: @escaping (Database) throws -> any SQLExpressible)
|
||||
-> Self
|
||||
{
|
||||
with {
|
||||
@@ -307,7 +307,7 @@ extension QueryInterfaceRequest: FilteredRequest {
|
||||
|
||||
extension QueryInterfaceRequest: OrderedRequest {
|
||||
public func orderWhenConnected(
|
||||
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm])
|
||||
_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm])
|
||||
-> Self
|
||||
{
|
||||
with {
|
||||
@@ -354,7 +354,7 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
|
||||
extension QueryInterfaceRequest: AggregatingRequest {
|
||||
public func groupWhenConnected(
|
||||
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible])
|
||||
_ expressions: @escaping (Database) throws -> [any SQLExpressible])
|
||||
-> Self
|
||||
{
|
||||
with {
|
||||
@@ -365,7 +365,7 @@ extension QueryInterfaceRequest: AggregatingRequest {
|
||||
}
|
||||
|
||||
public func havingWhenConnected(
|
||||
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
|
||||
_ predicate: @escaping (Database) throws -> any SQLExpressible)
|
||||
-> Self
|
||||
{
|
||||
with {
|
||||
|
||||
@@ -58,7 +58,7 @@ public protocol SelectionRequest {
|
||||
///
|
||||
/// - parameter selection: A closure that accepts a database connection and
|
||||
/// returns an array of result columns.
|
||||
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self
|
||||
func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self
|
||||
|
||||
/// Appends result columns to the selected columns.
|
||||
///
|
||||
@@ -78,7 +78,7 @@ public protocol SelectionRequest {
|
||||
///
|
||||
/// - parameter selection: A closure that accepts a database connection and
|
||||
/// returns an array of result columns.
|
||||
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self
|
||||
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self
|
||||
}
|
||||
|
||||
extension SelectionRequest {
|
||||
@@ -240,7 +240,7 @@ public protocol FilteredRequest {
|
||||
///
|
||||
/// - parameter predicate: A closure that accepts a database connection and
|
||||
/// returns a boolean SQL expression.
|
||||
func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self
|
||||
func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self
|
||||
}
|
||||
|
||||
extension FilteredRequest {
|
||||
@@ -729,7 +729,7 @@ public protocol AggregatingRequest {
|
||||
///
|
||||
/// - parameter expressions: A closure that accepts a database connection
|
||||
/// and returns an array of SQL expressions.
|
||||
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]) -> Self
|
||||
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self
|
||||
|
||||
/// Filters the aggregated groups with a boolean SQL expression.
|
||||
///
|
||||
@@ -753,7 +753,7 @@ public protocol AggregatingRequest {
|
||||
///
|
||||
/// - parameter predicate: A closure that accepts a database connection and
|
||||
/// returns a boolean SQL expression.
|
||||
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self
|
||||
func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self
|
||||
}
|
||||
|
||||
extension AggregatingRequest {
|
||||
@@ -934,7 +934,7 @@ public protocol OrderedRequest {
|
||||
///
|
||||
/// - parameter orderings: A closure that accepts a database connection and
|
||||
/// returns an array of SQL ordering terms.
|
||||
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]) -> Self
|
||||
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self
|
||||
|
||||
/// Returns a request with reversed ordering.
|
||||
///
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -408,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)
|
||||
|
||||
|
||||
@@ -197,7 +197,7 @@ extension SQLRelation {
|
||||
}
|
||||
|
||||
extension SQLRelation: Refinable {
|
||||
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
|
||||
func selectWhenConnected(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
|
||||
with {
|
||||
$0.selectionPromise = DatabasePromise(selection)
|
||||
}
|
||||
@@ -228,7 +228,7 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
|
||||
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
|
||||
with {
|
||||
let old = $0.selectionPromise
|
||||
$0.selectionPromise = DatabasePromise { db in
|
||||
@@ -242,7 +242,7 @@ extension SQLRelation: Refinable {
|
||||
annotatedWhenConnected(with: { _ in selection })
|
||||
}
|
||||
|
||||
func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
|
||||
func filterWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
|
||||
with {
|
||||
if let old = $0.filterPromise {
|
||||
$0.filterPromise = DatabasePromise { db in
|
||||
@@ -259,7 +259,7 @@ extension SQLRelation: Refinable {
|
||||
filterWhenConnected { _ in predicate }
|
||||
}
|
||||
|
||||
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) -> Self {
|
||||
func orderWhenConnected(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
|
||||
with {
|
||||
$0.ordering = SQLRelation.Ordering(orderings: orderings)
|
||||
}
|
||||
@@ -313,13 +313,13 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self {
|
||||
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
|
||||
with {
|
||||
$0.groupPromise = DatabasePromise(expressions)
|
||||
}
|
||||
}
|
||||
|
||||
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
|
||||
func havingWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
|
||||
with {
|
||||
if let old = $0.havingExpressionPromise {
|
||||
$0.havingExpressionPromise = DatabasePromise { db in
|
||||
|
||||
@@ -800,7 +800,7 @@ extension Table {
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@Sendable public func fetchCount(_ db: Database) throws -> Int {
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try all().fetchCount(db)
|
||||
}
|
||||
}
|
||||
@@ -860,7 +860,7 @@ extension Table where RowDecoder: FetchableRecord {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
try all().fetchAll(db)
|
||||
}
|
||||
|
||||
@@ -880,7 +880,7 @@ extension Table where RowDecoder: FetchableRecord {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
try all().fetchOne(db)
|
||||
}
|
||||
}
|
||||
@@ -902,7 +902,7 @@ extension Table where RowDecoder: FetchableRecord & Hashable {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
try all().fetchSet(db)
|
||||
}
|
||||
}
|
||||
@@ -961,7 +961,7 @@ extension Table where RowDecoder == Row {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
try all().fetchAll(db)
|
||||
}
|
||||
|
||||
@@ -980,7 +980,7 @@ extension Table where RowDecoder == Row {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchOne(_ db: Database) throws -> Row? {
|
||||
public func fetchOne(_ db: Database) throws -> Row? {
|
||||
try all().fetchOne(db)
|
||||
}
|
||||
|
||||
@@ -999,7 +999,7 @@ extension Table where RowDecoder == Row {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchSet(_ db: Database) throws -> Set<Row> {
|
||||
public func fetchSet(_ db: Database) throws -> Set<Row> {
|
||||
try all().fetchSet(db)
|
||||
}
|
||||
}
|
||||
@@ -1034,7 +1034,7 @@ extension Table where RowDecoder: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
try all().fetchAll(db)
|
||||
}
|
||||
|
||||
@@ -1048,7 +1048,7 @@ extension Table where RowDecoder: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
try all().fetchOne(db)
|
||||
}
|
||||
}
|
||||
@@ -1061,7 +1061,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & Hashable {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
try all().fetchSet(db)
|
||||
}
|
||||
}
|
||||
@@ -1096,7 +1096,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
try all().fetchAll(db)
|
||||
}
|
||||
|
||||
@@ -1110,7 +1110,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
try all().fetchOne(db)
|
||||
}
|
||||
}
|
||||
@@ -1123,7 +1123,7 @@ extension Table where RowDecoder: DatabaseValueConvertible & StatementColumnConv
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
try all().fetchSet(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -565,3 +565,8 @@ public final class ColumnDefinition {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 { }
|
||||
@@ -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 { }
|
||||
@@ -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 { }
|
||||
@@ -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 { }
|
||||
@@ -466,7 +466,7 @@ extension Row {
|
||||
/// var jsonData: Data
|
||||
/// }
|
||||
/// ```
|
||||
public enum DatabaseDataEncodingStrategy: Sendable {
|
||||
public enum DatabaseDataEncodingStrategy {
|
||||
/// Encodes `Data` columns as SQL blob.
|
||||
case deferredToData
|
||||
|
||||
@@ -474,7 +474,7 @@ public enum DatabaseDataEncodingStrategy: Sendable {
|
||||
case text
|
||||
|
||||
/// Encodes `Data` column as the result of the user-provided function.
|
||||
case custom(@Sendable (Data) -> (any DatabaseValueConvertible)?)
|
||||
case custom((Data) -> (any DatabaseValueConvertible)?)
|
||||
|
||||
func encode(_ data: Data) -> DatabaseValue {
|
||||
switch self {
|
||||
@@ -508,7 +508,7 @@ public enum DatabaseDataEncodingStrategy: Sendable {
|
||||
/// var creationDate: Date
|
||||
/// }
|
||||
/// ```
|
||||
public enum DatabaseDateEncodingStrategy: Sendable {
|
||||
public enum DatabaseDateEncodingStrategy {
|
||||
/// The strategy that uses formatting from the Date structure.
|
||||
///
|
||||
/// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the
|
||||
@@ -538,7 +538,7 @@ public enum DatabaseDateEncodingStrategy: Sendable {
|
||||
case formatted(DateFormatter)
|
||||
|
||||
/// Encodes the result of the user-provided function
|
||||
case custom(@Sendable (Date) -> (any DatabaseValueConvertible)?)
|
||||
case custom((Date) -> (any DatabaseValueConvertible)?)
|
||||
|
||||
private static let iso8601Formatter: ISO8601DateFormatter = {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
@@ -585,7 +585,7 @@ public enum DatabaseDateEncodingStrategy: Sendable {
|
||||
/// var uuid: UUID
|
||||
/// }
|
||||
/// ```
|
||||
public enum DatabaseUUIDEncodingStrategy: Sendable {
|
||||
public enum DatabaseUUIDEncodingStrategy {
|
||||
/// The strategy that uses formatting from the UUID type.
|
||||
///
|
||||
/// It encodes UUIDs as 16-bytes data blobs.
|
||||
@@ -626,7 +626,7 @@ public enum DatabaseUUIDEncodingStrategy: Sendable {
|
||||
/// var playerID: String
|
||||
/// }
|
||||
/// ```
|
||||
public enum DatabaseColumnEncodingStrategy: Sendable {
|
||||
public enum DatabaseColumnEncodingStrategy {
|
||||
/// A key encoding strategy that doesn’t change key names during encoding.
|
||||
case useDefaultKeys
|
||||
|
||||
@@ -634,7 +634,7 @@ public enum DatabaseColumnEncodingStrategy: Sendable {
|
||||
case convertToSnakeCase
|
||||
|
||||
/// A key encoding strategy defined by the closure you supply.
|
||||
case custom(@Sendable (any CodingKey) -> String)
|
||||
case custom((any CodingKey) -> String)
|
||||
|
||||
func column(forKey key: some CodingKey) -> String {
|
||||
switch self {
|
||||
|
||||
@@ -7,6 +7,7 @@ extension FetchableRecord where Self: Decodable {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO GRDB7: make it a final class, and Sendable.
|
||||
/// An object that decodes fetchable records from database rows.
|
||||
///
|
||||
/// The example below shows how to decode an instance of a simple `Player`
|
||||
|
||||
@@ -52,7 +52,7 @@ extension FetchableRecord where Self: TableRecord {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(_ db: Database) throws -> [Self] {
|
||||
public static func fetchAll(_ db: Database) throws -> [Self] {
|
||||
try all().fetchAll(db)
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ extension FetchableRecord where Self: TableRecord {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(_ db: Database) throws -> Self? {
|
||||
public static func fetchOne(_ db: Database) throws -> Self? {
|
||||
try all().fetchOne(db)
|
||||
}
|
||||
}
|
||||
@@ -92,7 +92,7 @@ extension FetchableRecord where Self: TableRecord & Hashable {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(_ db: Database) throws -> Set<Self> {
|
||||
public static func fetchSet(_ db: Database) throws -> Set<Self> {
|
||||
try all().fetchSet(db)
|
||||
}
|
||||
}
|
||||
@@ -154,7 +154,7 @@ extension FetchableRecord where Self: TableRecord {
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll<Keys>(_ db: Database, keys: Keys)
|
||||
public static func fetchAll<Keys>(_ db: Database, keys: Keys)
|
||||
throws -> [Self]
|
||||
where Keys: Sequence, Keys.Element: DatabaseValueConvertible
|
||||
{
|
||||
@@ -182,7 +182,7 @@ extension FetchableRecord where Self: TableRecord {
|
||||
/// - key: A primary key value.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? {
|
||||
public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? {
|
||||
if key.databaseValue.isNull {
|
||||
// Don't hit the database
|
||||
return nil
|
||||
@@ -275,7 +275,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa
|
||||
/// - ids: A collection of primary keys.
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll<IDS>(_ db: Database, ids: IDS) throws -> [Self]
|
||||
public static func fetchAll<IDS>(_ db: Database, ids: IDS) throws -> [Self]
|
||||
where IDS: Collection, IDS.Element == ID
|
||||
{
|
||||
if ids.isEmpty {
|
||||
@@ -301,7 +301,7 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa
|
||||
/// - id: A primary key value.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(_ db: Database, id: ID) throws -> Self? {
|
||||
public static func fetchOne(_ db: Database, id: ID) throws -> Self? {
|
||||
try filter(id: id).fetchOne(db)
|
||||
}
|
||||
|
||||
@@ -346,7 +346,7 @@ extension FetchableRecord where Self: TableRecord & Hashable {
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: A set of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet<Keys>(_ db: Database, keys: Keys)
|
||||
public static func fetchSet<Keys>(_ db: Database, keys: Keys)
|
||||
throws -> Set<Self>
|
||||
where Keys: Sequence, Keys.Element: DatabaseValueConvertible
|
||||
{
|
||||
@@ -377,7 +377,7 @@ extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID:
|
||||
/// - ids: A collection of primary keys.
|
||||
/// - returns: A set of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet<IDS>(_ db: Database, ids: IDS) throws -> Set<Self>
|
||||
public static func fetchSet<IDS>(_ db: Database, ids: IDS) throws -> Set<Self>
|
||||
where IDS: Collection, IDS.Element == ID
|
||||
{
|
||||
if ids.isEmpty {
|
||||
@@ -449,11 +449,7 @@ extension FetchableRecord where Self: TableRecord {
|
||||
/// - keys: An array of key dictionaries.
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(
|
||||
_ db: Database,
|
||||
keys: [[String: (any DatabaseValueConvertible)?]])
|
||||
throws -> [Self]
|
||||
{
|
||||
public static func fetchAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] {
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return []
|
||||
@@ -477,11 +473,7 @@ extension FetchableRecord where Self: TableRecord {
|
||||
/// - key: A key dictionary.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(
|
||||
_ db: Database,
|
||||
key: [String: (any DatabaseValueConvertible)?]?)
|
||||
throws -> Self?
|
||||
{
|
||||
public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? {
|
||||
guard let key else {
|
||||
// Avoid hitting the database
|
||||
return nil
|
||||
@@ -535,11 +527,7 @@ extension FetchableRecord where Self: TableRecord & Hashable {
|
||||
/// - keys: An array of key dictionaries.
|
||||
/// - returns: A set of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(
|
||||
_ db: Database,
|
||||
keys: [[String: (any DatabaseValueConvertible)?]])
|
||||
throws -> Set<Self>
|
||||
{
|
||||
public static func fetchSet(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Set<Self> {
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return []
|
||||
|
||||
@@ -320,7 +320,7 @@ extension FetchableRecord {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(
|
||||
public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -348,7 +348,7 @@ extension FetchableRecord {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(
|
||||
public static func fetchOne(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -378,7 +378,7 @@ extension FetchableRecord where Self: Hashable {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(
|
||||
public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -449,7 +449,7 @@ extension FetchableRecord {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(
|
||||
public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -478,7 +478,7 @@ extension FetchableRecord {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(
|
||||
public static func fetchOne(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -509,7 +509,7 @@ extension FetchableRecord where Self: Hashable {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(
|
||||
public static func fetchSet(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -589,7 +589,7 @@ extension FetchableRecord {
|
||||
/// - sql: a FetchRequest.
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
if let supplementaryFetch = request.supplementaryFetch {
|
||||
let rows = try Row.fetchAll(request.statement, adapter: request.adapter)
|
||||
@@ -624,7 +624,7 @@ extension FetchableRecord {
|
||||
/// - sql: a FetchRequest.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
if let supplementaryFetch = request.supplementaryFetch {
|
||||
guard let row = try Row.fetchOne(request.statement, adapter: request.adapter) else {
|
||||
@@ -664,7 +664,7 @@ extension FetchableRecord where Self: Hashable {
|
||||
/// - sql: a FetchRequest.
|
||||
/// - returns: A set of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
if let supplementaryFetch = request.supplementaryFetch {
|
||||
let rows = try Row.fetchAll(request.statement, adapter: request.adapter)
|
||||
@@ -746,7 +746,7 @@ extension FetchRequest where RowDecoder: FetchableRecord {
|
||||
/// - sql: a FetchRequest.
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
@@ -774,7 +774,7 @@ extension FetchRequest where RowDecoder: FetchableRecord {
|
||||
/// - sql: a FetchRequest.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
@@ -805,7 +805,7 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable {
|
||||
/// - sql: a FetchRequest.
|
||||
/// - returns: A set of records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
try RowDecoder.fetchSet(db, self)
|
||||
}
|
||||
}
|
||||
@@ -854,6 +854,11 @@ public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: database cursors must be used from
|
||||
// a serialized database access dispatch queue.
|
||||
@available(*, unavailable)
|
||||
extension RecordCursor: Sendable { }
|
||||
|
||||
// MARK: - DatabaseDataDecodingStrategy
|
||||
|
||||
/// `DatabaseDataDecodingStrategy` specifies how `FetchableRecord` types that
|
||||
@@ -875,7 +880,7 @@ public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
|
||||
/// var myData: Data
|
||||
/// }
|
||||
/// ```
|
||||
public enum DatabaseDataDecodingStrategy: Sendable {
|
||||
public enum DatabaseDataDecodingStrategy {
|
||||
/// Decodes `Data` columns from SQL blobs and UTF8 text.
|
||||
case deferredToData
|
||||
|
||||
@@ -884,7 +889,7 @@ public enum DatabaseDataDecodingStrategy: Sendable {
|
||||
/// If the database value does not contain a suitable value, the function
|
||||
/// must return nil (GRDB will interpret this nil result as a conversion
|
||||
/// error, and react accordingly).
|
||||
case custom(@Sendable (DatabaseValue) -> Data?)
|
||||
case custom((DatabaseValue) -> Data?)
|
||||
}
|
||||
|
||||
// MARK: - DatabaseDateDecodingStrategy
|
||||
@@ -901,7 +906,7 @@ public enum DatabaseDataDecodingStrategy: Sendable {
|
||||
/// var name: String
|
||||
/// var registrationDate: Date // decoded from epoch timestamp
|
||||
/// }
|
||||
public enum DatabaseDateDecodingStrategy: Sendable {
|
||||
public enum DatabaseDateDecodingStrategy {
|
||||
/// The strategy that uses formatting from the Date structure.
|
||||
///
|
||||
/// It decodes numeric values as a number of seconds since Epoch
|
||||
@@ -942,7 +947,7 @@ public enum DatabaseDateDecodingStrategy: Sendable {
|
||||
/// If the database value does not contain a suitable value, the function
|
||||
/// must return nil (GRDB will interpret this nil result as a conversion
|
||||
/// error, and react accordingly).
|
||||
case custom(@Sendable (DatabaseValue) -> Date?)
|
||||
case custom((DatabaseValue) -> Date?)
|
||||
}
|
||||
|
||||
// MARK: - DatabaseColumnDecodingStrategy
|
||||
@@ -959,7 +964,7 @@ public enum DatabaseDateDecodingStrategy: Sendable {
|
||||
/// // Decoded from the player_id column
|
||||
/// var playerID: Int
|
||||
/// }
|
||||
public enum DatabaseColumnDecodingStrategy: Sendable {
|
||||
public enum DatabaseColumnDecodingStrategy {
|
||||
/// A key decoding strategy that doesn’t change key names during decoding.
|
||||
case useDefaultKeys
|
||||
|
||||
@@ -967,7 +972,7 @@ public enum DatabaseColumnDecodingStrategy: Sendable {
|
||||
case convertFromSnakeCase
|
||||
|
||||
/// A key decoding strategy defined by the closure you supply.
|
||||
case custom(@Sendable (String) -> CodingKey)
|
||||
case custom((String) -> CodingKey)
|
||||
|
||||
func key<K: CodingKey>(forColumn column: String) -> K? {
|
||||
switch self {
|
||||
|
||||
@@ -224,7 +224,7 @@ extension TableRecord {
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@Sendable public static func fetchCount(_ db: Database) throws -> Int {
|
||||
public static func fetchCount(_ db: Database) throws -> Int {
|
||||
try all().fetchCount(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ extension String {
|
||||
/// A type that controls GRDB string inflections.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
public struct Inflections {
|
||||
public struct Inflections: Sendable {
|
||||
private var pluralizeRules: [(NSRegularExpression, String)] = []
|
||||
private var singularizeRules: [(NSRegularExpression, String)] = []
|
||||
private var uncountablesRegularExpressions: [String: NSRegularExpression] = [:]
|
||||
|
||||
@@ -46,8 +46,6 @@ final class Pool<T> {
|
||||
}
|
||||
}
|
||||
|
||||
typealias ElementAndRelease = (element: T, release: @Sendable (PoolCompletion) -> Void)
|
||||
|
||||
private let makeElement: () throws -> T
|
||||
@ReadWriteBox private var items: [Item] = []
|
||||
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
|
||||
@@ -77,7 +75,7 @@ final class Pool<T> {
|
||||
|
||||
/// Returns a tuple (element, release)
|
||||
/// Client must call release(), only once, after the element has been used.
|
||||
func get() throws -> ElementAndRelease {
|
||||
func get() throws -> (element: T, release: (PoolCompletion) -> Void) {
|
||||
try barrierQueue.sync {
|
||||
itemsSemaphore.wait()
|
||||
itemsGroup.enter()
|
||||
@@ -109,7 +107,7 @@ final class Pool<T> {
|
||||
///
|
||||
/// - important: The `execute` argument is executed in a serial dispatch
|
||||
/// queue, so make sure you use the element asynchronously.
|
||||
func asyncGet(_ execute: @escaping @Sendable (Result<ElementAndRelease, Error>) -> Void) {
|
||||
func asyncGet(_ execute: @escaping (Result<(element: T, release: (PoolCompletion) -> Void), Error>) -> Void) {
|
||||
// Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
|
||||
// > We wait on the semaphore in the serial queue, which means that
|
||||
// > we’ll have at most one blocked thread when we reach maximum
|
||||
@@ -174,7 +172,7 @@ final class Pool<T> {
|
||||
|
||||
/// Asynchronously runs the `barrier` function when no element is used, and
|
||||
/// before any other element is dequeued.
|
||||
func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) {
|
||||
func asyncBarrier(execute barrier: @escaping () -> Void) {
|
||||
barrierQueue.async(flags: [.barrier]) {
|
||||
self.itemsGroup.wait()
|
||||
barrier()
|
||||
|
||||
+1
-23
@@ -67,7 +67,7 @@ extension Dictionary {
|
||||
}
|
||||
|
||||
extension DispatchQueue {
|
||||
private static let mainKey: DispatchSpecificKey<()> = {
|
||||
private static var mainKey: DispatchSpecificKey<()> = {
|
||||
let key = DispatchSpecificKey<()>()
|
||||
DispatchQueue.main.setSpecific(key: key, value: ())
|
||||
return key
|
||||
@@ -194,25 +194,3 @@ extension NSLocking {
|
||||
#if !canImport(ObjectiveC)
|
||||
@inlinable func autoreleasepool<Result>(invoking body: () throws -> Result) rethrows -> Result { try body() }
|
||||
#endif
|
||||
|
||||
/// A helper class that builds a DatabaseFuture without compiler errors
|
||||
/// regarding concurrency.
|
||||
final class UnsafeDatabaseFutureBuilder<T>: @unchecked Sendable {
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var result: Result<T, Error>? = nil
|
||||
|
||||
/// - precondition: MUST be called once.
|
||||
func setResultAndReleaseFuture(_ result: Result<T, Error>) {
|
||||
self.result = result
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
/// - precondition: MUST be called once.
|
||||
func makeFuture() -> DatabaseFuture<T> {
|
||||
DatabaseFuture { [self] in
|
||||
// Block the future until results are fetched
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
return try result!.get()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import Foundation
|
||||
|
||||
/// A protocol indicating that an activity or action supports cancellation.
|
||||
///
|
||||
/// ## Topics
|
||||
@@ -18,13 +16,8 @@ public protocol DatabaseCancellable {
|
||||
/// An `AnyDatabaseCancellable` instance automatically calls ``cancel()``
|
||||
/// when deinitialized.
|
||||
public class AnyDatabaseCancellable: DatabaseCancellable {
|
||||
private let lock = NSLock()
|
||||
private var _cancel: (() -> Void)?
|
||||
|
||||
var isCancelled: Bool {
|
||||
lock.withLock { _cancel == nil }
|
||||
}
|
||||
|
||||
/// Initializes the cancellable object with the given cancel-time closure.
|
||||
public init(cancel: @escaping () -> Void) {
|
||||
_cancel = cancel
|
||||
@@ -32,20 +25,21 @@ public class AnyDatabaseCancellable: DatabaseCancellable {
|
||||
|
||||
/// Creates a cancellable object that forwards cancellation to `base`.
|
||||
public convenience init(_ base: some DatabaseCancellable) {
|
||||
var cancellable = Optional.some(base)
|
||||
self.init {
|
||||
base.cancel()
|
||||
cancellable?.cancel()
|
||||
cancellable = nil // Release memory
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
cancel()
|
||||
_cancel?()
|
||||
}
|
||||
|
||||
public func cancel() {
|
||||
lock.lock()
|
||||
let cancel = _cancel
|
||||
// Don't prevent multiple concurrent calls to _cancel, because it is
|
||||
// pointless. But release memory!
|
||||
_cancel?()
|
||||
_cancel = nil
|
||||
lock.unlock()
|
||||
cancel?()
|
||||
}
|
||||
}
|
||||
@@ -353,11 +353,10 @@ extension ValueConcurrentObserver {
|
||||
let initialFetchTransaction = try result.get()
|
||||
// Second async jump because that's how
|
||||
// `DatabasePool.asyncWALSnapshotTransaction` has to be used.
|
||||
initialFetchTransaction.asyncRead { dbResult in
|
||||
initialFetchTransaction.asyncRead { db in
|
||||
do {
|
||||
let fetchedValue: Reducer.Fetched
|
||||
let initialRegion: DatabaseRegion
|
||||
let db = try dbResult.get()
|
||||
|
||||
switch self.trackingMode {
|
||||
case let .constantRegion(regions):
|
||||
@@ -431,9 +430,11 @@ extension ValueConcurrentObserver {
|
||||
// checkpointed. That's why we'll keep `initialFetchTransaction`
|
||||
// alive until the comparison is done.
|
||||
//
|
||||
// However, we want to close `initialFetchTransaction` as soon as
|
||||
// However, we want to release `initialFetchTransaction` as soon as
|
||||
// possible, so that the reader connection it holds becomes
|
||||
// available for other reads.
|
||||
// available for other reads. It will be released when this optional
|
||||
// is set to nil:
|
||||
var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction
|
||||
|
||||
databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in
|
||||
let events = self.lock.synchronized { self.notificationCallbacks?.events }
|
||||
@@ -446,7 +447,7 @@ extension ValueConcurrentObserver {
|
||||
// Was the database modified since the initial fetch?
|
||||
let isModified: Bool
|
||||
if let currentWALSnapshot = try? WALSnapshot(writerDB) {
|
||||
let ordering = initialFetchTransaction.walSnapshot.compare(currentWALSnapshot)
|
||||
let ordering = initialFetchTransaction!.walSnapshot.compare(currentWALSnapshot)
|
||||
assert(ordering <= 0, "Unexpected snapshot ordering")
|
||||
isModified = ordering < 0
|
||||
} else {
|
||||
@@ -454,9 +455,9 @@ extension ValueConcurrentObserver {
|
||||
isModified = true
|
||||
}
|
||||
|
||||
// Comparison done: close the WAL snapshot transaction
|
||||
// Comparison done: end the WAL snapshot transaction
|
||||
// and release its reader connection.
|
||||
initialFetchTransaction.close()
|
||||
initialFetchTransaction = nil
|
||||
|
||||
if isModified {
|
||||
events.databaseDidChange?()
|
||||
@@ -709,6 +710,13 @@ extension ValueConcurrentObserver: TransactionObserver {
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidChange() {
|
||||
// Database was modified!
|
||||
observationState.isModified = true
|
||||
// We can stop observing the current transaction
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if let region = observationState.region, region.isModified(by: event) {
|
||||
// Database was modified!
|
||||
|
||||
@@ -345,6 +345,13 @@ extension ValueWriteOnlyObserver: TransactionObserver {
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidChange() {
|
||||
// Database was modified!
|
||||
observationState.isModified = true
|
||||
// We can stop observing the current transaction
|
||||
stopObservingDatabaseChangesUntilNextTransaction()
|
||||
}
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if let region = observationState.region, region.isModified(by: event) {
|
||||
// Database was modified!
|
||||
|
||||
@@ -82,8 +82,8 @@ struct ValueObservationEvents: Refinable {
|
||||
}
|
||||
|
||||
typealias ValueObservationStart<T> = (
|
||||
_ onError: @escaping @Sendable (Error) -> Void,
|
||||
_ onChange: @escaping @Sendable (T) -> Void)
|
||||
_ onError: @escaping (Error) -> Void,
|
||||
_ onChange: @escaping (T) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
|
||||
extension ValueObservation: Refinable {
|
||||
@@ -138,8 +138,8 @@ extension ValueObservation: Refinable {
|
||||
public func start(
|
||||
in reader: some DatabaseReader,
|
||||
scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main),
|
||||
onError: @escaping @Sendable (Error) -> Void,
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
where Reducer: ValueReducer
|
||||
{
|
||||
@@ -310,6 +310,7 @@ extension ValueObservation {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: [GRDB7] Make it Sendable for easier integration with AsyncAlgorithms
|
||||
/// An asynchronous sequence of values observed by a ``ValueObservation``.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
@@ -703,7 +704,7 @@ extension ValueObservation {
|
||||
///
|
||||
/// - parameter fetch: The closure that fetches the observed value.
|
||||
public static func trackingConstantRegion<Value>(
|
||||
_ fetch: @escaping @Sendable (Database) throws -> Value)
|
||||
_ fetch: @escaping (Database) throws -> Value)
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
@@ -764,7 +765,7 @@ extension ValueObservation {
|
||||
public static func tracking<Value>(
|
||||
region: any DatabaseRegionConvertible,
|
||||
_ otherRegions: any DatabaseRegionConvertible...,
|
||||
fetch: @escaping @Sendable (Database) throws -> Value)
|
||||
fetch: @escaping (Database) throws -> Value)
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
@@ -820,7 +821,7 @@ extension ValueObservation {
|
||||
/// - parameter fetch: The closure that fetches the observed value.
|
||||
public static func tracking<Value>(
|
||||
regions: [any DatabaseRegionConvertible],
|
||||
fetch: @escaping @Sendable (Database) throws -> Value)
|
||||
fetch: @escaping (Database) throws -> Value)
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
@@ -877,7 +878,7 @@ extension ValueObservation {
|
||||
///
|
||||
/// - parameter fetch: The closure that fetches the observed value.
|
||||
public static func tracking<Value>(
|
||||
_ fetch: @escaping @Sendable (Database) throws -> Value)
|
||||
_ fetch: @escaping (Database) throws -> Value)
|
||||
-> Self
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{
|
||||
|
||||
@@ -17,11 +17,11 @@ public protocol ValueObservationScheduler {
|
||||
/// If the result is true, then this method was called on the main thread.
|
||||
func immediateInitialValue() -> Bool
|
||||
|
||||
func schedule(_ action: @escaping @Sendable () -> Void)
|
||||
func schedule(_ action: @escaping () -> Void)
|
||||
}
|
||||
|
||||
extension ValueObservationScheduler {
|
||||
func scheduleInitial(_ action: @escaping @Sendable () -> Void) {
|
||||
func scheduleInitial(_ action: @escaping () -> Void) {
|
||||
if immediateInitialValue() {
|
||||
action()
|
||||
} else {
|
||||
@@ -42,7 +42,7 @@ public struct AsyncValueObservationScheduler: ValueObservationScheduler {
|
||||
|
||||
public func immediateInitialValue() -> Bool { false }
|
||||
|
||||
public func schedule(_ action: @escaping @Sendable () -> Void) {
|
||||
public func schedule(_ action: @escaping () -> Void) {
|
||||
queue.async(execute: action)
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,7 @@ extension ValueObservationScheduler where Self == AsyncValueObservationScheduler
|
||||
/// A scheduler that notifies all values on the main `DispatchQueue`. The
|
||||
/// first value is immediately notified when the `ValueObservation`
|
||||
/// is started.
|
||||
public struct ImmediateValueObservationScheduler: ValueObservationScheduler {
|
||||
public struct ImmediateValueObservationScheduler: ValueObservationScheduler, Sendable {
|
||||
public init() { }
|
||||
|
||||
public func immediateInitialValue() -> Bool {
|
||||
@@ -86,7 +86,7 @@ public struct ImmediateValueObservationScheduler: ValueObservationScheduler {
|
||||
return true
|
||||
}
|
||||
|
||||
public func schedule(_ action: @escaping @Sendable () -> Void) {
|
||||
public func schedule(_ action: @escaping () -> Void) {
|
||||
DispatchQueue.main.async(execute: action)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -332,6 +332,7 @@
|
||||
56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; };
|
||||
56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; };
|
||||
6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; };
|
||||
648704BA2B8261070036480B /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = 648704B82B8261070036480B /* PrivacyInfo.xcprivacy */; };
|
||||
EED476F21CFD17270026A4EC /* GRDBCustomSQLite-USER.h in Headers */ = {isa = PBXBuildFile; fileRef = EED476F11CFD16FF0026A4EC /* GRDBCustomSQLite-USER.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
F3BA80661CFB2E55003DC1BA /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238701B9C75030082EB20 /* Configuration.swift */; };
|
||||
F3BA80671CFB2E55003DC1BA /* Database.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238711B9C75030082EB20 /* Database.swift */; };
|
||||
@@ -859,6 +860,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>"; };
|
||||
648704B82B8261070036480B /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
|
||||
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = "<group>"; };
|
||||
DC3773F719C8CBB3004FCF85 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
DC3773F819C8CBB3004FCF85 /* GRDB.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GRDB.h; sourceTree = "<group>"; };
|
||||
@@ -1743,6 +1745,7 @@
|
||||
children = (
|
||||
56A2FA3724424F4200E97D23 /* Export.swift */,
|
||||
566DDE11288D76400000DCFB /* Fixits.swift */,
|
||||
648704B82B8261070036480B /* PrivacyInfo.xcprivacy */,
|
||||
56A2386F1B9C75030082EB20 /* Core */,
|
||||
567B5BED2AD3285100629622 /* Dump */,
|
||||
5698AC291D9E5A480056AF8C /* FTS */,
|
||||
@@ -1919,6 +1922,7 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
648704BA2B8261070036480B /* PrivacyInfo.xcprivacy in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright (C) 2015-2023 Gwendal Roué
|
||||
Copyright (C) 2015-2024 Gwendal Roué
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
@@ -76,17 +76,15 @@ test_framework_GRDB: test_framework_GRDBOSX test_framework_GRDBiOS test_framewor
|
||||
test_framework_GRDBCustom: test_framework_GRDBCustomSQLiteOSX test_framework_GRDBCustomSQLiteiOS
|
||||
test_framework_SQLCipher: test_framework_SQLCipher3 test_framework_SQLCipher3Encrypted test_framework_SQLCipher4 test_framework_SQLCipher4Encrypted
|
||||
test_archive: test_universal_xcframework
|
||||
test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods test_CocoaPodsLint
|
||||
test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods
|
||||
test_CocoaPodsLint: test_CocoaPodsLint_GRDB
|
||||
test_demo_apps: test_GRDBDemoiOS test_GRDBCombineDemo test_GRDBAsyncDemo
|
||||
|
||||
test_framework_GRDBOSX:
|
||||
rm -rf TestResults.xcresult
|
||||
$(XCODEBUILD) \
|
||||
-project GRDB.xcodeproj \
|
||||
-scheme GRDB \
|
||||
-destination "platform=macOS" \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \
|
||||
GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \
|
||||
$(TEST_ACTIONS) \
|
||||
@@ -95,92 +93,76 @@ test_framework_GRDBOSX:
|
||||
test_framework_GRDBiOS: test_framework_GRDBiOS_maxTarget test_framework_GRDBiOS_minTarget
|
||||
|
||||
test_framework_GRDBiOS_maxTarget:
|
||||
rm -rf TestResults.xcresult
|
||||
$(XCODEBUILD) \
|
||||
-project GRDB.xcodeproj \
|
||||
-scheme GRDB \
|
||||
-destination $(MAX_IOS_DESTINATION) \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \
|
||||
GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_framework_GRDBiOS_minTarget:
|
||||
rm -rf TestResults.xcresult
|
||||
$(XCODEBUILD) \
|
||||
-project GRDB.xcodeproj \
|
||||
-scheme GRDB \
|
||||
-destination $(MIN_IOS_DESTINATION) \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_framework_GRDBtvOS: test_framework_GRDBtvOS_maxTarget test_framework_GRDBtvOS_minTarget
|
||||
|
||||
test_framework_GRDBtvOS_maxTarget:
|
||||
rm -rf TestResults.xcresult
|
||||
$(XCODEBUILD) \
|
||||
-project GRDB.xcodeproj \
|
||||
-scheme GRDB \
|
||||
-destination $(MAX_TVOS_DESTINATION) \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
OTHER_SWIFT_FLAGS=$(OTHER_SWIFT_FLAGS) \
|
||||
GCC_PREPROCESSOR_DEFINITIONS=$(GCC_PREPROCESSOR_DEFINITIONS) \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_framework_GRDBtvOS_minTarget:
|
||||
rm -rf TestResults.xcresult
|
||||
$(XCODEBUILD) \
|
||||
-project GRDB.xcodeproj \
|
||||
-scheme GRDB \
|
||||
-destination $(MIN_TVOS_DESTINATION) \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_framework_GRDBCustomSQLiteOSX: SQLiteCustom
|
||||
rm -rf TestResults.xcresult
|
||||
$(XCODEBUILD) \
|
||||
-project GRDBCustom.xcodeproj \
|
||||
-scheme GRDBCustom \
|
||||
-destination "platform=macOS" \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_framework_GRDBCustomSQLiteiOS: test_framework_GRDBCustomSQLiteiOS_maxTarget test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
test_framework_GRDBCustomSQLiteiOS_maxTarget: SQLiteCustom
|
||||
rm -rf TestResults.xcresult
|
||||
$(XCODEBUILD) \
|
||||
-project GRDBCustom.xcodeproj \
|
||||
-scheme GRDBCustom \
|
||||
-destination $(MAX_IOS_DESTINATION) \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_framework_GRDBCustomSQLiteiOS_minTarget: SQLiteCustom
|
||||
rm -rf TestResults.xcresult
|
||||
$(XCODEBUILD) \
|
||||
-project GRDBCustom.xcodeproj \
|
||||
-scheme GRDBCustom \
|
||||
-destination $(MIN_IOS_DESTINATION) \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_framework_SQLCipher3:
|
||||
ifdef POD
|
||||
cd Tests/CocoaPods/SQLCipher3 && \
|
||||
rm -rf TestResults.xcresult && \
|
||||
$(POD) install && \
|
||||
$(XCODEBUILD) \
|
||||
-workspace GRDBTests.xcworkspace \
|
||||
-scheme GRDBTests \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
build-for-testing test-without-building \
|
||||
$(XCPRETTY)
|
||||
else
|
||||
@@ -191,12 +173,10 @@ endif
|
||||
test_framework_SQLCipher3Encrypted:
|
||||
ifdef POD
|
||||
cd Tests/CocoaPods/SQLCipher3 && \
|
||||
rm -rf TestResults_encrypted.xcresult && \
|
||||
$(POD) install && \
|
||||
$(XCODEBUILD) \
|
||||
-workspace GRDBTests.xcworkspace \
|
||||
-scheme GRDBEncryptedTests \
|
||||
-resultBundlePath TestResults_encrypted.xcresult \
|
||||
build-for-testing test-without-building \
|
||||
$(XCPRETTY)
|
||||
else
|
||||
@@ -207,12 +187,10 @@ endif
|
||||
test_framework_SQLCipher4:
|
||||
ifdef POD
|
||||
cd Tests/CocoaPods/SQLCipher4 && \
|
||||
rm -rf TestResults.xcresult && \
|
||||
$(POD) install && \
|
||||
$(XCODEBUILD) \
|
||||
-workspace GRDBTests.xcworkspace \
|
||||
-scheme GRDBTests \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
build-for-testing test-without-building \
|
||||
$(XCPRETTY)
|
||||
else
|
||||
@@ -223,12 +201,10 @@ endif
|
||||
test_framework_SQLCipher4Encrypted:
|
||||
ifdef POD
|
||||
cd Tests/CocoaPods/SQLCipher4 && \
|
||||
rm -rf TestResults_encrypted.xcresult && \
|
||||
$(POD) install && \
|
||||
$(XCODEBUILD) \
|
||||
-workspace GRDBTests.xcworkspace \
|
||||
-scheme GRDBEncryptedTests \
|
||||
-resultBundlePath TestResults_encrypted.xcresult \
|
||||
build-for-testing test-without-building \
|
||||
$(XCPRETTY)
|
||||
else
|
||||
@@ -393,32 +369,26 @@ else
|
||||
endif
|
||||
|
||||
test_GRDBDemoiOS:
|
||||
rm -rf TestResults.xcresult
|
||||
$(XCODEBUILD) \
|
||||
-project Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj \
|
||||
-scheme GRDBDemoiOS \
|
||||
-destination $(MAX_IOS_DESTINATION) \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_GRDBCombineDemo:
|
||||
rm -rf TestResults.xcresult
|
||||
$(XCODEBUILD) \
|
||||
-project Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj \
|
||||
-scheme GRDBCombineDemo \
|
||||
-destination $(MAX_IOS_DESTINATION) \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
test_GRDBAsyncDemo:
|
||||
rm -rf TestResults.xcresult
|
||||
$(XCODEBUILD) \
|
||||
-project Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj \
|
||||
-scheme GRDBAsyncDemo \
|
||||
-destination $(MAX_IOS_DESTINATION) \
|
||||
-resultBundlePath TestResults.xcresult \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ let package = Package(
|
||||
name: "GRDB",
|
||||
dependencies: ["CSQLite"],
|
||||
path: "GRDB",
|
||||
resources: [.copy("PrivacyInfo.xcprivacy")],
|
||||
cSettings: cSettings,
|
||||
swiftSettings: swiftSettings),
|
||||
.testTarget(
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
|
||||
</p>
|
||||
|
||||
**Latest release**: October 29, 2023 • [version 6.21.0](https://github.com/groue/GRDB.swift/tree/v6.21.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
|
||||
**Latest release**: February 25, 2024 • [version 6.25.0](https://github.com/groue/GRDB.swift/tree/v6.25.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5
|
||||
//GCC_PREPROCESSOR_DEFINITIONS = $(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1
|
||||
//OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
|
||||
// Enable concurrency checks
|
||||
// Enable concurrency warning in Swift 5.5
|
||||
// https://twitter.com/olebegemann/status/1421144304127463427?lang=en
|
||||
// Those as commented out by default, until minimum support Xcode version can handle them.
|
||||
// OTHER_SWIFT_FLAGS = $(inherited) -Xfrontend -warn-concurrency -Xfrontend -enable-actor-data-race-checks
|
||||
// SWIFT_STRICT_CONCURRENCY = complete
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>6.21.0</string>
|
||||
<string>6.25.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -106,53 +106,59 @@ public class Recorder<Input, Failure: Error>: Subscriber {
|
||||
/// the expectation. For example, the Prefix expectation uses true, but
|
||||
/// the NextOne expectation uses false.
|
||||
func fulfillOnInput(_ expectation: XCTestExpectation, includingConsumed: Bool) {
|
||||
synchronized {
|
||||
preconditionCanFulfillExpectation()
|
||||
lock.lock()
|
||||
|
||||
preconditionCanFulfillExpectation()
|
||||
|
||||
let expectedFulfillmentCount = expectation.expectedFulfillmentCount
|
||||
|
||||
switch state {
|
||||
case .waitingForSubscription:
|
||||
let exp = RecorderExpectation.onInput(expectation, remainingCount: expectedFulfillmentCount)
|
||||
state = .waitingForSubscription(exp)
|
||||
lock.unlock()
|
||||
|
||||
let expectedFulfillmentCount = expectation.expectedFulfillmentCount
|
||||
case let .subscribed(subscription, _, elements):
|
||||
let maxFulfillmentCount = includingConsumed
|
||||
? elements.count
|
||||
: elements.count - consumedCount
|
||||
let fulfillmentCount = min(expectedFulfillmentCount, maxFulfillmentCount)
|
||||
|
||||
switch state {
|
||||
case .waitingForSubscription:
|
||||
let exp = RecorderExpectation.onInput(expectation, remainingCount: expectedFulfillmentCount)
|
||||
state = .waitingForSubscription(exp)
|
||||
|
||||
case let .subscribed(subscription, _, elements):
|
||||
let maxFulfillmentCount = includingConsumed
|
||||
? elements.count
|
||||
: elements.count - consumedCount
|
||||
let fulfillmentCount = min(expectedFulfillmentCount, maxFulfillmentCount)
|
||||
expectation.fulfill(count: fulfillmentCount)
|
||||
|
||||
let remainingCount = expectedFulfillmentCount - fulfillmentCount
|
||||
if remainingCount > 0 {
|
||||
let exp = RecorderExpectation.onInput(expectation, remainingCount: remainingCount)
|
||||
state = .subscribed(subscription, exp, elements)
|
||||
}
|
||||
|
||||
case .completed:
|
||||
expectation.fulfill(count: expectedFulfillmentCount)
|
||||
let remainingCount = expectedFulfillmentCount - fulfillmentCount
|
||||
if remainingCount > 0 {
|
||||
let exp = RecorderExpectation.onInput(expectation, remainingCount: remainingCount)
|
||||
state = .subscribed(subscription, exp, elements)
|
||||
}
|
||||
lock.unlock()
|
||||
expectation.fulfill(count: fulfillmentCount)
|
||||
|
||||
case .completed:
|
||||
lock.unlock()
|
||||
expectation.fulfill(count: expectedFulfillmentCount)
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers the expectation so that it gets fulfilled when
|
||||
/// publisher completes.
|
||||
func fulfillOnCompletion(_ expectation: XCTestExpectation) {
|
||||
synchronized {
|
||||
preconditionCanFulfillExpectation()
|
||||
lock.lock()
|
||||
|
||||
preconditionCanFulfillExpectation()
|
||||
|
||||
switch state {
|
||||
case .waitingForSubscription:
|
||||
let exp = RecorderExpectation.onCompletion(expectation)
|
||||
state = .waitingForSubscription(exp)
|
||||
lock.unlock()
|
||||
|
||||
switch state {
|
||||
case .waitingForSubscription:
|
||||
let exp = RecorderExpectation.onCompletion(expectation)
|
||||
state = .waitingForSubscription(exp)
|
||||
|
||||
case let .subscribed(subscription, _, elements):
|
||||
let exp = RecorderExpectation.onCompletion(expectation)
|
||||
state = .subscribed(subscription, exp, elements)
|
||||
|
||||
case .completed:
|
||||
expectation.fulfill()
|
||||
}
|
||||
case let .subscribed(subscription, _, elements):
|
||||
let exp = RecorderExpectation.onCompletion(expectation)
|
||||
state = .subscribed(subscription, exp, elements)
|
||||
lock.unlock()
|
||||
|
||||
case .completed:
|
||||
lock.unlock()
|
||||
expectation.fulfill()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,7 +177,7 @@ public class Recorder<Input, Failure: Error>: Subscriber {
|
||||
_ completion: Subscribers.Completion<Failure>?,
|
||||
_ remainingElements: ArraySlice<Input>,
|
||||
_ consume: (_ count: Int) -> ()) throws -> T)
|
||||
rethrows -> T
|
||||
rethrows -> T
|
||||
{
|
||||
try synchronized {
|
||||
let (elements, completion) = state.elementsAndCompletion
|
||||
@@ -217,58 +223,64 @@ public class Recorder<Input, Failure: Error>: Subscriber {
|
||||
}
|
||||
|
||||
public func receive(_ input: Input) -> Subscribers.Demand {
|
||||
return synchronized {
|
||||
switch state {
|
||||
case let .subscribed(subscription, exp, elements):
|
||||
var elements = elements
|
||||
elements.append(input)
|
||||
|
||||
if case let .onInput(expectation, remainingCount: remainingCount) = exp {
|
||||
assert(remainingCount > 0)
|
||||
expectation.fulfill()
|
||||
if remainingCount > 1 {
|
||||
let exp = RecorderExpectation.onInput(expectation, remainingCount: remainingCount - 1)
|
||||
state = .subscribed(subscription, exp, elements)
|
||||
} else {
|
||||
state = .subscribed(subscription, nil, elements)
|
||||
}
|
||||
} else {
|
||||
lock.lock()
|
||||
|
||||
switch state {
|
||||
case let .subscribed(subscription, exp, elements):
|
||||
var elements = elements
|
||||
elements.append(input)
|
||||
|
||||
if case let .onInput(expectation, remainingCount: remainingCount) = exp {
|
||||
assert(remainingCount > 0)
|
||||
expectation.fulfill()
|
||||
if remainingCount > 1 {
|
||||
let exp = RecorderExpectation.onInput(expectation, remainingCount: remainingCount - 1)
|
||||
state = .subscribed(subscription, exp, elements)
|
||||
} else {
|
||||
state = .subscribed(subscription, nil, elements)
|
||||
}
|
||||
|
||||
return .unlimited
|
||||
|
||||
case .waitingForSubscription:
|
||||
XCTFail("Publisher recorder got unexpected input before subscription: \(String(reflecting: input))")
|
||||
return .none
|
||||
|
||||
case .completed:
|
||||
XCTFail("Publisher recorder got unexpected input after completion: \(String(reflecting: input))")
|
||||
return .none
|
||||
} else {
|
||||
state = .subscribed(subscription, exp, elements)
|
||||
}
|
||||
|
||||
lock.unlock()
|
||||
return .unlimited
|
||||
|
||||
case .waitingForSubscription:
|
||||
lock.unlock()
|
||||
XCTFail("Publisher recorder got unexpected input before subscription: \(String(reflecting: input))")
|
||||
return .none
|
||||
|
||||
case .completed:
|
||||
lock.unlock()
|
||||
XCTFail("Publisher recorder got unexpected input after completion: \(String(reflecting: input))")
|
||||
return .none
|
||||
}
|
||||
}
|
||||
|
||||
public func receive(completion: Subscribers.Completion<Failure>) {
|
||||
synchronized {
|
||||
switch state {
|
||||
case let .subscribed(_, exp, elements):
|
||||
if let exp {
|
||||
switch exp {
|
||||
case let .onCompletion(expectation):
|
||||
expectation.fulfill()
|
||||
case let .onInput(expectation, remainingCount: remainingCount):
|
||||
expectation.fulfill(count: remainingCount)
|
||||
}
|
||||
lock.lock()
|
||||
|
||||
switch state {
|
||||
case let .subscribed(_, exp, elements):
|
||||
if let exp {
|
||||
switch exp {
|
||||
case let .onCompletion(expectation):
|
||||
expectation.fulfill()
|
||||
case let .onInput(expectation, remainingCount: remainingCount):
|
||||
expectation.fulfill(count: remainingCount)
|
||||
}
|
||||
state = .completed(elements, completion)
|
||||
|
||||
case .waitingForSubscription:
|
||||
XCTFail("Publisher recorder got unexpected completion before subscription: \(String(describing: completion))")
|
||||
|
||||
case .completed:
|
||||
XCTFail("Publisher recorder got unexpected completion after completion: \(String(describing: completion))")
|
||||
}
|
||||
state = .completed(elements, completion)
|
||||
lock.unlock()
|
||||
|
||||
case .waitingForSubscription:
|
||||
lock.unlock()
|
||||
XCTFail("Publisher recorder got unexpected completion before subscription: \(String(describing: completion))")
|
||||
|
||||
case .completed:
|
||||
lock.unlock()
|
||||
XCTFail("Publisher recorder got unexpected completion after completion: \(String(describing: completion))")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1733,6 +1733,81 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testTableBelongsToView() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE child (foo);
|
||||
CREATE VIEW parent AS SELECT 1 AS bar;
|
||||
""")
|
||||
|
||||
let child = Table("child")
|
||||
let parent = Table("parent")
|
||||
let foreignKey = ForeignKey(["foo"], to: ["bar"])
|
||||
let association = child.belongsTo(parent, using: foreignKey)
|
||||
|
||||
try assertEqualSQL(db, child.joining(required: association), """
|
||||
SELECT "child".* \
|
||||
FROM "child" \
|
||||
JOIN "parent" ON "parent"."bar" = "child"."foo"
|
||||
""")
|
||||
try assertEqualSQL(db, child.joining(optional: association), """
|
||||
SELECT "child".* \
|
||||
FROM "child" \
|
||||
LEFT JOIN "parent" ON "parent"."bar" = "child"."foo"
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testViewBelongsToTable() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW child AS SELECT 1 AS foo;
|
||||
CREATE TABLE parent(id INTEGER PRIMARY KEY);
|
||||
""")
|
||||
|
||||
let child = Table("child")
|
||||
let parent = Table("parent")
|
||||
let foreignKey = ForeignKey(["foo"])
|
||||
let association = child.belongsTo(parent, using: foreignKey)
|
||||
|
||||
try assertEqualSQL(db, child.joining(required: association), """
|
||||
SELECT "child".* \
|
||||
FROM "child" \
|
||||
JOIN "parent" ON "parent"."id" = "child"."foo"
|
||||
""")
|
||||
try assertEqualSQL(db, child.joining(optional: association), """
|
||||
SELECT "child".* \
|
||||
FROM "child" \
|
||||
LEFT JOIN "parent" ON "parent"."id" = "child"."foo"
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func testViewBelongsToView() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW child AS SELECT 1 AS foo;
|
||||
CREATE VIEW parent AS SELECT 1 AS bar;
|
||||
""")
|
||||
|
||||
let child = Table("child")
|
||||
let parent = Table("parent")
|
||||
let foreignKey = ForeignKey(["foo"], to: ["bar"])
|
||||
let association = child.belongsTo(parent, using: foreignKey)
|
||||
|
||||
try assertEqualSQL(db, child.joining(required: association), """
|
||||
SELECT "child".* \
|
||||
FROM "child" \
|
||||
JOIN "parent" ON "parent"."bar" = "child"."foo"
|
||||
""")
|
||||
try assertEqualSQL(db, child.joining(optional: association), """
|
||||
SELECT "child".* \
|
||||
FROM "child" \
|
||||
LEFT JOIN "parent" ON "parent"."bar" = "child"."foo"
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for https://github.com/groue/GRDB.swift/issues/495
|
||||
func testFetchCount() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -289,4 +289,106 @@ class ColumnInfoTests: GRDBTestCase {
|
||||
_ = try db.columns(in: "t1")
|
||||
}
|
||||
}
|
||||
|
||||
func testUnknownSchema() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE t (id INTEGER)")
|
||||
do {
|
||||
_ = try db.columns(in: "t", in: "invalid")
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message, "no such schema: invalid")
|
||||
XCTAssertEqual(error.description, "SQLite error 1: no such schema: invalid")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testSpecifiedMainSchema() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE t (id INTEGER)")
|
||||
let columns = try db.columns(in: "t")
|
||||
XCTAssertEqual(columns.count, 1)
|
||||
XCTAssertEqual(columns[0].name, "id")
|
||||
XCTAssertEqual(columns[0].type, "INTEGER")
|
||||
}
|
||||
}
|
||||
|
||||
func testSpecifiedSchemaWithTableNameCollisions() throws {
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Avoid error due to key not being provided:
|
||||
// file is not a database - while executing `ATTACH DATABASE...`
|
||||
throw XCTSkip("This test does not support encrypted databases")
|
||||
#endif
|
||||
|
||||
let attached = try makeDatabaseQueue(filename: "attached1")
|
||||
try attached.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE t (id2 TEXT)")
|
||||
}
|
||||
let main = try makeDatabaseQueue(filename: "main")
|
||||
try main.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE t (id1 INTEGER)")
|
||||
try db.execute(literal: "ATTACH DATABASE \(attached.path) AS attached")
|
||||
|
||||
let columnsMain = try db.columns(in: "t", in: "main")
|
||||
XCTAssertEqual(columnsMain.count, 1)
|
||||
XCTAssertEqual(columnsMain[0].name, "id1")
|
||||
XCTAssertEqual(columnsMain[0].type, "INTEGER")
|
||||
|
||||
let columnsAttached = try db.columns(in: "t", in: "attached")
|
||||
XCTAssertEqual(columnsAttached.count, 1)
|
||||
XCTAssertEqual(columnsAttached[0].name, "id2")
|
||||
XCTAssertEqual(columnsAttached[0].type, "TEXT")
|
||||
}
|
||||
}
|
||||
|
||||
// The `t` table in the attached database should never
|
||||
// be found unless explicitly specified as it is after
|
||||
// `main.t` in resolution order.
|
||||
func testUnspecifiedSchemaWithTableNameCollisions() throws {
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Avoid error due to key not being provided:
|
||||
// file is not a database - while executing `ATTACH DATABASE...`
|
||||
throw XCTSkip("This test does not support encrypted databases")
|
||||
#endif
|
||||
|
||||
let attached = try makeDatabaseQueue(filename: "attached1")
|
||||
try attached.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE t (id2 TEXT)")
|
||||
}
|
||||
let main = try makeDatabaseQueue(filename: "main")
|
||||
try main.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE t (id1 INTEGER)")
|
||||
try db.execute(literal: "ATTACH DATABASE \(attached.path) AS attached")
|
||||
|
||||
let columnsMain = try db.columns(in: "t")
|
||||
XCTAssertEqual(columnsMain.count, 1)
|
||||
XCTAssertEqual(columnsMain[0].name, "id1")
|
||||
XCTAssertEqual(columnsMain[0].type, "INTEGER")
|
||||
}
|
||||
}
|
||||
|
||||
func testUnspecifiedSchemaFindsAttachedDatabase() throws {
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Avoid error due to key not being provided:
|
||||
// file is not a database - while executing `ATTACH DATABASE...`
|
||||
throw XCTSkip("This test does not support encrypted databases")
|
||||
#endif
|
||||
|
||||
let attached = try makeDatabaseQueue(filename: "attached1")
|
||||
try attached.inDatabase { db in
|
||||
try db.execute(sql: "CREATE TABLE t (id2 TEXT)")
|
||||
}
|
||||
let main = try makeDatabaseQueue(filename: "main")
|
||||
try main.inDatabase { db in
|
||||
try db.execute(literal: "ATTACH DATABASE \(attached.path) AS attached")
|
||||
|
||||
let columnsMain = try db.columns(in: "t")
|
||||
XCTAssertEqual(columnsMain.count, 1)
|
||||
XCTAssertEqual(columnsMain[0].name, "id2")
|
||||
XCTAssertEqual(columnsMain[0].type, "TEXT")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,47 +6,40 @@ class DatabaseConfigurationTests: GRDBTestCase {
|
||||
|
||||
func testPrepareDatabase() throws {
|
||||
// prepareDatabase is called when connection opens
|
||||
class Context {
|
||||
var connectionCount = 0
|
||||
}
|
||||
let context = Context()
|
||||
|
||||
var connectionCount = 0
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
context.connectionCount += 1
|
||||
connectionCount += 1
|
||||
}
|
||||
|
||||
_ = try DatabaseQueue(configuration: configuration)
|
||||
XCTAssertEqual(context.connectionCount, 1)
|
||||
XCTAssertEqual(connectionCount, 1)
|
||||
|
||||
_ = try makeDatabaseQueue(configuration: configuration)
|
||||
XCTAssertEqual(context.connectionCount, 2)
|
||||
XCTAssertEqual(connectionCount, 2)
|
||||
|
||||
let pool = try makeDatabasePool(configuration: configuration)
|
||||
XCTAssertEqual(context.connectionCount, 3)
|
||||
XCTAssertEqual(connectionCount, 3)
|
||||
|
||||
try pool.read { _ in }
|
||||
XCTAssertEqual(context.connectionCount, 4)
|
||||
XCTAssertEqual(connectionCount, 4)
|
||||
|
||||
try pool.makeSnapshot().read { _ in }
|
||||
XCTAssertEqual(context.connectionCount, 5)
|
||||
XCTAssertEqual(connectionCount, 5)
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
try pool.makeSnapshotPool().read { _ in }
|
||||
XCTAssertEqual(context.connectionCount, 6)
|
||||
XCTAssertEqual(connectionCount, 6)
|
||||
#endif
|
||||
}
|
||||
|
||||
func testPrepareDatabaseError() throws {
|
||||
struct TestError: Error { }
|
||||
class Context {
|
||||
var error: TestError?
|
||||
}
|
||||
let context = Context()
|
||||
var error: TestError?
|
||||
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
if let error = context.error {
|
||||
if let error {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -54,36 +47,36 @@ class DatabaseConfigurationTests: GRDBTestCase {
|
||||
// TODO: what about in-memory DatabaseQueue???
|
||||
|
||||
do {
|
||||
context.error = TestError()
|
||||
error = TestError()
|
||||
_ = try makeDatabaseQueue(configuration: configuration)
|
||||
XCTFail("Expected TestError")
|
||||
} catch is TestError { }
|
||||
|
||||
do {
|
||||
context.error = TestError()
|
||||
error = TestError()
|
||||
_ = try makeDatabasePool(configuration: configuration)
|
||||
XCTFail("Expected TestError")
|
||||
} catch is TestError { }
|
||||
|
||||
do {
|
||||
context.error = nil
|
||||
error = nil
|
||||
let pool = try makeDatabasePool(configuration: configuration)
|
||||
|
||||
do {
|
||||
context.error = TestError()
|
||||
error = TestError()
|
||||
try pool.read { _ in }
|
||||
XCTFail("Expected TestError")
|
||||
} catch is TestError { }
|
||||
|
||||
do {
|
||||
context.error = TestError()
|
||||
error = TestError()
|
||||
_ = try pool.makeSnapshot()
|
||||
XCTFail("Expected TestError")
|
||||
} catch is TestError { }
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
do {
|
||||
context.error = TestError()
|
||||
error = TestError()
|
||||
_ = try pool.makeSnapshotPool()
|
||||
XCTFail("Expected TestError")
|
||||
} catch is TestError { }
|
||||
|
||||
@@ -1196,6 +1196,164 @@ final class DatabaseDumpTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database schema dump
|
||||
|
||||
func test_dumpSchema() throws {
|
||||
try makeRugbyDatabase().read { db in
|
||||
let stream = TestStream()
|
||||
try db.dumpSchema(to: stream)
|
||||
XCTAssertEqual(stream.output, """
|
||||
sqlite_master
|
||||
CREATE TABLE "player" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "teamId" TEXT REFERENCES "team"("id"), "name" TEXT NOT NULL);
|
||||
CREATE INDEX "player_on_teamId" ON "player"("teamId");
|
||||
CREATE TABLE "team" ("id" TEXT PRIMARY KEY NOT NULL, "name" TEXT NOT NULL, "color" TEXT NOT NULL);
|
||||
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func test_dumpSchema_empty_database() throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
let stream = TestStream()
|
||||
try db.dumpSchema(to: stream)
|
||||
XCTAssertEqual(stream.output, """
|
||||
sqlite_master
|
||||
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func test_dumpSchema_empty_tables() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.execute(literal: """
|
||||
CREATE TABLE blue(name);
|
||||
CREATE TABLE red(name);
|
||||
CREATE TABLE yellow(name);
|
||||
INSERT INTO red VALUES ('vermillon')
|
||||
""")
|
||||
let stream = TestStream()
|
||||
try db.dumpSchema(to: stream)
|
||||
XCTAssertEqual(stream.output, """
|
||||
sqlite_master
|
||||
CREATE TABLE blue(name);
|
||||
CREATE TABLE red(name);
|
||||
CREATE TABLE yellow(name);
|
||||
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func test_dumpSchema_sqlite_master_ordering() throws {
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.execute(literal: """
|
||||
CREATE TABLE blue(name);
|
||||
CREATE TABLE RED(name);
|
||||
CREATE TABLE yellow(name);
|
||||
CREATE INDEX index_blue1 ON blue(name);
|
||||
CREATE INDEX INDEX_blue2 ON blue(name);
|
||||
CREATE INDEX indexRed1 ON RED(name);
|
||||
CREATE INDEX INDEXRed2 ON RED(name);
|
||||
CREATE VIEW colors1 AS SELECT name FROM blue;
|
||||
CREATE VIEW COLORS2 AS SELECT name FROM blue UNION SELECT name FROM yellow;
|
||||
CREATE TRIGGER update_blue UPDATE OF name ON blue
|
||||
BEGIN
|
||||
DELETE FROM RED;
|
||||
END;
|
||||
CREATE TRIGGER update_RED UPDATE OF name ON RED
|
||||
BEGIN
|
||||
DELETE FROM yellow;
|
||||
END;
|
||||
""")
|
||||
let stream = TestStream()
|
||||
try db.dumpSchema(to: stream)
|
||||
XCTAssertEqual(stream.output, """
|
||||
sqlite_master
|
||||
CREATE TABLE blue(name);
|
||||
CREATE INDEX index_blue1 ON blue(name);
|
||||
CREATE INDEX INDEX_blue2 ON blue(name);
|
||||
CREATE TRIGGER update_blue UPDATE OF name ON blue
|
||||
BEGIN
|
||||
DELETE FROM RED;
|
||||
END;
|
||||
CREATE VIEW colors1 AS SELECT name FROM blue;
|
||||
CREATE VIEW COLORS2 AS SELECT name FROM blue UNION SELECT name FROM yellow;
|
||||
CREATE TABLE RED(name);
|
||||
CREATE INDEX indexRed1 ON RED(name);
|
||||
CREATE INDEX INDEXRed2 ON RED(name);
|
||||
CREATE TRIGGER update_RED UPDATE OF name ON RED
|
||||
BEGIN
|
||||
DELETE FROM yellow;
|
||||
END;
|
||||
CREATE TABLE yellow(name);
|
||||
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func test_dumpSchema_ignores_shadow_tables() throws {
|
||||
guard sqlite3_libversion_number() >= 3037000 else {
|
||||
throw XCTSkip("Can't detect shadow tables")
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.create(table: "document") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("body")
|
||||
}
|
||||
|
||||
try db.execute(sql: "INSERT INTO document VALUES (1, 'Hello world!')")
|
||||
|
||||
try db.create(virtualTable: "document_ft", using: FTS4()) { t in
|
||||
t.synchronize(withTable: "document")
|
||||
t.column("body")
|
||||
}
|
||||
|
||||
let stream = TestStream()
|
||||
try db.dumpSchema(to: stream)
|
||||
print(stream.output)
|
||||
XCTAssertEqual(stream.output, """
|
||||
sqlite_master
|
||||
CREATE TABLE "document" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "body");
|
||||
CREATE TRIGGER "__document_ft_ai" AFTER INSERT ON "document" BEGIN
|
||||
INSERT INTO "document_ft"("docid", "body") VALUES(new."id", new."body");
|
||||
END;
|
||||
CREATE TRIGGER "__document_ft_au" AFTER UPDATE ON "document" BEGIN
|
||||
INSERT INTO "document_ft"("docid", "body") VALUES(new."id", new."body");
|
||||
END;
|
||||
CREATE TRIGGER "__document_ft_bd" BEFORE DELETE ON "document" BEGIN
|
||||
DELETE FROM "document_ft" WHERE docid=old."id";
|
||||
END;
|
||||
CREATE TRIGGER "__document_ft_bu" BEFORE UPDATE ON "document" BEGIN
|
||||
DELETE FROM "document_ft" WHERE docid=old."id";
|
||||
END;
|
||||
CREATE VIRTUAL TABLE "document_ft" USING fts4(body, content="document");
|
||||
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func test_dumpSchema_ignores_GRDB_internal_tables() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("v1") { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
try dbQueue.read { db in
|
||||
let stream = TestStream()
|
||||
try db.dumpSchema(to: stream)
|
||||
print(stream.output)
|
||||
XCTAssertEqual(stream.output, """
|
||||
sqlite_master
|
||||
CREATE TABLE "player" ("id" INTEGER PRIMARY KEY AUTOINCREMENT);
|
||||
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database content dump
|
||||
|
||||
func test_dumpContent() throws {
|
||||
@@ -1336,6 +1494,78 @@ final class DatabaseDumpTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_dumpContent_ignores_shadow_tables() throws {
|
||||
guard sqlite3_libversion_number() >= 3037000 else {
|
||||
throw XCTSkip("Can't detect shadow tables")
|
||||
}
|
||||
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.create(table: "document") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("body")
|
||||
}
|
||||
|
||||
try db.execute(sql: "INSERT INTO document VALUES (1, 'Hello world!')")
|
||||
|
||||
try db.create(virtualTable: "document_ft", using: FTS4()) { t in
|
||||
t.synchronize(withTable: "document")
|
||||
t.column("body")
|
||||
}
|
||||
|
||||
let stream = TestStream()
|
||||
try db.dumpContent(to: stream)
|
||||
print(stream.output)
|
||||
XCTAssertEqual(stream.output, """
|
||||
sqlite_master
|
||||
CREATE TABLE "document" ("id" INTEGER PRIMARY KEY AUTOINCREMENT, "body");
|
||||
CREATE TRIGGER "__document_ft_ai" AFTER INSERT ON "document" BEGIN
|
||||
INSERT INTO "document_ft"("docid", "body") VALUES(new."id", new."body");
|
||||
END;
|
||||
CREATE TRIGGER "__document_ft_au" AFTER UPDATE ON "document" BEGIN
|
||||
INSERT INTO "document_ft"("docid", "body") VALUES(new."id", new."body");
|
||||
END;
|
||||
CREATE TRIGGER "__document_ft_bd" BEFORE DELETE ON "document" BEGIN
|
||||
DELETE FROM "document_ft" WHERE docid=old."id";
|
||||
END;
|
||||
CREATE TRIGGER "__document_ft_bu" BEFORE UPDATE ON "document" BEGIN
|
||||
DELETE FROM "document_ft" WHERE docid=old."id";
|
||||
END;
|
||||
CREATE VIRTUAL TABLE "document_ft" USING fts4(body, content="document");
|
||||
|
||||
document
|
||||
1|Hello world!
|
||||
|
||||
document_ft
|
||||
Hello world!
|
||||
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
func test_dumpContent_ignores_GRDB_internal_tables() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("v1") { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
}
|
||||
}
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
try dbQueue.read { db in
|
||||
let stream = TestStream()
|
||||
try db.dumpContent(to: stream)
|
||||
print(stream.output)
|
||||
XCTAssertEqual(stream.output, """
|
||||
sqlite_master
|
||||
CREATE TABLE "player" ("id" INTEGER PRIMARY KEY AUTOINCREMENT);
|
||||
|
||||
player
|
||||
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Support Databases
|
||||
|
||||
private func makeValuesDatabase() throws -> DatabaseQueue {
|
||||
|
||||
@@ -122,7 +122,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
}
|
||||
|
||||
let expectation = self.expectation(description: "")
|
||||
migrator.asyncMigrate(writer, completion: { [migrator2] dbResult in
|
||||
migrator.asyncMigrate(writer, completion: { dbResult in
|
||||
// No migration error
|
||||
let db = try! dbResult.get()
|
||||
|
||||
@@ -789,17 +789,13 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
|
||||
class Context {
|
||||
var witness = 1
|
||||
}
|
||||
let context = Context()
|
||||
|
||||
var witness = 1
|
||||
migrator.registerMigration("1") { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t1(id INTEGER PRIMARY KEY);
|
||||
INSERT INTO t1(id) VALUES (?)
|
||||
""", arguments: [context.witness])
|
||||
context.witness += 1
|
||||
""", arguments: [witness])
|
||||
witness += 1
|
||||
}
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -1146,16 +1146,13 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
|
||||
func testAsyncConcurrentReadOpensATransaction() throws {
|
||||
let dbPool = try makeDatabasePool()
|
||||
class Context {
|
||||
var isInsideTransaction: Bool? = nil
|
||||
}
|
||||
let context = Context()
|
||||
var isInsideTransaction: Bool? = nil
|
||||
let expectation = self.expectation(description: "read")
|
||||
dbPool.writeWithoutTransaction { db in
|
||||
dbPool.asyncConcurrentRead { dbResult in
|
||||
do {
|
||||
let db = try dbResult.get()
|
||||
context.isInsideTransaction = db.isInsideTransaction
|
||||
isInsideTransaction = db.isInsideTransaction
|
||||
do {
|
||||
try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
|
||||
XCTFail("Expected error")
|
||||
@@ -1168,7 +1165,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
XCTAssertEqual(context.isInsideTransaction, true)
|
||||
XCTAssertEqual(isInsideTransaction, true)
|
||||
}
|
||||
|
||||
func testAsyncConcurrentReadOutsideOfTransaction() throws {
|
||||
@@ -1191,17 +1188,14 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
// <
|
||||
// }
|
||||
|
||||
class Context {
|
||||
var count: Int?
|
||||
}
|
||||
let context = Context()
|
||||
var count: Int? = nil
|
||||
let expectation = self.expectation(description: "read")
|
||||
try dbPool.writeWithoutTransaction { db in
|
||||
dbPool.asyncConcurrentRead { dbResult in
|
||||
do {
|
||||
_ = s1.wait(timeout: .distantFuture)
|
||||
let db = try dbResult.get()
|
||||
context.count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")!
|
||||
count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")!
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -1211,17 +1205,14 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
s1.signal()
|
||||
}
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
XCTAssertEqual(context.count, 0)
|
||||
XCTAssertEqual(count, 0)
|
||||
}
|
||||
|
||||
func testAsyncConcurrentReadError() throws {
|
||||
// Necessary for this test to run as quickly as possible
|
||||
dbConfiguration.readonlyBusyMode = .immediateError
|
||||
let dbPool = try makeDatabasePool()
|
||||
class Context {
|
||||
var readError: DatabaseError? = nil
|
||||
}
|
||||
let context = Context()
|
||||
var readError: DatabaseError? = nil
|
||||
let expectation = self.expectation(description: "read")
|
||||
try dbPool.writeWithoutTransaction { db in
|
||||
try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE")
|
||||
@@ -1233,12 +1224,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase {
|
||||
XCTFail("Unexpected result: \(dbResult)")
|
||||
return
|
||||
}
|
||||
context.readError = dbError
|
||||
readError = dbError
|
||||
expectation.fulfill()
|
||||
}
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
XCTAssertEqual(context.readError!.resultCode, .SQLITE_BUSY)
|
||||
XCTAssertEqual(context.readError!.message!, "database is locked")
|
||||
XCTAssertEqual(readError!.resultCode, .SQLITE_BUSY)
|
||||
XCTAssertEqual(readError!.message!, "database is locked")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -228,10 +228,7 @@ class DatabasePoolTests: GRDBTestCase {
|
||||
let group = DispatchGroup()
|
||||
|
||||
// The maximum number of threads we could witness
|
||||
class Context {
|
||||
var maxThreadCount: CInt = 0
|
||||
}
|
||||
let context = Context()
|
||||
var maxThreadCount: CInt = 0
|
||||
let lock = NSLock()
|
||||
|
||||
for _ in (0..<numberOfConcurrentReads) {
|
||||
@@ -243,14 +240,14 @@ class DatabasePoolTests: GRDBTestCase {
|
||||
|
||||
let threadsCount = getThreadsCount()
|
||||
lock.lock()
|
||||
context.maxThreadCount = max(context.maxThreadCount, threadsCount)
|
||||
maxThreadCount = max(maxThreadCount, threadsCount)
|
||||
lock.unlock()
|
||||
|
||||
group.leave()
|
||||
}
|
||||
}
|
||||
group.wait()
|
||||
XCTAssert(context.maxThreadCount < 50)
|
||||
XCTAssert(maxThreadCount < 50)
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -273,10 +270,7 @@ class DatabasePoolTests: GRDBTestCase {
|
||||
let group = DispatchGroup()
|
||||
|
||||
// The maximum number of threads we could witness
|
||||
class Context {
|
||||
var maxThreadCount: CInt = 0
|
||||
}
|
||||
let context = Context()
|
||||
var maxThreadCount: CInt = 0
|
||||
let lock = NSLock()
|
||||
|
||||
for _ in (0..<numberOfConcurrentReads) {
|
||||
@@ -288,14 +282,14 @@ class DatabasePoolTests: GRDBTestCase {
|
||||
|
||||
let threadsCount = getThreadsCount()
|
||||
lock.lock()
|
||||
context.maxThreadCount = max(context.maxThreadCount, threadsCount)
|
||||
maxThreadCount = max(maxThreadCount, threadsCount)
|
||||
lock.unlock()
|
||||
|
||||
group.leave()
|
||||
}
|
||||
}
|
||||
group.wait()
|
||||
XCTAssert(context.maxThreadCount < 50)
|
||||
XCTAssert(maxThreadCount < 50)
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -244,13 +244,9 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
// BEGIN EXCLUSIVE TRANSACTION
|
||||
// COMMIT
|
||||
|
||||
class Context {
|
||||
var busyCallbackCalled = false
|
||||
}
|
||||
let context = Context()
|
||||
|
||||
var busyCallbackCalled = false
|
||||
self.busyCallback = { n in
|
||||
context.busyCallbackCalled = true
|
||||
busyCallbackCalled = true
|
||||
s2.signal()
|
||||
return true
|
||||
}
|
||||
@@ -287,7 +283,7 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
|
||||
_ = group.wait(timeout: .distantFuture)
|
||||
|
||||
XCTAssertTrue(context.busyCallbackCalled)
|
||||
XCTAssertTrue(busyCallbackCalled)
|
||||
}
|
||||
|
||||
func testReaderDuringDefaultTransaction() throws {
|
||||
@@ -388,13 +384,9 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
// COMMIT
|
||||
// COMMIT
|
||||
|
||||
class Context {
|
||||
var busyCallbackCalled = false
|
||||
}
|
||||
let context = Context()
|
||||
|
||||
var busyCallbackCalled = false
|
||||
self.busyCallback = { n in
|
||||
context.busyCallbackCalled = true
|
||||
busyCallbackCalled = true
|
||||
s3.signal()
|
||||
return true
|
||||
}
|
||||
@@ -439,6 +431,6 @@ class ConcurrencyTests: GRDBTestCase {
|
||||
|
||||
_ = group.wait(timeout: .distantFuture)
|
||||
|
||||
XCTAssertTrue(context.busyCallbackCalled)
|
||||
XCTAssertTrue(busyCallbackCalled)
|
||||
}
|
||||
}
|
||||
@@ -150,7 +150,7 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
|
||||
}
|
||||
|
||||
func testMainShadowedByAttachedDatabase() throws {
|
||||
#if SQLITE_HAS_CODEC
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Avoid error due to key not being provided:
|
||||
// file is not a database - while executing `ATTACH DATABASE...`
|
||||
throw XCTSkip("This test does not support encrypted databases")
|
||||
@@ -229,4 +229,171 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
|
||||
try XCTAssertFalse(db.tableExists("item"))
|
||||
}
|
||||
}
|
||||
|
||||
func testTableExistsThrowsWhenUnknownSchema() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t (id INTEGER);
|
||||
CREATE VIEW v AS SELECT * FROM t;
|
||||
CREATE TRIGGER tr AFTER INSERT ON t BEGIN SELECT 1; END;
|
||||
""")
|
||||
do {
|
||||
_ = try db.tableExists("t", in: "invalid")
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message, "no such schema: invalid")
|
||||
XCTAssertEqual(error.description, "SQLite error 1: no such schema: invalid")
|
||||
}
|
||||
do {
|
||||
_ = try db.viewExists("v", in: "invalid")
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message, "no such schema: invalid")
|
||||
XCTAssertEqual(error.description, "SQLite error 1: no such schema: invalid")
|
||||
}
|
||||
do {
|
||||
_ = try db.triggerExists("tr", in: "invalid")
|
||||
XCTFail("Expected Error")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message, "no such schema: invalid")
|
||||
XCTAssertEqual(error.description, "SQLite error 1: no such schema: invalid")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testExistsWithSpecifiedMainSchema() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t (id INTEGER);
|
||||
CREATE VIEW v AS SELECT * FROM t;
|
||||
CREATE TRIGGER tr AFTER INSERT ON t BEGIN SELECT 1; END;
|
||||
""")
|
||||
let tableExists = try db.tableExists("t", in: "main")
|
||||
let viewExists = try db.viewExists("v", in: "main")
|
||||
let triggerExists = try db.triggerExists("tr", in: "main")
|
||||
XCTAssertTrue(tableExists)
|
||||
XCTAssertTrue(viewExists)
|
||||
XCTAssertTrue(triggerExists)
|
||||
}
|
||||
}
|
||||
|
||||
func testNotExistsWithSpecifiedMainSchema() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let tableExists = try db.tableExists("t", in: "main")
|
||||
let viewExists = try db.viewExists("v", in: "main")
|
||||
let triggerExists = try db.triggerExists("tr", in: "main")
|
||||
XCTAssertFalse(tableExists)
|
||||
XCTAssertFalse(viewExists)
|
||||
XCTAssertFalse(triggerExists)
|
||||
}
|
||||
}
|
||||
|
||||
func testExistsWithSpecifiedSchemaWithEntityNameCollisions() throws {
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Avoid error due to key not being provided:
|
||||
// file is not a database - while executing `ATTACH DATABASE...`
|
||||
throw XCTSkip("This test does not support encrypted databases")
|
||||
#endif
|
||||
|
||||
let attached = try makeDatabaseQueue(filename: "attached")
|
||||
try attached.inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t (id INTEGER);
|
||||
CREATE VIEW v AS SELECT * FROM t;
|
||||
CREATE TRIGGER tr AFTER INSERT ON t BEGIN SELECT 1; END;
|
||||
""")
|
||||
}
|
||||
let main = try makeDatabaseQueue(filename: "main")
|
||||
try main.inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t (id INTEGER);
|
||||
CREATE VIEW v AS SELECT * FROM t;
|
||||
CREATE TRIGGER tr AFTER INSERT ON t BEGIN SELECT 1; END;
|
||||
""")
|
||||
try db.execute(literal: "ATTACH DATABASE \(attached.path) AS attached")
|
||||
|
||||
let tableExistsInMain = try db.tableExists("t", in: "main")
|
||||
let viewExistsInMain = try db.viewExists("v", in: "main")
|
||||
let triggerExistsInMain = try db.triggerExists("tr", in: "main")
|
||||
XCTAssertTrue(tableExistsInMain)
|
||||
XCTAssertTrue(viewExistsInMain)
|
||||
XCTAssertTrue(triggerExistsInMain)
|
||||
|
||||
let tableExistsInAttached = try db.tableExists("t", in: "attached")
|
||||
let viewExistsInAttached = try db.viewExists("v", in: "attached")
|
||||
let triggerExistsInAttached = try db.triggerExists("tr", in: "attached")
|
||||
XCTAssertTrue(tableExistsInAttached)
|
||||
XCTAssertTrue(viewExistsInAttached)
|
||||
XCTAssertTrue(triggerExistsInAttached)
|
||||
}
|
||||
}
|
||||
|
||||
func testExistsWithUnspecifiedSchemaWithEntityNameCollisions() throws {
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Avoid error due to key not being provided:
|
||||
// file is not a database - while executing `ATTACH DATABASE...`
|
||||
throw XCTSkip("This test does not support encrypted databases")
|
||||
#endif
|
||||
|
||||
let attached = try makeDatabaseQueue(filename: "attached")
|
||||
try attached.inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t (id INTEGER);
|
||||
CREATE VIEW v AS SELECT * FROM t;
|
||||
CREATE TRIGGER tr AFTER INSERT ON t BEGIN SELECT 1; END;
|
||||
""")
|
||||
}
|
||||
let main = try makeDatabaseQueue(filename: "main")
|
||||
try main.inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t (id INTEGER);
|
||||
CREATE VIEW v AS SELECT * FROM t;
|
||||
CREATE TRIGGER tr AFTER INSERT ON t BEGIN SELECT 1; END;
|
||||
""")
|
||||
try db.execute(literal: "ATTACH DATABASE \(attached.path) AS attached")
|
||||
|
||||
// Some entity with the name exists, but we can't prove from this information which one
|
||||
// it's getting. `true` is still the correct result.
|
||||
let tableExists = try db.tableExists("t")
|
||||
let viewExists = try db.viewExists("v")
|
||||
let triggerExists = try db.triggerExists("tr")
|
||||
XCTAssertTrue(tableExists)
|
||||
XCTAssertTrue(viewExists)
|
||||
XCTAssertTrue(triggerExists)
|
||||
}
|
||||
}
|
||||
|
||||
func testExistsWithUnspecifiedSchemaFindsAttachedDatabase() throws {
|
||||
#if GRDBCIPHER_USE_ENCRYPTION
|
||||
// Avoid error due to key not being provided:
|
||||
// file is not a database - while executing `ATTACH DATABASE...`
|
||||
throw XCTSkip("This test does not support encrypted databases")
|
||||
#endif
|
||||
|
||||
let attached = try makeDatabaseQueue(filename: "attached")
|
||||
try attached.inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE t (id INTEGER);
|
||||
CREATE VIEW v AS SELECT * FROM t;
|
||||
CREATE TRIGGER tr AFTER INSERT ON t BEGIN SELECT 1; END;
|
||||
""")
|
||||
}
|
||||
let main = try makeDatabaseQueue(filename: "main")
|
||||
try main.inDatabase { db in
|
||||
try db.execute(literal: "ATTACH DATABASE \(attached.path) AS attached")
|
||||
|
||||
let tableExists = try db.tableExists("t")
|
||||
let viewExists = try db.viewExists("v")
|
||||
let triggerExists = try db.triggerExists("tr")
|
||||
XCTAssertTrue(tableExists)
|
||||
XCTAssertTrue(viewExists)
|
||||
XCTAssertTrue(triggerExists)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -258,6 +258,140 @@ class DatabaseQueueTests: GRDBTestCase {
|
||||
try test(qos: .userInitiated)
|
||||
}
|
||||
|
||||
// MARK: - SQLITE_BUSY prevention
|
||||
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1483>
|
||||
func test_busy_timeout_does_not_prevent_SQLITE_BUSY_when_write_lock_is_acquired_by_other_connection() throws {
|
||||
var configuration = dbConfiguration!
|
||||
configuration.journalMode = .wal
|
||||
configuration.busyMode = .timeout(1) // Does not help in this case
|
||||
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test", configuration: configuration)
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test", configuration: configuration)
|
||||
|
||||
// DB1 DB2
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// READ
|
||||
let s1 = DispatchSemaphore(value: 0)
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// WRITE
|
||||
let s2 = DispatchSemaphore(value: 0)
|
||||
// WRITE -> SQLITE_BUSY because DB2 is already holding the write lock.
|
||||
let s3 = DispatchSemaphore(value: 0)
|
||||
// COMMIT
|
||||
|
||||
let block1 = {
|
||||
try! dbQueue1.inDatabase { db in
|
||||
try db.inTransaction(.deferred) {
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
s1.signal()
|
||||
s2.wait()
|
||||
do {
|
||||
try db.execute(sql: "CREATE TABLE test1(a)")
|
||||
XCTFail("Expected error")
|
||||
} catch DatabaseError.SQLITE_BUSY {
|
||||
// Test success
|
||||
}
|
||||
s3.signal()
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let block2 = {
|
||||
try! dbQueue2.inDatabase { db in
|
||||
s1.wait()
|
||||
try db.inTransaction(.deferred) {
|
||||
try db.execute(sql: "CREATE TABLE test2(a)")
|
||||
s2.signal()
|
||||
s3.wait()
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let blocks = [block1, block2]
|
||||
DispatchQueue.concurrentPerform(iterations: blocks.count) { index in
|
||||
blocks[index]()
|
||||
}
|
||||
}
|
||||
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1483>
|
||||
func test_busy_timeout_does_not_prevent_SQLITE_BUSY_when_write_lock_was_acquired_by_other_connection() throws {
|
||||
var configuration = dbConfiguration!
|
||||
configuration.journalMode = .wal
|
||||
configuration.busyMode = .timeout(1) // Does not help in this case
|
||||
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test", configuration: configuration)
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test", configuration: configuration)
|
||||
|
||||
// DB1 DB2
|
||||
// BEGIN DEFERRED TRANSACTION
|
||||
// READ
|
||||
let s1 = DispatchSemaphore(value: 0)
|
||||
// WRITE
|
||||
let s2 = DispatchSemaphore(value: 0)
|
||||
// WRITE -> SQLITE_BUSY because write lock can't be acquired,
|
||||
// even though DB2 does no longer hold any lock.
|
||||
|
||||
let block1 = {
|
||||
try! dbQueue1.inDatabase { db in
|
||||
try db.inTransaction(.deferred) {
|
||||
try db.execute(sql: "SELECT * FROM sqlite_master")
|
||||
s1.signal()
|
||||
s2.wait()
|
||||
do {
|
||||
try db.execute(sql: "CREATE TABLE test1(a)")
|
||||
XCTFail("Expected error")
|
||||
} catch DatabaseError.SQLITE_BUSY {
|
||||
// Test success
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let block2 = {
|
||||
try! dbQueue2.inDatabase { db in
|
||||
s1.wait()
|
||||
try db.execute(sql: "CREATE TABLE test2(a)")
|
||||
s2.signal()
|
||||
}
|
||||
}
|
||||
|
||||
let blocks = [block1, block2]
|
||||
DispatchQueue.concurrentPerform(iterations: blocks.count) { index in
|
||||
blocks[index]()
|
||||
}
|
||||
}
|
||||
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1483>
|
||||
func test_busy_timeout_and_IMMEDIATE_transactions_do_prevent_SQLITE_BUSY() throws {
|
||||
var configuration = dbConfiguration!
|
||||
// Test fails when this line is commented
|
||||
configuration.defaultTransactionKind = .immediate
|
||||
// Test fails when this line is commented
|
||||
configuration.busyMode = .timeout(10)
|
||||
|
||||
let dbQueue = try makeDatabaseQueue(filename: "test")
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "PRAGMA journal_mode = wal")
|
||||
try db.execute(sql: "CREATE TABLE test(a)")
|
||||
}
|
||||
|
||||
let parallelWritesCount = 50
|
||||
DispatchQueue.concurrentPerform(iterations: parallelWritesCount) { index in
|
||||
let dbQueue = try! makeDatabaseQueue(filename: "test", configuration: configuration)
|
||||
try! dbQueue.write { db in
|
||||
_ = try Table("test").fetchCount(db)
|
||||
try db.execute(sql: "INSERT INTO test VALUES (1)")
|
||||
}
|
||||
}
|
||||
|
||||
let count = try dbQueue.read(Table("test").fetchCount)
|
||||
XCTAssertEqual(count, parallelWritesCount)
|
||||
}
|
||||
|
||||
// MARK: - Closing
|
||||
|
||||
func testClose() throws {
|
||||
|
||||
@@ -205,19 +205,15 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
// MARK: - AsyncRead
|
||||
|
||||
func testAsyncRead() throws {
|
||||
class Context {
|
||||
var count: Int?
|
||||
}
|
||||
|
||||
func test(_ dbReader: some DatabaseReader) throws {
|
||||
let context = Context()
|
||||
let expectation = self.expectation(description: "updates")
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
var count: Int?
|
||||
dbReader.asyncRead { dbResult in
|
||||
// Make sure this block executes asynchronously
|
||||
semaphore.wait()
|
||||
do {
|
||||
context.count = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master")
|
||||
count = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master")
|
||||
} catch {
|
||||
XCTFail("Unexpected error: \(error)")
|
||||
}
|
||||
@@ -226,7 +222,7 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
semaphore.signal()
|
||||
|
||||
waitForExpectations(timeout: 1, handler: nil)
|
||||
XCTAssertNotNil(context.count)
|
||||
XCTAssertNotNil(count)
|
||||
}
|
||||
|
||||
try test(makeDatabaseQueue())
|
||||
|
||||
@@ -224,6 +224,42 @@ class DatabaseRegionObservationTests: GRDBTestCase {
|
||||
XCTAssertEqual(count, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func test_DatabaseRegionObservation_is_triggered_by_explicit_change_notification() throws {
|
||||
let dbQueue1 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
try dbQueue1.write { db in
|
||||
try db.execute(sql: "CREATE TABLE test(a)")
|
||||
}
|
||||
|
||||
let undetectedExpectation = expectation(description: "undetected")
|
||||
undetectedExpectation.isInverted = true
|
||||
|
||||
let detectedExpectation = expectation(description: "detected")
|
||||
|
||||
let observation = DatabaseRegionObservation(tracking: Table("test"))
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue1,
|
||||
onError: { error in XCTFail("Unexpected error: \(error)") },
|
||||
onChange: { _ in
|
||||
undetectedExpectation.fulfill()
|
||||
detectedExpectation.fulfill()
|
||||
})
|
||||
|
||||
try withExtendedLifetime(cancellable) {
|
||||
// Change performed from external connection is not detected...
|
||||
let dbQueue2 = try makeDatabaseQueue(filename: "test.sqlite")
|
||||
try dbQueue2.write { db in
|
||||
try db.execute(sql: "INSERT INTO test (a) VALUES (1)")
|
||||
}
|
||||
wait(for: [undetectedExpectation], timeout: 2)
|
||||
|
||||
// ... until we perform an explicit change notification
|
||||
try dbQueue1.write { db in
|
||||
try db.notifyChanges(in: Table("test"))
|
||||
}
|
||||
wait(for: [detectedExpectation], timeout: 2)
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for https://github.com/groue/GRDB.swift/issues/514
|
||||
// TODO: uncomment and make this test pass.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import XCTest
|
||||
@testable import GRDB
|
||||
import GRDB
|
||||
|
||||
class DatabaseTests : GRDBTestCase {
|
||||
|
||||
@@ -520,7 +520,6 @@ class DatabaseTests : GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// Test an internal API
|
||||
func testReadOnly() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
|
||||
@@ -114,14 +114,11 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
}
|
||||
|
||||
func testTraceFromConfigurationWithDefaultOptions() throws {
|
||||
class Context {
|
||||
var events: [String] = []
|
||||
}
|
||||
let context = Context()
|
||||
var events: [String] = []
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { event in
|
||||
context.events.append("SQL: \(event)")
|
||||
events.append("SQL: \(event)")
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue(configuration: configuration)
|
||||
@@ -130,23 +127,19 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
CREATE table t(a);
|
||||
INSERT INTO t (a) VALUES (?)
|
||||
""", arguments: [1])
|
||||
XCTAssertEqual(context.events.suffix(2), [
|
||||
XCTAssertEqual(events.suffix(2), [
|
||||
"SQL: CREATE table t(a)",
|
||||
"SQL: INSERT INTO t (a) VALUES (?)"])
|
||||
}
|
||||
}
|
||||
|
||||
func testTraceFromConfigurationWithPublicStatementArguments() throws {
|
||||
class Context {
|
||||
var events: [String] = []
|
||||
}
|
||||
let context = Context()
|
||||
|
||||
var events: [String] = []
|
||||
var configuration = Configuration()
|
||||
configuration.publicStatementArguments = true
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { event in
|
||||
context.events.append("SQL: \(event)")
|
||||
events.append("SQL: \(event)")
|
||||
}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue(configuration: configuration)
|
||||
@@ -155,7 +148,7 @@ class DatabaseTraceTests : GRDBTestCase {
|
||||
CREATE table t(a);
|
||||
INSERT INTO t (a) VALUES (?)
|
||||
""", arguments: [1])
|
||||
XCTAssertEqual(context.events.suffix(2), [
|
||||
XCTAssertEqual(events.suffix(2), [
|
||||
"SQL: CREATE table t(a)",
|
||||
"SQL: INSERT INTO t (a) VALUES (1)"])
|
||||
}
|
||||
|
||||
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user