mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-05 05:18:44 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d66e069822 | ||
|
|
e7eac0d500 | ||
|
|
61e0e97b39 | ||
|
|
fc10db84fe |
No files matched your search
@@ -28,6 +28,7 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
permissions:
|
||||
contents: read
|
||||
checks: write
|
||||
|
||||
jobs:
|
||||
Framework:
|
||||
@@ -79,7 +80,13 @@ 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 }}" 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
|
||||
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()
|
||||
SPM:
|
||||
name: SPM
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
@@ -126,6 +133,12 @@ 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 }}
|
||||
@@ -146,6 +159,12 @@ 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 }}
|
||||
@@ -166,6 +185,12 @@ 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,3 +115,6 @@ Tests/SPM/Packages
|
||||
|
||||
# Test products
|
||||
Tests/products
|
||||
|
||||
# CI
|
||||
*.xcresult
|
||||
@@ -7,10 +7,6 @@ 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)
|
||||
@@ -125,51 +121,7 @@ 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
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ struct PlayerRequest: Queryable {
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], any Error> {
|
||||
// Build the publisher from the general-purpose read-only access
|
||||
// granted by `appDatabase.reader`.
|
||||
// Some apps will prefer to call a dedicated method of `appDatabase`.
|
||||
|
||||
@@ -27,7 +27,7 @@ struct PlayerRequest: Queryable {
|
||||
|
||||
static var defaultValue: [Player] { [] }
|
||||
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> {
|
||||
func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], any Error> {
|
||||
// Build the publisher from the general-purpose read-only access
|
||||
// granted by `appDatabase.reader`.
|
||||
// Some apps will prefer to call a dedicated method of `appDatabase`.
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<key>NSExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>WKAppBundleIdentifier</key>
|
||||
<string>com.github.groue.GRDBDemoiOS2.watchkitapp</string>
|
||||
<string>com.github.groue.GRDBDemoiOS.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.GRDBDemoiOS2</string>
|
||||
<string>com.github.groue.GRDBDemoiOS</string>
|
||||
<key>WKWatchKitApp</key>
|
||||
<true/>
|
||||
</dict>
|
||||
|
||||
@@ -640,7 +640,7 @@
|
||||
"@executable_path/Frameworks",
|
||||
"@executable_path/../../Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.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.GRDBDemoiOS2.watchkitapp.watchkitextension;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.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.GRDBDemoiOS2.watchkitapp;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.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.GRDBDemoiOS2.watchkitapp;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = watchos;
|
||||
SKIP_INSTALL = YES;
|
||||
@@ -832,7 +832,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -849,7 +849,7 @@
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
};
|
||||
name = Release;
|
||||
|
||||
@@ -6,7 +6,7 @@ Release Process
|
||||
To release a new GRDB version:
|
||||
|
||||
- Tests
|
||||
- `make distclean test`
|
||||
- `make 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.25.0'
|
||||
s.version = '6.21.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -157,7 +157,6 @@
|
||||
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 */; };
|
||||
@@ -853,7 +852,6 @@
|
||||
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>"; };
|
||||
@@ -1739,7 +1737,6 @@
|
||||
children = (
|
||||
56A2FA3524424D2A00E97D23 /* Export.swift */,
|
||||
566DDE0C288D763C0000DCFB /* Fixits.swift */,
|
||||
648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */,
|
||||
56A2386F1B9C75030082EB20 /* Core */,
|
||||
567B5BDF2AD3284100629622 /* Dump */,
|
||||
5698AC291D9E5A480056AF8C /* FTS */,
|
||||
@@ -1876,7 +1873,6 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
565498612B8B815500585804 /* PrivacyInfo.xcprivacy in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
|
||||
@@ -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 (Database) throws -> Void) {
|
||||
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
|
||||
setups.append(setup)
|
||||
}
|
||||
|
||||
@@ -294,7 +294,7 @@ public struct Configuration {
|
||||
/// connection is opened.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_journal_mode>
|
||||
public enum JournalModeConfiguration: Sendable {
|
||||
public enum JournalModeConfiguration {
|
||||
/// The default setup has ``DatabaseQueue`` perform no specific
|
||||
/// configuration of the journal mode, and ``DatabasePool``
|
||||
/// configure the database for the WAL mode (just like the
|
||||
|
||||
@@ -733,11 +733,6 @@ 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> {
|
||||
@@ -752,11 +747,6 @@ 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 {
|
||||
@@ -783,11 +773,6 @@ 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 {
|
||||
@@ -833,11 +818,6 @@ 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 }
|
||||
@@ -895,11 +875,6 @@ 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 {
|
||||
@@ -926,11 +901,6 @@ 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 }
|
||||
@@ -957,11 +927,6 @@ 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 }
|
||||
@@ -989,11 +954,6 @@ 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() {
|
||||
|
||||
+44
-194
@@ -57,14 +57,6 @@ 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.
|
||||
@@ -154,19 +146,6 @@ 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? {
|
||||
@@ -223,19 +202,10 @@ extension Database {
|
||||
return tableInfo
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// 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 {
|
||||
try exists(type: .table, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
@@ -268,57 +238,20 @@ extension Database {
|
||||
|
||||
/// Returns whether a view exists, in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
///
|
||||
/// 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 {
|
||||
public func viewExists(_ name: String) throws -> Bool {
|
||||
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.
|
||||
///
|
||||
/// 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 {
|
||||
public func triggerExists(_ name: String) throws -> Bool {
|
||||
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
|
||||
@@ -331,17 +264,10 @@ extension Database {
|
||||
/// table has no explicit primary key, the result is the hidden
|
||||
/// "rowid" column.
|
||||
///
|
||||
/// 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(_:))
|
||||
}
|
||||
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
@@ -500,18 +426,10 @@ extension Database {
|
||||
/// the columns contain the primary key or a unique index, use
|
||||
/// ``table(_:hasUniqueKey:)``.
|
||||
///
|
||||
/// 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:))
|
||||
}
|
||||
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func indexes(on tableName: String) throws -> [IndexInfo] {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
@@ -600,18 +518,10 @@ extension Database {
|
||||
|
||||
/// Returns the foreign keys defined on table named `tableName`.
|
||||
///
|
||||
/// 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:))
|
||||
}
|
||||
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
@@ -692,27 +602,10 @@ extension Database {
|
||||
|
||||
/// Returns a cursor over foreign key violations in the table.
|
||||
///
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table exists in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func foreignKeyViolations(in tableName: String) throws -> RecordCursor<ForeignKeyViolation> {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if try exists(type: .table, name: tableName, in: schemaIdentifier) {
|
||||
return try foreignKeyViolations(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName))
|
||||
@@ -741,21 +634,14 @@ 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: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))
|
||||
/// ``foreignKeyViolations(in:)`` instead.
|
||||
public func checkForeignKeys(in tableName: String) throws {
|
||||
try checkForeignKeys(from: foreignKeyViolations(in: tableName))
|
||||
}
|
||||
|
||||
private func checkForeignKeys(from violations: RecordCursor<ForeignKeyViolation>) throws {
|
||||
@@ -772,17 +658,9 @@ 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
|
||||
}
|
||||
@@ -795,44 +673,16 @@ 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.
|
||||
///
|
||||
/// 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:))
|
||||
}
|
||||
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or if no
|
||||
/// such table or view with this name exists in the main or temp schema, or
|
||||
/// in an attached database.
|
||||
public func columns(in tableName: String) throws -> [ColumnInfo] {
|
||||
for schemaIdentifier in try schemaIdentifiers() {
|
||||
if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
|
||||
return result
|
||||
@@ -990,14 +840,14 @@ extension Database {
|
||||
|
||||
/// Information about a column of a database table.
|
||||
///
|
||||
/// You get `ColumnInfo` instances with the ``Database/columns(in:in:)``
|
||||
/// You get `ColumnInfo` instances with the ``Database/columns(in:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
/// - [pragma `table_info`](https://www.sqlite.org/pragma.html#pragma_table_info)
|
||||
/// - [pragma `table_xinfo`](https://www.sqlite.org/pragma.html#pragma_table_xinfo)
|
||||
public struct ColumnInfo: FetchableRecord, Sendable {
|
||||
public struct ColumnInfo: FetchableRecord {
|
||||
let cid: Int
|
||||
let hidden: Int?
|
||||
|
||||
@@ -1076,16 +926,16 @@ public struct ColumnInfo: FetchableRecord, Sendable {
|
||||
|
||||
/// Information about an index.
|
||||
///
|
||||
/// You get `IndexInfo` instances with the ``Database/indexes(on:in:)``
|
||||
/// You get `IndexInfo` instances with the ``Database/indexes(on:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
/// - [pragma `index_list`](https://www.sqlite.org/pragma.html#pragma_index_list)
|
||||
/// - [pragma `index_info`](https://www.sqlite.org/pragma.html#pragma_index_info)
|
||||
public struct IndexInfo: Sendable{
|
||||
public struct IndexInfo {
|
||||
/// The origin of an index.
|
||||
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible, Sendable {
|
||||
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible {
|
||||
public var rawValue: String
|
||||
|
||||
public init(rawValue: String) {
|
||||
@@ -1119,7 +969,7 @@ public struct IndexInfo: Sendable{
|
||||
///
|
||||
/// You get instances of `ForeignKeyViolation` from the `Database` methods
|
||||
/// ``Database/foreignKeyViolations()`` and
|
||||
/// ``Database/foreignKeyViolations(in:in:)`` methods.
|
||||
/// ``Database/foreignKeyViolations(in:)`` methods.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -1158,7 +1008,7 @@ public struct IndexInfo: Sendable{
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_foreign_key_check>
|
||||
public struct ForeignKeyViolation: Sendable {
|
||||
public struct ForeignKeyViolation {
|
||||
/// The name of the table that contains the foreign key.
|
||||
public var originTable: String
|
||||
|
||||
@@ -1173,7 +1023,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:in:)``.
|
||||
/// ``ForeignKeyInfo``. See ``Database/foreignKeys(on:)``.
|
||||
public var foreignKeyId: Int
|
||||
|
||||
/// A precise description of the foreign key violation.
|
||||
@@ -1263,7 +1113,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
|
||||
|
||||
/// Information about a primary key.
|
||||
///
|
||||
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:in:)``
|
||||
/// You get `PrimaryKeyInfo` instances with the ``Database/primaryKey(_:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// When the table's primary key is the rowid:
|
||||
@@ -1307,7 +1157,7 @@ extension ForeignKeyViolation: CustomStringConvertible {
|
||||
/// pk.rowIDColumn // nil
|
||||
/// pk.isRowID // false
|
||||
/// ```
|
||||
public struct PrimaryKeyInfo: Sendable {
|
||||
public struct PrimaryKeyInfo {
|
||||
private enum Impl {
|
||||
/// The hidden rowID.
|
||||
case hiddenRowID
|
||||
@@ -1429,11 +1279,11 @@ public struct PrimaryKeyInfo: Sendable {
|
||||
|
||||
/// Information about a foreign key.
|
||||
///
|
||||
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:in:)``
|
||||
/// You get `ForeignKeyInfo` instances with the ``Database/foreignKeys(on:)``
|
||||
/// `Database` method.
|
||||
///
|
||||
/// Related SQLite documentation: [pragma `foreign_key_list`](https://www.sqlite.org/pragma.html#pragma_foreign_key_list).
|
||||
public struct ForeignKeyInfo: Sendable {
|
||||
public struct ForeignKeyInfo {
|
||||
/// The first column in the output of the `foreign_key_list` pragma.
|
||||
public var id: Int
|
||||
|
||||
@@ -1517,7 +1367,7 @@ struct SchemaObject: Hashable, FetchableRecord {
|
||||
|
||||
/// All objects in a database schema (tables, views, indexes, triggers).
|
||||
struct SchemaInfo: Equatable {
|
||||
let objects: Set<SchemaObject>
|
||||
private var objects: Set<SchemaObject>
|
||||
|
||||
/// Returns whether there exists a object of given type with this name
|
||||
/// (case-insensitive).
|
||||
|
||||
@@ -361,11 +361,6 @@ 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 {
|
||||
|
||||
+32
-128
@@ -60,7 +60,6 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``inSavepoint(_:)``
|
||||
/// - ``inTransaction(_:_:)``
|
||||
/// - ``isInsideTransaction``
|
||||
/// - ``readOnly(_:)``
|
||||
/// - ``rollback()``
|
||||
/// - ``transactionDate``
|
||||
/// - ``TransactionCompletion``
|
||||
@@ -70,7 +69,6 @@ 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``
|
||||
@@ -81,7 +79,6 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``add(transactionObserver:extent:)``
|
||||
/// - ``remove(transactionObserver:)``
|
||||
/// - ``afterNextTransaction(onCommit:onRollback:)``
|
||||
/// - ``notifyChanges(in:)``
|
||||
/// - ``registerAccess(to:)``
|
||||
///
|
||||
/// ### Collations
|
||||
@@ -133,20 +130,28 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
@LockedBox private static var logErrorFunction: LogErrorFunction? = nil
|
||||
|
||||
/// The error logging function.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
|
||||
public static var logError: LogErrorFunction? = nil {
|
||||
didSet {
|
||||
if logError != nil {
|
||||
_registerErrorLogCallback { (_, code, message) in
|
||||
guard let logError = Database.logError else { return }
|
||||
guard let message = message.map(String.init) else { return }
|
||||
let resultCode = ResultCode(rawValue: code)
|
||||
logError(resultCode, message)
|
||||
public static var logError: LogErrorFunction? {
|
||||
get {
|
||||
logErrorFunction
|
||||
}
|
||||
set {
|
||||
$logErrorFunction.update {
|
||||
$0 = newValue
|
||||
if $0 != nil {
|
||||
_registerErrorLogCallback { (_, code, message) in
|
||||
guard let logError = Database.logError else { return }
|
||||
guard let message = message.map(String.init) else { return }
|
||||
let resultCode = ResultCode(rawValue: code)
|
||||
logError(resultCode, message)
|
||||
}
|
||||
} else {
|
||||
_registerErrorLogCallback(nil)
|
||||
}
|
||||
} else {
|
||||
_registerErrorLogCallback(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -311,7 +316,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
///
|
||||
/// Invariant: `transactionDateResult` is nil iff connection is not
|
||||
/// inside a transaction.
|
||||
var transactionDateResult: Result<Date, Error>?
|
||||
var transactionDateResult: Result<Date, any Error>?
|
||||
|
||||
/// The date of the current transaction.
|
||||
///
|
||||
@@ -774,38 +779,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// Grants read-only access in the wrapped closure.
|
||||
func readOnly<T>(_ block: () throws -> T) throws -> T {
|
||||
try beginReadOnly()
|
||||
return try throwingFirstError(
|
||||
execute: value,
|
||||
execute: block,
|
||||
finally: endReadOnly)
|
||||
}
|
||||
|
||||
@@ -850,65 +828,6 @@ 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.
|
||||
@@ -1254,7 +1173,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.writeWithoutTransaction do { db in
|
||||
/// try dbQueue.writeWithoutTransaction do {
|
||||
/// try db.inTransaction {
|
||||
/// try db.execute(sql: "INSERT ...")
|
||||
/// return .commit
|
||||
@@ -1298,7 +1217,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// Now that transaction has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
var firstError: Error? = nil
|
||||
var firstError: (any Error)? = nil
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -1442,7 +1361,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// Now that savepoint has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
var firstError: Error? = nil
|
||||
var firstError: (any Error)? = nil
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -1730,11 +1649,6 @@ 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 {
|
||||
|
||||
@@ -1860,7 +1774,7 @@ extension Database {
|
||||
/// The available checkpoint modes.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html>
|
||||
public enum CheckpointMode: CInt, Sendable {
|
||||
public enum CheckpointMode: CInt {
|
||||
/// The `SQLITE_CHECKPOINT_PASSIVE` mode.
|
||||
case passive = 0
|
||||
|
||||
@@ -1916,7 +1830,7 @@ extension Database {
|
||||
///
|
||||
/// For more information, see
|
||||
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
|
||||
public struct ColumnType: RawRepresentable, Hashable, Sendable {
|
||||
public struct ColumnType: RawRepresentable, Hashable {
|
||||
/// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.)
|
||||
public let rawValue: String
|
||||
|
||||
@@ -1968,7 +1882,7 @@ extension Database {
|
||||
/// An SQLite conflict resolution.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
|
||||
public enum ConflictResolution: String, Sendable {
|
||||
public enum ConflictResolution: String {
|
||||
/// The `ROLLBACK` conflict resolution.
|
||||
case rollback = "ROLLBACK"
|
||||
|
||||
@@ -1988,7 +1902,7 @@ extension Database {
|
||||
/// A foreign key action.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
|
||||
public enum ForeignKeyAction: String, Sendable {
|
||||
public enum ForeignKeyAction: String {
|
||||
/// The `CASCADE` foreign key action.
|
||||
case cascade = "CASCADE"
|
||||
|
||||
@@ -2011,7 +1925,7 @@ extension Database {
|
||||
/// ``Database/trace(options:_:)`` method.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/c_trace.html>
|
||||
public struct TracingOptions: OptionSet, Sendable {
|
||||
public struct TracingOptions: OptionSet {
|
||||
/// The raw trace event code.
|
||||
public let rawValue: CInt
|
||||
|
||||
@@ -2144,7 +2058,7 @@ extension Database {
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
|
||||
@frozen
|
||||
public enum TransactionCompletion: Sendable {
|
||||
public enum TransactionCompletion {
|
||||
case commit
|
||||
case rollback
|
||||
}
|
||||
@@ -2152,7 +2066,7 @@ extension Database {
|
||||
/// A transaction kind.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
|
||||
public enum TransactionKind: String, Sendable {
|
||||
public enum TransactionKind: String {
|
||||
/// The `DEFERRED` transaction kind.
|
||||
case deferred = "DEFERRED"
|
||||
|
||||
@@ -2185,13 +2099,3 @@ extension Database {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: a trace event contains transient
|
||||
// information.
|
||||
@available(*, unavailable)
|
||||
extension Database.TraceEvent: Sendable { }
|
||||
|
||||
// Explicit non-conformance to Sendable: a trace event contains transient
|
||||
// information.
|
||||
@available(*, unavailable)
|
||||
extension Database.TraceEvent.Statement: Sendable { }
|
||||
@@ -1,7 +1,7 @@
|
||||
/// Describe the progress of a database backup.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
public struct DatabaseBackupProgress: Sendable {
|
||||
public struct DatabaseBackupProgress {
|
||||
/// The number of pages still to be backed up.
|
||||
///
|
||||
/// It is the result of the `sqlite3_backup_remaining` function.
|
||||
|
||||
@@ -186,7 +186,7 @@ extension ResultCode {
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// ```
|
||||
public static func ~= (lhs: Self, rhs: Error) -> Bool {
|
||||
public static func ~= (lhs: Self, rhs: any Error) -> Bool {
|
||||
guard let error = rhs as? DatabaseError else { return false }
|
||||
return lhs ~= error.extendedResultCode
|
||||
}
|
||||
@@ -396,10 +396,6 @@ 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 {
|
||||
|
||||
@@ -403,7 +403,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
}
|
||||
|
||||
private static func report(error: Error, in sqliteContext: OpaquePointer?) {
|
||||
private static func report(error: some Error, in sqliteContext: OpaquePointer?) {
|
||||
if let error = error as? DatabaseError {
|
||||
if let message = error.message {
|
||||
sqlite3_result_error(sqliteContext, message, -1)
|
||||
|
||||
@@ -14,7 +14,7 @@ public final class DatabasePool {
|
||||
@LockedBox var databaseSnapshotCount = 0
|
||||
|
||||
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
|
||||
private var suspensionObservers: [NSObjectProtocol] = []
|
||||
private var suspensionObservers: [any NSObjectProtocol] = []
|
||||
|
||||
// MARK: - Database Information
|
||||
|
||||
@@ -91,7 +91,9 @@ public final class DatabasePool {
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
#if os(iOS)
|
||||
if configuration.automaticMemoryManagement {
|
||||
setupMemoryManagement()
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.setupMemoryManagement()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -221,6 +223,7 @@ extension DatabasePool {
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
/// as much memory as possible.
|
||||
@MainActor
|
||||
private func setupMemoryManagement() {
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(
|
||||
@@ -235,7 +238,7 @@ extension DatabasePool {
|
||||
object: nil)
|
||||
}
|
||||
|
||||
@objc
|
||||
@MainActor @objc
|
||||
private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = notification.object as? UIApplication else {
|
||||
return
|
||||
@@ -257,7 +260,9 @@ extension DatabasePool {
|
||||
// has freed its memory. That's better than nothing.
|
||||
releaseMemoryEventually()
|
||||
writer.async { _ in
|
||||
application.endBackgroundTask(task)
|
||||
DispatchQueue.main.async {
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -357,7 +362,7 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -401,7 +406,7 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -446,25 +451,18 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
public func concurrentRead<T: Sendable>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
let builder = DatabaseFutureBuilder<T>()
|
||||
|
||||
asyncConcurrentRead { dbResult in
|
||||
// Fetch and release the future
|
||||
futureResult = dbResult.flatMap { db in Result { try value(db) } }
|
||||
futureSemaphore.signal()
|
||||
builder.resolve(dbResult.flatMap { db in Result { try value(db) } })
|
||||
}
|
||||
|
||||
return DatabaseFuture {
|
||||
// Block the future until results are fetched
|
||||
_ = futureSemaphore.wait(timeout: .distantFuture)
|
||||
return try futureResult!.get()
|
||||
}
|
||||
return builder.future()
|
||||
}
|
||||
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
asyncConcurrentRead(value)
|
||||
}
|
||||
|
||||
@@ -505,7 +503,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// ```
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
public func asyncConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncConcurrentRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
@@ -665,7 +663,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 (Result<WALSnapshotTransaction, Error>) -> Void) {
|
||||
func asyncWALSnapshotTransaction(_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, any Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
completion(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -691,7 +689,7 @@ extension DatabasePool: DatabaseReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
@@ -722,7 +720,7 @@ extension DatabasePool: DatabaseReader {
|
||||
private func _addConcurrent<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
@@ -756,7 +754,7 @@ extension DatabasePool: DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
updates(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -809,7 +807,7 @@ extension DatabasePool: DatabaseWriter {
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ public final class DatabaseQueue {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
|
||||
private var suspensionObservers: [NSObjectProtocol] = []
|
||||
private var suspensionObservers: [any NSObjectProtocol] = []
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
@@ -65,7 +65,9 @@ public final class DatabaseQueue {
|
||||
// See https://github.com/groue/GRDB.swift/#memory-management
|
||||
#if os(iOS)
|
||||
if configuration.automaticMemoryManagement {
|
||||
setupMemoryManagement()
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.setupMemoryManagement()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -141,6 +143,7 @@ extension DatabaseQueue {
|
||||
/// Listens to UIApplicationDidEnterBackgroundNotification and
|
||||
/// UIApplicationDidReceiveMemoryWarningNotification in order to release
|
||||
/// as much memory as possible.
|
||||
@MainActor
|
||||
private func setupMemoryManagement() {
|
||||
let center = NotificationCenter.default
|
||||
center.addObserver(
|
||||
@@ -155,7 +158,7 @@ extension DatabaseQueue {
|
||||
object: nil)
|
||||
}
|
||||
|
||||
@objc
|
||||
@MainActor @objc
|
||||
private func applicationDidEnterBackground(_ notification: NSNotification) {
|
||||
guard let application = notification.object as? UIApplication else {
|
||||
return
|
||||
@@ -169,7 +172,9 @@ extension DatabaseQueue {
|
||||
// Release memory asynchronously
|
||||
writer.async { db in
|
||||
db.releaseMemory()
|
||||
application.endBackgroundTask(task)
|
||||
DispatchQueue.main.async {
|
||||
application.endBackgroundTask(task)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -233,7 +238,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
writer.async { db in
|
||||
defer {
|
||||
// Ignore error because we can not notify it.
|
||||
@@ -258,7 +263,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
try writer.sync(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
writer.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
@@ -266,7 +271,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
try writer.reentrantSync(value)
|
||||
}
|
||||
|
||||
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
// DatabaseQueue can't perform parallel reads.
|
||||
// Perform a blocking read instead.
|
||||
return DatabaseFuture(Result {
|
||||
@@ -279,7 +284,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
})
|
||||
}
|
||||
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
@@ -309,7 +314,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
@@ -379,7 +384,7 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
writer.async { updates(.success($0)) }
|
||||
}
|
||||
|
||||
@@ -425,7 +430,7 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,7 +37,6 @@ import Dispatch
|
||||
///
|
||||
/// - ``dumpContent(format:to:)``
|
||||
/// - ``dumpRequest(_:format:to:)``
|
||||
/// - ``dumpSchema(to:)``
|
||||
/// - ``dumpSQL(_:format:to:)``
|
||||
/// - ``dumpTables(_:format:tableHeader:stableOrder:to:)``
|
||||
/// - ``DumpFormat``
|
||||
@@ -214,7 +213,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 (Result<Database, Error>) -> Void)
|
||||
func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void)
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
@@ -285,7 +284,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 (Result<Database, Error>) -> Void)
|
||||
func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void)
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
@@ -343,7 +342,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
}
|
||||
|
||||
@@ -459,7 +458,7 @@ extension DatabaseReader {
|
||||
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func read<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
public func read<T>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncRead { result in
|
||||
do {
|
||||
@@ -505,7 +504,7 @@ extension DatabaseReader {
|
||||
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func unsafeRead<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
public func unsafeRead<T>(_ value: @escaping @Sendable (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncUnsafeRead { result in
|
||||
do {
|
||||
@@ -552,14 +551,12 @@ 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 (Database) throws -> Output)
|
||||
value: @escaping @Sendable (Database) throws -> Output)
|
||||
-> DatabasePublishers.Read<Output>
|
||||
{
|
||||
Deferred {
|
||||
Future { fulfill in
|
||||
self.asyncRead { dbResult in
|
||||
fulfill(dbResult.flatMap { db in Result { try value(db) } })
|
||||
}
|
||||
OnDemandFuture{ fulfill in
|
||||
self.asyncRead { dbResult in
|
||||
fulfill(dbResult.flatMap { db in Result { try value(db) } })
|
||||
}
|
||||
}
|
||||
.receiveValues(on: scheduler)
|
||||
@@ -576,9 +573,9 @@ extension DatabasePublishers {
|
||||
/// You build such a publisher from ``DatabaseReader``.
|
||||
public struct Read<Output>: Publisher {
|
||||
public typealias Output = Output
|
||||
public typealias Failure = Error
|
||||
public typealias Failure = any Error
|
||||
|
||||
fileprivate let upstream: AnyPublisher<Output, Error>
|
||||
fileprivate let upstream: AnyPublisher<Output, any Error>
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
|
||||
upstream.receive(subscriber: subscriber)
|
||||
@@ -587,7 +584,7 @@ extension DatabasePublishers {
|
||||
}
|
||||
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension Publisher where Failure == Error {
|
||||
extension Publisher where Failure == any Error {
|
||||
fileprivate func eraseToReadPublisher() -> DatabasePublishers.Read<Output> {
|
||||
.init(upstream: eraseToAnyPublisher())
|
||||
}
|
||||
@@ -602,7 +599,7 @@ extension DatabaseReader {
|
||||
func _addReadOnly<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if scheduler.immediateInitialValue() {
|
||||
@@ -620,16 +617,16 @@ extension DatabaseReader {
|
||||
}
|
||||
return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ })
|
||||
} else {
|
||||
var isCancelled = false
|
||||
let cancellable = AnyDatabaseCancellable { }
|
||||
asyncRead { dbResult in
|
||||
guard !isCancelled else { return }
|
||||
guard !cancellable.isCancelled else { return }
|
||||
|
||||
let result = dbResult.flatMap { db in
|
||||
Result { try observation.fetchInitialValue(db) }
|
||||
}
|
||||
|
||||
scheduler.schedule {
|
||||
guard !isCancelled else { return }
|
||||
guard !cancellable.isCancelled else { return }
|
||||
do {
|
||||
try onChange(result.get())
|
||||
} catch {
|
||||
@@ -637,7 +634,7 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
}
|
||||
return AnyDatabaseCancellable(cancel: { isCancelled = true })
|
||||
return cancellable
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -678,7 +675,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
try base.read(value)
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
base.asyncRead(value)
|
||||
}
|
||||
|
||||
@@ -687,7 +684,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
try base.unsafeRead(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
base.asyncUnsafeRead(value)
|
||||
}
|
||||
|
||||
@@ -698,7 +695,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
@@ -758,7 +755,7 @@ extension DatabaseSnapshotReader {
|
||||
}
|
||||
|
||||
// There is no such thing as an unsafe access to a snapshot.
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
asyncRead(value)
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,7 @@
|
||||
///
|
||||
/// - ``isModified(byEventsOfKind:)``
|
||||
/// - ``isModified(by:)``
|
||||
public struct DatabaseRegion: Sendable {
|
||||
public struct DatabaseRegion {
|
||||
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
|
||||
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
|
||||
@@ -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. (TODO: is this comment still accurate?
|
||||
// Isn't it about providing TransactionObserver.observes() with
|
||||
// real tables names, instead?)
|
||||
// `isModified` methods.
|
||||
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.
|
||||
func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
/// This method removes views (assuming no table exists with the same name
|
||||
/// as a view).
|
||||
private func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
guard let tableRegions else { return .fullDatabase }
|
||||
var region = DatabaseRegion()
|
||||
for (table, tableRegion) in tableRegions {
|
||||
@@ -233,44 +233,6 @@ 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 {
|
||||
@@ -416,11 +378,11 @@ private struct TableRegion: Equatable {
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyDatabaseRegionConvertible``
|
||||
public protocol DatabaseRegionConvertible {
|
||||
public protocol DatabaseRegionConvertible: Sendable {
|
||||
/// Returns a database region.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func databaseRegion(_ db: Database) throws -> DatabaseRegion
|
||||
@Sendable func databaseRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
extension DatabaseRegionConvertible where Self == DatabaseRegion {
|
||||
@@ -437,9 +399,9 @@ extension DatabaseRegion: DatabaseRegionConvertible {
|
||||
|
||||
/// A type-erased DatabaseRegionConvertible
|
||||
public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
|
||||
let _region: (Database) throws -> DatabaseRegion
|
||||
let _region: @Sendable (Database) throws -> DatabaseRegion
|
||||
|
||||
public init(_ region: @escaping (Database) throws -> DatabaseRegion) {
|
||||
public init(_ region: @escaping @Sendable (Database) throws -> DatabaseRegion) {
|
||||
_region = region
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ extension DatabaseRegionObservation {
|
||||
|
||||
extension DatabaseRegionObservation {
|
||||
/// The state of a started DatabaseRegionObservation
|
||||
private enum ObservationState {
|
||||
private enum ObservationState: Sendable {
|
||||
case cancelled
|
||||
case pending
|
||||
case started(DatabaseRegionObserver)
|
||||
@@ -85,23 +85,23 @@ extension DatabaseRegionObservation {
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
public func start(
|
||||
in writer: some DatabaseWriter,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Database) -> Void)
|
||||
onError: @escaping @Sendable (any Error) -> Void,
|
||||
onChange: @escaping @Sendable (Database) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@LockedBox var state = ObservationState.pending
|
||||
let state = LockedBox(wrappedValue: ObservationState.pending)
|
||||
|
||||
// Use unsafeReentrantWrite so that observation can start from any
|
||||
// dispatch queue.
|
||||
writer.unsafeReentrantWrite { db in
|
||||
do {
|
||||
let region = try observedRegion(db).observableRegion(db)
|
||||
$state.update {
|
||||
let observer = DatabaseRegionObserver(region: region, onChange: {
|
||||
if case .cancelled = state {
|
||||
state.update {
|
||||
let observer = DatabaseRegionObserver(region: region, onChange: { db in
|
||||
if case .cancelled = state.wrappedValue {
|
||||
return
|
||||
}
|
||||
onChange($0)
|
||||
onChange(db)
|
||||
})
|
||||
|
||||
// Use the `.observerLifetime` extent so that we can cancel
|
||||
@@ -122,7 +122,7 @@ extension DatabaseRegionObservation {
|
||||
// Deallocates the transaction observer. This makes sure that the
|
||||
// `onChange` callback will never be called again, because the
|
||||
// observation was started with the `.observerLifetime` extent.
|
||||
state = .cancelled
|
||||
state.wrappedValue = .cancelled
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,12 +147,12 @@ extension DatabaseRegionObservation {
|
||||
}
|
||||
#endif
|
||||
|
||||
private class DatabaseRegionObserver: TransactionObserver {
|
||||
private class DatabaseRegionObserver: TransactionObserver, @unchecked Sendable {
|
||||
let region: DatabaseRegion
|
||||
let onChange: (Database) -> Void
|
||||
let onChange: @Sendable (Database) -> Void
|
||||
var isChanged = false
|
||||
|
||||
init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) {
|
||||
init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) {
|
||||
self.region = region
|
||||
self.onChange = onChange
|
||||
}
|
||||
@@ -161,11 +161,6 @@ 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
|
||||
@@ -193,7 +188,7 @@ extension DatabasePublishers {
|
||||
/// You build such a publisher from ``DatabaseRegionObservation``.
|
||||
public struct DatabaseRegion: Publisher {
|
||||
public typealias Output = Database
|
||||
public typealias Failure = Error
|
||||
public typealias Failure = any Error
|
||||
|
||||
let writer: any DatabaseWriter
|
||||
let observation: DatabaseRegionObservation
|
||||
@@ -212,8 +207,8 @@ extension DatabasePublishers {
|
||||
}
|
||||
}
|
||||
|
||||
private class DatabaseRegionSubscription<Downstream: Subscriber>: Subscription
|
||||
where Downstream.Failure == Error, Downstream.Input == Database
|
||||
private class DatabaseRegionSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable
|
||||
where Downstream.Failure == any Error, Downstream.Input == Database
|
||||
{
|
||||
private struct WaitingForDemand {
|
||||
let downstream: Downstream
|
||||
@@ -303,7 +298,7 @@ extension DatabasePublishers {
|
||||
}
|
||||
}
|
||||
|
||||
private func receive(failure error: Error) {
|
||||
private func receive(failure error: any Error) {
|
||||
lock.synchronized {
|
||||
if case let .observing(info) = state {
|
||||
state = .finished
|
||||
|
||||
@@ -154,7 +154,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
try reader.sync(block)
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
reader.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
@@ -162,7 +162,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
try reader.sync(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any 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 (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
_addReadOnly(
|
||||
|
||||
@@ -292,7 +292,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
@@ -330,7 +330,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
public func _add<Reducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable where Reducer: ValueReducer
|
||||
{
|
||||
_addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange)
|
||||
|
||||
@@ -222,11 +222,6 @@ 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:
|
||||
///
|
||||
@@ -306,7 +301,7 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
@Sendable public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -340,7 +335,7 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
@Sendable public static func fetchOne(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -375,7 +370,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
@Sendable public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -452,7 +447,7 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
@Sendable public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -487,7 +482,7 @@ extension DatabaseValueConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
@Sendable public static func fetchOne(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -521,7 +516,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
@Sendable public static func fetchSet(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -608,7 +603,7 @@ extension DatabaseValueConvertible {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
@Sendable 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)
|
||||
}
|
||||
@@ -645,7 +640,7 @@ extension DatabaseValueConvertible {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
@Sendable 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)
|
||||
}
|
||||
@@ -681,7 +676,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A set.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
@Sendable 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)
|
||||
}
|
||||
@@ -758,7 +753,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
@@ -792,7 +787,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
@@ -825,7 +820,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.
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
@Sendable 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 (Result<Database, Error>) -> Void)
|
||||
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, any 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 (Database) -> Void)
|
||||
func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (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 (Database) throws -> T) -> DatabaseFuture<T>
|
||||
func concurrentRead<T>(_ value: @escaping @Sendable (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 (Result<Database, Error>) -> Void)
|
||||
func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, any 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 (Database) throws -> T,
|
||||
completion: @escaping (Database, Result<T, Error>) -> Void)
|
||||
_ updates: @escaping @Sendable (Database) throws -> T,
|
||||
completion: @escaping @Sendable (Database, Result<T, any 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 (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
@@ -608,7 +608,7 @@ extension DatabaseWriter {
|
||||
/// would happen while establishing the database access or committing
|
||||
/// the transaction.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func write<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
public func write<T>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncWrite(updates, completion: { _, result in
|
||||
continuation.resume(with: result)
|
||||
@@ -646,7 +646,7 @@ extension DatabaseWriter {
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func writeWithoutTransaction<T>(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
public func writeWithoutTransaction<T>(_ updates: @escaping @Sendable (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncWriteWithoutTransaction { db in
|
||||
do {
|
||||
@@ -699,7 +699,7 @@ extension DatabaseWriter {
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func barrierWriteWithoutTransaction<T>(
|
||||
_ updates: @Sendable @escaping (Database) throws -> T)
|
||||
_ updates: @escaping @Sendable (Database) throws -> T)
|
||||
async throws -> T
|
||||
{
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
@@ -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 (Database) throws -> Output)
|
||||
updates: @escaping @Sendable (Database) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
{
|
||||
OnDemandFuture { fulfill in
|
||||
@@ -866,10 +866,10 @@ extension DatabaseWriter {
|
||||
/// - parameter updates: A closure which writes in the database.
|
||||
/// - parameter value: A closure which reads from the database.
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
public func writePublisher<S, T, Output>(
|
||||
public func writePublisher<S, T: Sendable, Output: Sendable>(
|
||||
receiveOn scheduler: S = DispatchQueue.main,
|
||||
updates: @escaping (Database) throws -> T,
|
||||
thenRead value: @escaping (Database, T) throws -> Output)
|
||||
updates: @escaping @Sendable (Database) throws -> T,
|
||||
thenRead value: @escaping @Sendable (Database, T) throws -> Output)
|
||||
-> DatabasePublishers.Write<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
@@ -885,7 +885,7 @@ extension DatabaseWriter {
|
||||
fulfill(.failure(error))
|
||||
return
|
||||
}
|
||||
self.spawnConcurrentRead { dbResult in
|
||||
self.spawnConcurrentRead { [updatesValue] dbResult in
|
||||
fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } })
|
||||
}
|
||||
}
|
||||
@@ -906,9 +906,9 @@ extension DatabasePublishers {
|
||||
/// You build such a publisher from ``DatabaseWriter``.
|
||||
public struct Write<Output>: Publisher {
|
||||
public typealias Output = Output
|
||||
public typealias Failure = Error
|
||||
public typealias Failure = any Error
|
||||
|
||||
fileprivate let upstream: AnyPublisher<Output, Error>
|
||||
fileprivate let upstream: AnyPublisher<Output, any Error>
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
|
||||
upstream.receive(subscriber: subscriber)
|
||||
@@ -917,7 +917,7 @@ extension DatabasePublishers {
|
||||
}
|
||||
|
||||
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
|
||||
extension Publisher where Failure == Error {
|
||||
extension Publisher where Failure == any Error {
|
||||
fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write<Output> {
|
||||
.init(upstream: self.eraseToAnyPublisher())
|
||||
}
|
||||
@@ -941,7 +941,7 @@ extension Publisher where Failure == Error {
|
||||
///
|
||||
/// let count: Int = try futureCount.wait()
|
||||
/// ```
|
||||
public class DatabaseFuture<Value> {
|
||||
public class DatabaseFuture<Value: Sendable> {
|
||||
private var consumed = false
|
||||
private let _wait: () throws -> Value
|
||||
|
||||
@@ -949,7 +949,7 @@ public class DatabaseFuture<Value> {
|
||||
_wait = wait
|
||||
}
|
||||
|
||||
init(_ result: Result<Value, Error>) {
|
||||
init(_ result: Result<Value, any Error>) {
|
||||
_wait = result.get
|
||||
}
|
||||
|
||||
@@ -967,6 +967,31 @@ public class DatabaseFuture<Value> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Helps building DatabaseFuture with strict concurrency checkings
|
||||
final class DatabaseFutureBuilder<Value: Sendable>: @unchecked Sendable {
|
||||
/// The semaphore that blocks until result is set.
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
var result: Result<Value, any Error>? = nil
|
||||
|
||||
init() { }
|
||||
|
||||
/// - precondition: MUST be called once.
|
||||
func resolve(_ result: Result<Value, any Error>) {
|
||||
self.result = result
|
||||
semaphore.signal()
|
||||
}
|
||||
|
||||
/// - precondition: MUST be called once.
|
||||
func future() -> DatabaseFuture<Value> {
|
||||
DatabaseFuture { [self] in
|
||||
// Block the future until results are fetched
|
||||
_ = semaphore.wait(timeout: .distantFuture)
|
||||
return try result!.get()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased database writer.
|
||||
///
|
||||
/// An instance of `AnyDatabaseWriter` forwards its operations to an underlying
|
||||
@@ -1003,7 +1028,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
try base.read(value)
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
base.asyncRead(value)
|
||||
}
|
||||
|
||||
@@ -1012,7 +1037,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
try base.unsafeRead(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncUnsafeRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
base.asyncUnsafeRead(value)
|
||||
}
|
||||
|
||||
@@ -1023,7 +1048,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: some ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
onChange: @escaping @Sendable (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
@@ -1044,11 +1069,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
|
||||
try base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
base.asyncBarrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping @Sendable (Database) -> Void) {
|
||||
base.asyncWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
@@ -1056,11 +1081,11 @@ extension AnyDatabaseWriter: DatabaseWriter {
|
||||
try base.unsafeReentrantWrite(updates)
|
||||
}
|
||||
|
||||
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
public func concurrentRead<T>(_ value: @escaping @Sendable (Database) throws -> T) -> DatabaseFuture<T> {
|
||||
base.concurrentRead(value)
|
||||
}
|
||||
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
public func spawnConcurrentRead(_ value: @escaping @Sendable (Result<Database, any Error>) -> Void) {
|
||||
base.spawnConcurrentRead(value)
|
||||
}
|
||||
}
|
||||
@@ -152,11 +152,6 @@ public struct PreparedRequest {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `PreparedRequest` contains
|
||||
// a statement.
|
||||
@available(*, unavailable)
|
||||
extension PreparedRequest: Sendable { }
|
||||
|
||||
extension PreparedRequest: Refinable { }
|
||||
|
||||
// MARK: - AdaptedFetchRequest
|
||||
@@ -171,7 +166,7 @@ extension FetchRequest {
|
||||
///
|
||||
/// - parameter adapter: A closure that accepts a database connection and
|
||||
/// returns a row adapter.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
public func adapted(_ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
AdaptedFetchRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
@@ -181,11 +176,11 @@ extension FetchRequest {
|
||||
/// See ``FetchRequest/adapted(_:)``.
|
||||
public struct AdaptedFetchRequest<Base: FetchRequest> {
|
||||
let base: Base
|
||||
let adapter: (Database) throws -> any RowAdapter
|
||||
let adapter: @Sendable (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 (Database) throws -> any RowAdapter) {
|
||||
init(_ base: Base, _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
}
|
||||
@@ -200,7 +195,7 @@ extension AdaptedFetchRequest: SQLSubqueryable {
|
||||
extension AdaptedFetchRequest: FetchRequest {
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
@Sendable public func fetchCount(_ db: Database) throws -> Int {
|
||||
try base.fetchCount(db)
|
||||
}
|
||||
|
||||
@@ -260,7 +255,7 @@ extension AnyFetchRequest: SQLSubqueryable {
|
||||
}
|
||||
|
||||
extension AnyFetchRequest: FetchRequest {
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
@Sendable public func fetchCount(_ db: Database) throws -> Int {
|
||||
try request.fetchCount(db)
|
||||
}
|
||||
|
||||
@@ -274,7 +269,7 @@ extension AnyFetchRequest: FetchRequest {
|
||||
}
|
||||
|
||||
// Class-based type erasure, so that we preserve full type information.
|
||||
private class FetchRequestEraser: FetchRequest {
|
||||
private class FetchRequestEraser: FetchRequest, @unchecked Sendable {
|
||||
typealias RowDecoder = Void
|
||||
|
||||
var sqlSubquery: SQLSubquery {
|
||||
|
||||
+13
-24
@@ -245,12 +245,6 @@ 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
|
||||
@@ -1383,11 +1377,6 @@ 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
|
||||
@@ -1458,7 +1447,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
@Sendable public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -1487,7 +1476,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
@Sendable public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -1516,7 +1505,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
@Sendable public static func fetchOne(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -1600,7 +1589,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
@Sendable public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -1629,7 +1618,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
@Sendable public static func fetchSet(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -1658,7 +1647,7 @@ extension Row {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
@Sendable public static func fetchOne(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -1747,7 +1736,7 @@ extension Row {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
|
||||
@Sendable 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)
|
||||
@@ -1779,7 +1768,7 @@ extension Row {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A set of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Row> {
|
||||
@Sendable 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)
|
||||
@@ -1815,7 +1804,7 @@ extension Row {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? {
|
||||
@Sendable 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
|
||||
@@ -1885,7 +1874,7 @@ extension FetchRequest<Row> {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of fetched rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
@Sendable public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
try Row.fetchAll(db, self)
|
||||
}
|
||||
|
||||
@@ -1906,7 +1895,7 @@ extension FetchRequest<Row> {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of fetched rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchSet(_ db: Database) throws -> Set<Row> {
|
||||
@Sendable public func fetchSet(_ db: Database) throws -> Set<Row> {
|
||||
try Row.fetchSet(db, self)
|
||||
}
|
||||
|
||||
@@ -1927,7 +1916,7 @@ extension FetchRequest<Row> {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> Row? {
|
||||
@Sendable public func fetchOne(_ db: Database) throws -> Row? {
|
||||
try Row.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
@@ -2070,7 +2059,7 @@ typealias RowIndex = Row.Index
|
||||
|
||||
extension Row {
|
||||
/// An index to a (column, value) pair in a ``Row``.
|
||||
public struct Index: Sendable {
|
||||
public struct Index {
|
||||
let index: Int
|
||||
init(_ index: Int) { self.index = index }
|
||||
}
|
||||
|
||||
@@ -318,7 +318,7 @@ extension Statement: _RowLayout {
|
||||
/// - ``RenameColumnAdapter``
|
||||
/// - ``ScopeAdapter``
|
||||
/// - ``SuffixRowAdapter``
|
||||
public protocol RowAdapter {
|
||||
public protocol RowAdapter: Sendable {
|
||||
/// You never call this method directly. It is called for you whenever an
|
||||
/// adapter has to be applied.
|
||||
///
|
||||
@@ -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, Sendable {
|
||||
public struct EmptyRowAdapter: RowAdapter {
|
||||
/// Creates an `EmptyRowAdapter`.
|
||||
public init() { }
|
||||
|
||||
@@ -403,7 +403,7 @@ public struct EmptyRowAdapter: RowAdapter, Sendable {
|
||||
///
|
||||
/// Note that columns that are not present in the dictionary are not present
|
||||
/// in the resulting adapted row.
|
||||
public struct ColumnMapping: RowAdapter, Sendable {
|
||||
public struct ColumnMapping: RowAdapter {
|
||||
/// 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, Sendable {
|
||||
/// // [c:2, d: 3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)!
|
||||
/// ```
|
||||
public struct SuffixRowAdapter: RowAdapter, Sendable {
|
||||
public struct SuffixRowAdapter: RowAdapter {
|
||||
/// The suffix index
|
||||
let index: Int
|
||||
|
||||
@@ -473,7 +473,7 @@ public struct SuffixRowAdapter: RowAdapter, Sendable {
|
||||
/// // [b:1 c:2]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// ```
|
||||
public struct RangeRowAdapter: RowAdapter, Sendable {
|
||||
public struct RangeRowAdapter: RowAdapter {
|
||||
/// The range
|
||||
let range: CountableRange<Int>
|
||||
|
||||
@@ -656,11 +656,11 @@ struct ChainedAdapter: RowAdapter {
|
||||
/// print(Array(adaptedRow.columnNames))
|
||||
/// ```
|
||||
public struct RenameColumnAdapter: RowAdapter {
|
||||
let transform: (String) -> String
|
||||
let transform: @Sendable (String) -> String
|
||||
|
||||
/// Creates a `RenameColumnAdapter` adapter that renames columns according to the
|
||||
/// provided transform function.
|
||||
public init(_ transform: @escaping (String) -> String) {
|
||||
public init(_ transform: @escaping @Sendable (String) -> String) {
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
|
||||
@@ -191,7 +191,7 @@ extension SQLRequest: FetchRequest {
|
||||
.literal(sqlLiteral)
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
@Sendable public func fetchCount(_ db: Database) throws -> Int {
|
||||
try SQLRequest<Int>("SELECT COUNT(*) FROM (\(self))").fetchOne(db)!
|
||||
}
|
||||
|
||||
|
||||
@@ -223,7 +223,7 @@ final class SerializedDatabase {
|
||||
}
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
func async(_ block: @escaping (Database) -> Void) {
|
||||
func async(_ block: @escaping @Sendable (Database) -> Void) {
|
||||
queue.async {
|
||||
block(self.db)
|
||||
self.preconditionNoUnsafeTransactionLeft(self.db)
|
||||
|
||||
@@ -623,11 +623,6 @@ 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,11 +241,6 @@ 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.
|
||||
@@ -317,7 +312,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
@Sendable public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -351,7 +346,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
@Sendable public static func fetchOne(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -389,7 +384,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
@Sendable public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -466,7 +461,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
@Sendable public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -501,7 +496,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
@Sendable public static func fetchOne(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -535,7 +530,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
@Sendable public static func fetchSet(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
@@ -624,7 +619,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
@Sendable 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)
|
||||
}
|
||||
@@ -661,7 +656,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
@Sendable 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)
|
||||
}
|
||||
@@ -697,7 +692,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
@Sendable 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)
|
||||
}
|
||||
@@ -774,7 +769,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
@Sendable public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
@@ -808,7 +803,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
@Sendable public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
@@ -841,7 +836,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
try RowDecoder.fetchSet(db, self)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
/// A database value that holds date components.
|
||||
public struct DatabaseDateComponents: Sendable {
|
||||
public struct DatabaseDateComponents {
|
||||
|
||||
/// The SQLite formats for date components.
|
||||
public enum Format: String, Sendable {
|
||||
@@ -152,7 +152,7 @@ extension DatabaseDateComponents: DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
extension DatabaseDateComponents: Decodable {
|
||||
public init(from decoder: Decoder) throws {
|
||||
public init(from decoder: any Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
let stringValue = try container.decode(String.self)
|
||||
guard let decodedValue = DatabaseDateComponents.fromDatabaseValue(stringValue.databaseValue) else {
|
||||
@@ -164,7 +164,7 @@ extension DatabaseDateComponents: Decodable {
|
||||
}
|
||||
|
||||
extension DatabaseDateComponents: Encodable {
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
public func encode(to encoder: any Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(String.fromDatabaseValue(databaseValue)!)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
// GRDB7: remove conformance because NSData is not Sendable.
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
extension NSData: DatabaseValueConvertible {
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
// GRDB7: remove conformance because NSString is not Sendable.
|
||||
/// NSString adopts DatabaseValueConvertible
|
||||
extension NSString: DatabaseValueConvertible {
|
||||
|
||||
|
||||
@@ -161,12 +161,12 @@ private struct DatabaseValueDecoder: Decoder {
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
func unkeyedContainer() throws -> any UnkeyedDecodingContainer {
|
||||
// We need to switch to JSON decoding
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
func singleValueContainer() throws -> any SingleValueDecodingContainer {
|
||||
DatabaseValueDecodingContainer(dbValue: dbValue, codingPath: codingPath)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ private class DatabaseValueEncoder: Encoder {
|
||||
/// - precondition: May not be called after a prior `self.container(keyedBy:)` call.
|
||||
/// - precondition: May not be called after a value has been encoded through
|
||||
/// a previous `self.singleValueContainer()` call.
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
func unkeyedContainer() -> any UnkeyedEncodingContainer {
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
@@ -109,7 +109,7 @@ private class DatabaseValueEncoder: Encoder {
|
||||
/// - precondition: May not be called after a prior `self.unkeyedContainer()` call.
|
||||
/// - precondition: May not be called after a value has been encoded through
|
||||
/// a previous `self.singleValueContainer()` call.
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
func singleValueContainer() -> any SingleValueEncodingContainer {
|
||||
DatabaseValueEncodingContainer(encode: encode, jsonEncoder: jsonEncoder)
|
||||
}
|
||||
|
||||
|
||||
@@ -10,9 +10,9 @@ struct JSONRequiredEncoder: Encoder {
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
func unkeyedContainer() -> any UnkeyedEncodingContainer { self }
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer { self }
|
||||
func singleValueContainer() -> any SingleValueEncodingContainer { self }
|
||||
|
||||
struct KeyedContainer<KeyType: CodingKey>: KeyedEncodingContainerProtocol {
|
||||
var codingPath: [any CodingKey]
|
||||
@@ -47,15 +47,15 @@ struct JSONRequiredEncoder: Encoder {
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer {
|
||||
func nestedUnkeyedContainer(forKey key: KeyType) -> any UnkeyedEncodingContainer {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder() -> Encoder {
|
||||
func superEncoder() -> any Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder(forKey key: KeyType) -> Encoder {
|
||||
func superEncoder(forKey key: KeyType) -> any Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
}
|
||||
@@ -91,7 +91,7 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer {
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
mutating func nestedUnkeyedContainer() -> any UnkeyedEncodingContainer { self }
|
||||
|
||||
mutating func superEncoder() -> Encoder { self }
|
||||
mutating func superEncoder() -> any Encoder { self }
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import Foundation
|
||||
///
|
||||
/// - ``DefaultTransactionClock``
|
||||
/// - ``CustomTransactionClock``
|
||||
public protocol TransactionClock {
|
||||
public protocol TransactionClock: Sendable {
|
||||
/// 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 (Database) throws -> Date) -> Self {
|
||||
public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
|
||||
CustomTransactionClock(now)
|
||||
}
|
||||
}
|
||||
@@ -53,9 +53,9 @@ public struct DefaultTransactionClock: TransactionClock {
|
||||
|
||||
/// A custom transaction clock.
|
||||
public struct CustomTransactionClock: TransactionClock {
|
||||
let _now: (Database) throws -> Date
|
||||
let _now: @Sendable (Database) throws -> Date
|
||||
|
||||
public init(_ now: @escaping (Database) throws -> Date) {
|
||||
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
|
||||
self._now = now
|
||||
}
|
||||
|
||||
|
||||
@@ -101,14 +101,17 @@ extension Database {
|
||||
/// - parameter onCommit: A closure executed on transaction commit.
|
||||
/// - parameter onRollback: A closure executed on transaction rollback.
|
||||
public func afterNextTransaction(
|
||||
onCommit: @escaping (Database) -> Void,
|
||||
onRollback: @escaping (Database) -> Void = { _ in })
|
||||
onCommit: @escaping @Sendable (Database) -> Void,
|
||||
onRollback: @escaping @Sendable (Database) -> Void = { _ in })
|
||||
{
|
||||
class TransactionHandler: TransactionObserver {
|
||||
let onCommit: (Database) -> Void
|
||||
let onRollback: (Database) -> Void
|
||||
let onCommit: @Sendable (Database) -> Void
|
||||
let onRollback: @Sendable (Database) -> Void
|
||||
|
||||
init(onCommit: @escaping (Database) -> Void, onRollback: @escaping (Database) -> Void) {
|
||||
init(
|
||||
onCommit: @escaping @Sendable (Database) -> Void,
|
||||
onRollback: @escaping @Sendable (Database) -> Void)
|
||||
{
|
||||
self.onCommit = onCommit
|
||||
self.onRollback = onRollback
|
||||
}
|
||||
@@ -135,7 +138,7 @@ extension Database {
|
||||
}
|
||||
|
||||
/// The extent of the observation performed by a ``TransactionObserver``.
|
||||
public enum TransactionObservationExtent: Sendable {
|
||||
public enum TransactionObservationExtent {
|
||||
/// Observation lasts until observer is deallocated.
|
||||
case observerLifetime
|
||||
/// Observation lasts until the next transaction.
|
||||
@@ -282,20 +285,6 @@ 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
|
||||
@@ -580,11 +569,6 @@ 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()
|
||||
@@ -770,7 +754,7 @@ class DatabaseObservationBroker {
|
||||
|
||||
/// Transaction turns rollbacked because a transaction observer has
|
||||
/// cancelled a commit by throwing an error.
|
||||
case cancelledCommit(Error)
|
||||
case cancelledCommit(any Error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -801,16 +785,6 @@ 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.
|
||||
///
|
||||
@@ -886,15 +860,11 @@ extension TransactionObserver {
|
||||
public func databaseWillChange(with event: DatabasePreUpdateEvent) { }
|
||||
#endif
|
||||
|
||||
/// The default implementation does nothing.
|
||||
public func databaseDidChange() { }
|
||||
|
||||
/// Prevents the observer from receiving further change notifications
|
||||
/// until the next transaction.
|
||||
/// Prevents the observer from receiving further change notifications until
|
||||
/// the next transaction.
|
||||
///
|
||||
/// After this method has been called, the ``databaseDidChange(with:)``
|
||||
/// and ``databaseDidChange()-7olv7`` methods won't be called until the
|
||||
/// next transaction.
|
||||
/// method won't be called until the next transaction.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -907,13 +877,6 @@ 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
|
||||
///
|
||||
@@ -924,12 +887,12 @@ extension TransactionObserver {
|
||||
/// ```
|
||||
///
|
||||
/// - precondition: This method must be called from
|
||||
/// ``databaseDidChange(with:)`` or ``databaseDidChange()-7olv7``.
|
||||
/// ``databaseDidChange(with:)``.
|
||||
public func stopObservingDatabaseChangesUntilNextTransaction() {
|
||||
guard let broker = SchedulingWatchdog.current?.databaseObservationBroker else {
|
||||
fatalError("""
|
||||
stopObservingDatabaseChangesUntilNextTransaction must be called \
|
||||
from the `databaseDidChange()` or `databaseDidChange(with:)` methods
|
||||
from the databaseDidChange method
|
||||
""")
|
||||
}
|
||||
broker.disableUntilNextTransaction(transactionObserver: self)
|
||||
@@ -982,11 +945,6 @@ 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)
|
||||
@@ -1056,7 +1014,7 @@ struct StatementObservation {
|
||||
/// See the ``TransactionObserver/observes(eventsOfKind:)`` method in the
|
||||
/// ``TransactionObserver`` protocol for more information.
|
||||
@frozen
|
||||
public enum DatabaseEventKind: Sendable {
|
||||
public enum DatabaseEventKind {
|
||||
/// The insertion of a row in a database table.
|
||||
case insert(tableName: String)
|
||||
|
||||
@@ -1109,7 +1067,7 @@ protocol DatabaseEventProtocol {
|
||||
/// ``TransactionObserver`` protocol for more information.
|
||||
public struct DatabaseEvent {
|
||||
/// An event kind.
|
||||
public enum Kind: CInt, Sendable {
|
||||
public enum Kind: CInt {
|
||||
/// An insertion event
|
||||
case insert = 18 // SQLITE_INSERT
|
||||
|
||||
@@ -1173,11 +1131,6 @@ public struct DatabaseEvent {
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: this type can't be made Sendable
|
||||
// until GRDB7 where we can distinguish between a transient event and its copy.
|
||||
@available(*, unavailable)
|
||||
extension DatabaseEvent: Sendable { }
|
||||
|
||||
extension DatabaseEvent: DatabaseEventProtocol {
|
||||
func send(to observer: TransactionObservation) {
|
||||
observer.databaseDidChange(with: self)
|
||||
|
||||
@@ -21,9 +21,7 @@
|
||||
/// Yes, this is an awfully complex logic.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
|
||||
final class WALSnapshot: @unchecked Sendable {
|
||||
// @unchecked because sqlite3_snapshot has no threading requirements.
|
||||
// <https://www.sqlite.org/c3ref/snapshot.html>
|
||||
final class WALSnapshot: Sendable {
|
||||
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
|
||||
|
||||
init(_ db: Database) throws {
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
///
|
||||
/// `WALSnapshotTransaction` **takes ownership** of its reader
|
||||
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
|
||||
class WALSnapshotTransaction {
|
||||
final class WALSnapshotTransaction: Sendable {
|
||||
private let reader: SerializedDatabase
|
||||
private let release: (_ isInsideTransaction: Bool) -> Void
|
||||
private let release: @Sendable (_ isInsideTransaction: Bool) -> Void
|
||||
|
||||
/// The state of the database at the beginning of the transaction.
|
||||
let walSnapshot: WALSnapshot
|
||||
@@ -37,7 +37,7 @@ class WALSnapshotTransaction {
|
||||
/// is no longer used.
|
||||
init(
|
||||
onReader reader: SerializedDatabase,
|
||||
release: @escaping (_ isInsideTransaction: Bool) -> Void)
|
||||
release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
|
||||
throws
|
||||
{
|
||||
assert(reader.configuration.readonly)
|
||||
@@ -46,9 +46,7 @@ class WALSnapshotTransaction {
|
||||
// Open a long-lived transaction, and enter snapshot isolation
|
||||
self.walSnapshot = try reader.sync(allowingLongLivedTransaction: true) { db in
|
||||
try db.beginTransaction(.deferred)
|
||||
// This also acquires snapshot isolation because checking
|
||||
// database schema performs a read access.
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
|
||||
return try WALSnapshot(db)
|
||||
}
|
||||
self.reader = reader
|
||||
@@ -73,7 +71,7 @@ class WALSnapshotTransaction {
|
||||
|
||||
/// Schedules database operations for execution, and
|
||||
/// returns immediately.
|
||||
func asyncRead(_ value: @escaping (Database) -> Void) {
|
||||
func asyncRead(_ value: @escaping @Sendable (Database) -> Void) {
|
||||
// We should check the validity of the snapshot, as DatabaseSnapshotPool does.
|
||||
reader.async(value)
|
||||
}
|
||||
|
||||
@@ -391,17 +391,17 @@ extension Team: TableRecord {
|
||||
|
||||
### Querying the Database Schema
|
||||
|
||||
- ``Database/columns(in:in:)``
|
||||
- ``Database/foreignKeys(on:in:)``
|
||||
- ``Database/indexes(on:in:)``
|
||||
- ``Database/columns(in:)``
|
||||
- ``Database/foreignKeys(on:)``
|
||||
- ``Database/indexes(on:)``
|
||||
- ``Database/isGRDBInternalTable(_:)``
|
||||
- ``Database/isSQLiteInternalTable(_:)``
|
||||
- ``Database/primaryKey(_:in:)``
|
||||
- ``Database/primaryKey(_:)``
|
||||
- ``Database/schemaVersion()``
|
||||
- ``Database/table(_:hasUniqueKey:)``
|
||||
- ``Database/tableExists(_:in:)``
|
||||
- ``Database/triggerExists(_:in:)``
|
||||
- ``Database/viewExists(_:in:)``
|
||||
- ``Database/tableExists(_:)``
|
||||
- ``Database/triggerExists(_:)``
|
||||
- ``Database/viewExists(_:)``
|
||||
- ``ColumnInfo``
|
||||
- ``ForeignKeyInfo``
|
||||
- ``IndexInfo``
|
||||
@@ -410,9 +410,9 @@ extension Team: TableRecord {
|
||||
### Integrity Checks
|
||||
|
||||
- ``Database/checkForeignKeys()``
|
||||
- ``Database/checkForeignKeys(in:in:)``
|
||||
- ``Database/checkForeignKeys(in:)``
|
||||
- ``Database/foreignKeyViolations()``
|
||||
- ``Database/foreignKeyViolations(in:in:)``
|
||||
- ``Database/foreignKeyViolations(in:)``
|
||||
- ``ForeignKeyViolation``
|
||||
|
||||
### Sunsetted Methods
|
||||
|
||||
@@ -152,14 +152,11 @@ 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)
|
||||
```
|
||||
|
||||
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:
|
||||
With such a setup, you may still get `SQLITE_BUSY` errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout. You can catch those errors:
|
||||
|
||||
```swift
|
||||
do {
|
||||
@@ -231,7 +228,9 @@ 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
|
||||
@@ -247,8 +246,6 @@ 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,7 +6,11 @@
|
||||
|
||||
`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).
|
||||
|
||||
See <doc:GRDB/DatabaseRegionObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
|
||||
The only changes that are not notified are:
|
||||
|
||||
- Changes performed by external database connections.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
|
||||
`DatabaseRegionObservation` calls your application right after changes have been committed in the database, and before any other thread had any opportunity to perform further changes. *This is a pretty strong guarantee, that most applications do not really need.* Instead, most applications prefer to be notified with fresh values: make sure you check ``ValueObservation`` before using `DatabaseRegionObservation`.
|
||||
|
||||
@@ -74,30 +78,6 @@ 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,7 +25,13 @@ Database changes are notified to the ``databaseDidChange(with:)`` callback. This
|
||||
|
||||
Transaction completions are notified to the ``databaseWillCommit()-7mksu``, ``databaseDidCommit(_:)`` and ``databaseDidRollback(_:)`` callbacks.
|
||||
|
||||
> Important: Some changes and transactions are not automatically notified. See <doc:GRDB/TransactionObserver#Dealing-with-Undetected-Changes> below.
|
||||
The only changes and transactions that are not notified are:
|
||||
|
||||
- Read-only transactions.
|
||||
- Changes and transactions performed by external database connections.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
- The deletion of duplicate rows triggered by [`ON CONFLICT REPLACE`](https://www.sqlite.org/lang_conflict.html) clauses (this last exception might change in a future release of SQLite).
|
||||
|
||||
Notified changes are not actually written to disk until the transaction commits, and the `databaseDidCommit` callback is called. On the other side, `databaseDidRollback` confirms their invalidation:
|
||||
|
||||
@@ -183,7 +189,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:
|
||||
|
||||
@@ -229,41 +235,6 @@ 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
|
||||
@@ -273,7 +244,6 @@ try dbQueue.write { db in
|
||||
|
||||
### Handling Database Changes
|
||||
|
||||
- ``databaseDidChange()-7olv7``
|
||||
- ``databaseDidChange(with:)``
|
||||
- ``stopObservingDatabaseChangesUntilNextTransaction()``
|
||||
- ``DatabaseEvent``
|
||||
|
||||
@@ -6,7 +6,11 @@
|
||||
|
||||
`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).
|
||||
|
||||
See <doc:GRDB/ValueObservation#Dealing-with-Undetected-Changes> below for the list of exceptions.
|
||||
The only changes that are not notified are:
|
||||
|
||||
- Changes performed by external database connections. See <doc:DatabaseSharing#How-to-perform-cross-process-database-observation> for more information.
|
||||
- Changes to the database schema, changes to internal system tables such as `sqlite_master`.
|
||||
- Changes to [`WITHOUT ROWID`](https://www.sqlite.org/withoutrowid.html) tables.
|
||||
|
||||
## ValueObservation Usage
|
||||
|
||||
@@ -170,30 +174,6 @@ 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: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:)`` 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
|
||||
/// try db.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// db.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -40,7 +40,7 @@ extension Database {
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// try db.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// db.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -72,7 +72,7 @@ extension Database {
|
||||
/// // team
|
||||
/// // 1|Red
|
||||
/// // 2|Blue
|
||||
/// try db.dumpTables(["player", "team"])
|
||||
/// db.dumpTables(["player", "team"])
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -111,7 +111,7 @@ extension Database {
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// try db.dumpContent()
|
||||
/// db.dumpContent()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
@@ -129,9 +129,6 @@ 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.
|
||||
@@ -145,40 +142,6 @@ 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: -
|
||||
@@ -275,26 +238,6 @@ 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: """
|
||||
@@ -309,46 +252,30 @@ extension Database {
|
||||
""")
|
||||
for row in sqlRows {
|
||||
let name: String = row[1]
|
||||
if try ignoresObject(named: name) {
|
||||
if Database.isSQLiteInternalTable(name) || Database.isGRDBInternalTable(name) {
|
||||
continue
|
||||
}
|
||||
stream.writeln(row[0])
|
||||
}
|
||||
}
|
||||
|
||||
private func ignoresObject(named name: String) throws -> Bool {
|
||||
if Database.isSQLiteInternalTable(name) { return true }
|
||||
if Database.isGRDBInternalTable(name) { return true }
|
||||
if try isShadowTable(name) { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
private func isShadowTable(_ tableName: String) throws -> Bool {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Maybe SQLCipher is too old: check actual version
|
||||
if sqlite3_libversion_number() >= 3037000 {
|
||||
guard let table = try table(tableName) else {
|
||||
// Not a table
|
||||
return false
|
||||
|
||||
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))
|
||||
}
|
||||
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
|
||||
if tables.isEmpty { return }
|
||||
stream.write("\n")
|
||||
try _dumpTables(tables, format: format, tableHeader: .always, stableOrder: true, to: &stream)
|
||||
}
|
||||
}
|
||||
|
||||
/// Options for printing table names.
|
||||
public enum DumpTableHeaderOptions: Sendable {
|
||||
public enum DumpTableHeaderOptions {
|
||||
/// 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
|
||||
/// try dbQueue.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// dbQueue.dumpSQL("SELECT * FROM player ORDER BY id")
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -34,7 +34,7 @@ extension DatabaseReader {
|
||||
/// // Prints
|
||||
/// // 1|Arthur|500
|
||||
/// // 2|Barbara|1000
|
||||
/// try dbQueue.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// dbQueue.dumpRequest(Player.orderByPrimaryKey())
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -65,7 +65,7 @@ extension DatabaseReader {
|
||||
/// // team
|
||||
/// // 1|Red
|
||||
/// // 2|Blue
|
||||
/// try dbQueue.dumpTables(["player", "team"])
|
||||
/// dbQueue.dumpTables(["player", "team"])
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -103,7 +103,7 @@ extension DatabaseReader {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.dumpContent()
|
||||
/// dbQueue.dumpContent()
|
||||
/// ```
|
||||
///
|
||||
/// This prints the database schema as well as the content of all
|
||||
@@ -120,9 +120,6 @@ 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.
|
||||
@@ -137,37 +134,4 @@ 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: Sendable {
|
||||
public struct DebugDumpFormat {
|
||||
/// 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: Sendable {
|
||||
public struct JSONDumpFormat {
|
||||
/// 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: Sendable {
|
||||
public struct LineDumpFormat {
|
||||
/// 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: Sendable {
|
||||
public struct ListDumpFormat {
|
||||
/// 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: Sendable {
|
||||
public struct QuoteDumpFormat {
|
||||
/// A boolean value indicating if column labels are printed as the first
|
||||
/// line of output.
|
||||
public var header: Bool
|
||||
|
||||
+1
-6
@@ -29,7 +29,7 @@
|
||||
/// - ``tokenize(_:withTokenizer:)``
|
||||
public struct FTS3 {
|
||||
/// Options for Latin script characters.
|
||||
public enum Diacritics: Sendable {
|
||||
public enum Diacritics {
|
||||
/// Do not remove diacritics from Latin script characters. This option
|
||||
/// matches the `remove_diacritics=0` tokenizer argument.
|
||||
///
|
||||
@@ -183,8 +183,3 @@ public final class FTS3TableDefinition {
|
||||
columns.append(name)
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `FTS3TableDefinition` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension FTS3TableDefinition: Sendable { }
|
||||
@@ -16,7 +16,7 @@
|
||||
/// - ``init(matchingAllTokensIn:)``
|
||||
/// - ``init(matchingAnyTokenIn:)``
|
||||
/// - ``init(matchingPhrase:)``
|
||||
public struct FTS3Pattern: Sendable {
|
||||
public struct FTS3Pattern {
|
||||
/// The raw pattern string.
|
||||
///
|
||||
/// It is guaranteed to be a valid FTS3/4 pattern.
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
/// - ``simple``
|
||||
/// - ``unicode61(diacritics:separators:tokenCharacters:)``
|
||||
/// - ``FTS3/Diacritics``
|
||||
public struct FTS3TokenizerDescriptor: Sendable {
|
||||
public struct FTS3TokenizerDescriptor {
|
||||
let name: String
|
||||
let arguments: [String]
|
||||
|
||||
|
||||
@@ -313,11 +313,6 @@ 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``
|
||||
@@ -382,11 +377,6 @@ 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.
|
||||
///
|
||||
|
||||
+1
-11
@@ -44,7 +44,7 @@ public struct FTS5 {
|
||||
/// tokenizer argument.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#unicode61_tokenizer>
|
||||
public enum Diacritics: Sendable {
|
||||
public enum Diacritics {
|
||||
/// Do not remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=0" tokenizer argument.
|
||||
case keep
|
||||
@@ -492,11 +492,6 @@ 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``
|
||||
@@ -539,11 +534,6 @@ 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")
|
||||
|
||||
@@ -50,7 +50,7 @@ extension Database {
|
||||
|
||||
init(
|
||||
db: Database,
|
||||
constructor: @escaping (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> CInt)
|
||||
constructor: @escaping @Sendable (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> CInt)
|
||||
{
|
||||
self.db = db
|
||||
self.constructor = constructor
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
/// - ``init(matchingAnyTokenIn:)``
|
||||
/// - ``init(matchingPhrase:)``
|
||||
/// - ``init(matchingPrefixPhrase:)``
|
||||
public struct FTS5Pattern: Sendable {
|
||||
public struct FTS5Pattern {
|
||||
|
||||
/// The raw pattern string.
|
||||
///
|
||||
|
||||
@@ -16,7 +16,7 @@ public typealias FTS5TokenCallback = @convention(c) (
|
||||
/// The reason why FTS5 is requesting tokenization.
|
||||
///
|
||||
/// See the `FTS5_TOKENIZE_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
|
||||
public struct FTS5Tokenization: OptionSet, Sendable {
|
||||
public struct FTS5Tokenization: OptionSet {
|
||||
public let rawValue: CInt
|
||||
|
||||
public init(rawValue: CInt) {
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
/// ### Instantiating Tokenizers
|
||||
///
|
||||
/// - ``Database/makeTokenizer(_:)``
|
||||
public struct FTS5TokenizerDescriptor: Sendable {
|
||||
public struct FTS5TokenizerDescriptor {
|
||||
/// The tokenizer components.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -4,7 +4,7 @@ import Foundation
|
||||
/// Flags that tell SQLite how to register a token.
|
||||
///
|
||||
/// See the `FTS5_TOKEN_*` constants in <https://www.sqlite.org/fts5.html#custom_tokenizers>.
|
||||
public struct FTS5TokenFlags: OptionSet, Sendable {
|
||||
public struct FTS5TokenFlags: OptionSet {
|
||||
public let rawValue: CInt
|
||||
|
||||
public init(rawValue: CInt) {
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ extension DatabaseMigrator {
|
||||
@available(*, unavailable, message: "The completion function now accepts one Result<Database, Error> argument")
|
||||
public func asyncMigrate(
|
||||
_ writer: any DatabaseWriter,
|
||||
completion: @escaping (Database, Error?) -> Void)
|
||||
completion: @escaping (Database, (any Error)?) -> Void)
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@
|
||||
/// > .fetchAll(db)
|
||||
/// > }
|
||||
/// > ```
|
||||
public struct JSONColumn: ColumnExpression, SQLJSONExpressible, Sendable {
|
||||
public struct JSONColumn: ColumnExpression, SQLJSONExpressible {
|
||||
public var name: String
|
||||
|
||||
/// Creates a `JSONColumn` given its name.
|
||||
|
||||
@@ -40,9 +40,9 @@ import Foundation
|
||||
/// - ``completedMigrations(_:)``
|
||||
/// - ``hasBeenSuperseded(_:)``
|
||||
/// - ``hasCompletedMigrations(_:)``
|
||||
public struct DatabaseMigrator {
|
||||
public struct DatabaseMigrator: Sendable {
|
||||
/// Controls how a migration handle foreign keys constraints.
|
||||
public enum ForeignKeyChecks: Sendable {
|
||||
public enum ForeignKeyChecks {
|
||||
/// The migration runs with disabled foreign keys.
|
||||
///
|
||||
/// Foreign keys are checked right before changes are committed on disk,
|
||||
@@ -50,7 +50,7 @@ public struct DatabaseMigrator {
|
||||
/// ``DatabaseMigrator/disablingDeferredForeignKeyChecks()``.
|
||||
///
|
||||
/// In this case, you can perform your own deferred foreign key checks
|
||||
/// with ``Database/checkForeignKeys(in:in:)`` or
|
||||
/// with ``Database/checkForeignKeys(in:)`` or
|
||||
/// ``Database/checkForeignKeys()``:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -118,7 +118,7 @@ public struct DatabaseMigrator {
|
||||
/// The returned migrator is _unsafe_, because it no longer guarantees the
|
||||
/// integrity of the database. It is now _your_ responsibility to register
|
||||
/// migrations that do not break foreign key constraints. See
|
||||
/// ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:in:)``.
|
||||
/// ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:)``.
|
||||
///
|
||||
/// Running migrations without foreign key checks can improve migration
|
||||
/// performance on huge databases.
|
||||
@@ -207,7 +207,7 @@ public struct DatabaseMigrator {
|
||||
public mutating func registerMigration(
|
||||
_ identifier: String,
|
||||
foreignKeyChecks: ForeignKeyChecks = .deferred,
|
||||
migrate: @escaping (Database) throws -> Void)
|
||||
migrate: @escaping @Sendable (Database) throws -> Void)
|
||||
{
|
||||
let migrationChecks: Migration.ForeignKeyChecks
|
||||
switch foreignKeyChecks {
|
||||
@@ -264,7 +264,7 @@ public struct DatabaseMigrator {
|
||||
/// from succeeding.
|
||||
public func asyncMigrate(
|
||||
_ writer: some DatabaseWriter,
|
||||
completion: @escaping (Result<Database, Error>) -> Void)
|
||||
completion: @escaping @Sendable (Result<Database, any Error>) -> Void)
|
||||
{
|
||||
writer.asyncBarrierWriteWithoutTransaction { dbResult in
|
||||
do {
|
||||
@@ -523,9 +523,9 @@ extension DatabasePublishers {
|
||||
/// You build such a publisher from ``DatabaseMigrator``.
|
||||
public struct Migrate: Publisher {
|
||||
public typealias Output = Void
|
||||
public typealias Failure = Error
|
||||
public typealias Failure = any Error
|
||||
|
||||
fileprivate let upstream: AnyPublisher<Void, Error>
|
||||
fileprivate let upstream: AnyPublisher<Void, any Error>
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
|
||||
upstream.receive(subscriber: subscriber)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/// An internal struct that defines a migration.
|
||||
struct Migration {
|
||||
struct Migration: Sendable {
|
||||
enum ForeignKeyChecks {
|
||||
case deferred
|
||||
case immediate
|
||||
@@ -8,7 +8,7 @@ struct Migration {
|
||||
|
||||
let identifier: String
|
||||
var foreignKeyChecks: ForeignKeyChecks
|
||||
let migrate: (Database) throws -> Void
|
||||
let migrate: @Sendable (Database) throws -> Void
|
||||
|
||||
func run(_ db: Database) throws {
|
||||
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
<?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,7 +173,7 @@ extension Association {
|
||||
|
||||
// SelectionRequest conformance
|
||||
extension Association {
|
||||
public func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self {
|
||||
public func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.selectWhenConnected { db in
|
||||
try selection(db).map(\.sqlSelection)
|
||||
@@ -181,7 +181,7 @@ extension Association {
|
||||
}
|
||||
}
|
||||
|
||||
public func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self {
|
||||
public func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.annotatedWhenConnected { db in
|
||||
try selection(db).map(\.sqlSelection)
|
||||
@@ -192,7 +192,7 @@ extension Association {
|
||||
|
||||
// FilteredRequest conformance
|
||||
extension Association {
|
||||
public func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self {
|
||||
public func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.filterWhenConnected { db in
|
||||
try predicate(db).sqlExpression
|
||||
@@ -203,7 +203,7 @@ extension Association {
|
||||
|
||||
// OrderedRequest conformance
|
||||
extension Association {
|
||||
public func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self {
|
||||
public func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.orderWhenConnected { db in
|
||||
try orderings(db).map(\.sqlOrdering)
|
||||
@@ -239,7 +239,7 @@ extension Association {
|
||||
|
||||
// AggregatingRequest conformance
|
||||
extension Association {
|
||||
public func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self {
|
||||
public func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.groupWhenConnected { db in
|
||||
try expressions(db).map(\.sqlExpression)
|
||||
@@ -247,7 +247,7 @@ extension Association {
|
||||
}
|
||||
}
|
||||
|
||||
public func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self {
|
||||
public func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.havingWhenConnected { db in
|
||||
try predicate(db).sqlExpression
|
||||
|
||||
@@ -385,7 +385,7 @@ extension CommonTableExpression {
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to cte: CommonTableExpression<Destination>,
|
||||
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
{
|
||||
JoinAssociation(
|
||||
@@ -421,7 +421,7 @@ extension CommonTableExpression {
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to destination: Destination.Type,
|
||||
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
where Destination: TableRecord
|
||||
{
|
||||
@@ -458,7 +458,7 @@ extension CommonTableExpression {
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to destination: Table<Destination>,
|
||||
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
{
|
||||
JoinAssociation(
|
||||
|
||||
@@ -86,7 +86,7 @@ extension QueryInterfaceRequest: FetchRequest {
|
||||
.relation(relation)
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
@Sendable public func fetchCount(_ db: Database) throws -> Int {
|
||||
try relation.fetchCount(db)
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ extension QueryInterfaceRequest: FetchRequest {
|
||||
|
||||
extension QueryInterfaceRequest: SelectionRequest {
|
||||
public func selectWhenConnected(
|
||||
_ selection: @escaping (Database) throws -> [any SQLSelectable])
|
||||
_ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
|
||||
-> Self
|
||||
{
|
||||
with {
|
||||
@@ -281,7 +281,7 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
}
|
||||
|
||||
public func annotatedWhenConnected(
|
||||
with selection: @escaping (Database) throws -> [any SQLSelectable])
|
||||
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
|
||||
-> Self
|
||||
{
|
||||
with {
|
||||
@@ -294,7 +294,7 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
|
||||
extension QueryInterfaceRequest: FilteredRequest {
|
||||
public func filterWhenConnected(
|
||||
_ predicate: @escaping (Database) throws -> any SQLExpressible)
|
||||
_ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible)
|
||||
-> Self
|
||||
{
|
||||
with {
|
||||
@@ -307,7 +307,7 @@ extension QueryInterfaceRequest: FilteredRequest {
|
||||
|
||||
extension QueryInterfaceRequest: OrderedRequest {
|
||||
public func orderWhenConnected(
|
||||
_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm])
|
||||
_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm])
|
||||
-> Self
|
||||
{
|
||||
with {
|
||||
@@ -354,7 +354,7 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
|
||||
extension QueryInterfaceRequest: AggregatingRequest {
|
||||
public func groupWhenConnected(
|
||||
_ expressions: @escaping (Database) throws -> [any SQLExpressible])
|
||||
_ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible])
|
||||
-> Self
|
||||
{
|
||||
with {
|
||||
@@ -365,7 +365,7 @@ extension QueryInterfaceRequest: AggregatingRequest {
|
||||
}
|
||||
|
||||
public func havingWhenConnected(
|
||||
_ predicate: @escaping (Database) throws -> any SQLExpressible)
|
||||
_ predicate: @escaping @Sendable (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 (Database) throws -> [any SQLSelectable]) -> Self
|
||||
func selectWhenConnected(_ selection: @escaping @Sendable (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 (Database) throws -> [any SQLSelectable]) -> Self
|
||||
func annotatedWhenConnected(with selection: @escaping @Sendable (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 (Database) throws -> any SQLExpressible) -> Self
|
||||
func filterWhenConnected(_ predicate: @escaping @Sendable (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 (Database) throws -> [any SQLExpressible]) -> Self
|
||||
func groupWhenConnected(_ expressions: @escaping @Sendable (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 (Database) throws -> any SQLExpressible) -> Self
|
||||
func havingWhenConnected(_ predicate: @escaping @Sendable (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 (Database) throws -> [any SQLOrderingTerm]) -> Self
|
||||
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]) -> Self
|
||||
|
||||
/// Returns a request with reversed ordering.
|
||||
///
|
||||
|
||||
@@ -92,7 +92,7 @@ extension ColumnExpression where Self == Column {
|
||||
///
|
||||
/// - ``init(_:)-5grmu``
|
||||
/// - ``init(_:)-7xc4z``
|
||||
public struct Column: Sendable {
|
||||
public struct Column {
|
||||
/// The hidden rowID column.
|
||||
public static let rowID = Column("rowid")
|
||||
|
||||
|
||||
@@ -21,9 +21,9 @@
|
||||
///
|
||||
/// Such late computations are backed by DatabasePromise. In our example,
|
||||
/// see SQLRelation.filterPromise.
|
||||
struct DatabasePromise<T> {
|
||||
struct DatabasePromise<T: Sendable> {
|
||||
/// Returns the resolved value.
|
||||
let resolve: (Database) throws -> T
|
||||
let resolve: @Sendable (Database) throws -> T
|
||||
|
||||
/// Creates a promise that resolves to a value.
|
||||
init(value: T) {
|
||||
@@ -31,12 +31,12 @@ struct DatabasePromise<T> {
|
||||
}
|
||||
|
||||
/// Creates a promise from a closure.
|
||||
init(_ resolve: @escaping (Database) throws -> T) {
|
||||
init(_ resolve: @escaping @Sendable (Database) throws -> T) {
|
||||
self.resolve = resolve
|
||||
}
|
||||
|
||||
/// Returns a promise whose value is transformed by the given closure.
|
||||
func map<U>(_ transform: @escaping (T) throws -> U) -> DatabasePromise<U> {
|
||||
func map<U>(_ transform: @escaping @Sendable (T) throws -> U) -> DatabasePromise<U> {
|
||||
DatabasePromise<U> { db in
|
||||
try transform(resolve(db))
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ public struct SQLExpression {
|
||||
var preferredJSONInterpretation = JSONInterpretation.deferredToSQLite
|
||||
|
||||
/// The private implementation of the public `SQLExpression`.
|
||||
private enum Impl {
|
||||
private enum Impl: Sendable {
|
||||
/// A column.
|
||||
///
|
||||
/// id
|
||||
@@ -2109,7 +2109,7 @@ extension SQLExpression {
|
||||
/// A type that can be used as an SQL expression.
|
||||
///
|
||||
/// Related SQLite documentation <https://www.sqlite.org/syntax/expr.html>
|
||||
public protocol SQLExpressible {
|
||||
public protocol SQLExpressible: Sendable {
|
||||
/// Returns an SQL expression.
|
||||
var sqlExpression: SQLExpression { get }
|
||||
}
|
||||
|
||||
@@ -32,76 +32,41 @@ struct SQLForeignKeyRequest {
|
||||
}
|
||||
|
||||
// Incomplete information: let's look for schema foreign keys
|
||||
//
|
||||
// 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)
|
||||
}
|
||||
|
||||
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.
|
||||
""")
|
||||
let foreignKeys = try db.foreignKeys(on: originTable).filter { foreignKey in
|
||||
if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
let foreignKeys = try db.foreignKeys(on: originTable).filter { foreignKey in
|
||||
if destinationTable.lowercased() != foreignKey.destinationTable.lowercased() {
|
||||
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 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.
|
||||
""")
|
||||
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)")
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -111,28 +76,7 @@ struct SQLForeignKeyRequest {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
fatalError("Could not infer foreign key from \(originTable) to \(destinationTable)")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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, Sendable {
|
||||
public enum SQLDateModifier: SQLSpecificExpressible {
|
||||
/// Adds the specified amount of seconds
|
||||
case second(Double)
|
||||
|
||||
|
||||
@@ -138,7 +138,7 @@ extension SQLOrdering {
|
||||
/// ### Supporting Type
|
||||
///
|
||||
/// - ``SQLOrdering``
|
||||
public protocol SQLOrderingTerm {
|
||||
public protocol SQLOrderingTerm: Sendable {
|
||||
/// Returns an SQL ordering.
|
||||
var sqlOrdering: SQLOrdering { get }
|
||||
}
|
||||
|
||||
@@ -90,8 +90,8 @@
|
||||
/// // JOIN passport ON passport.citizenId = citizens.id
|
||||
/// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...);
|
||||
/// Country.including(all: Country.citizens)
|
||||
struct SQLRelation {
|
||||
struct Child: Refinable {
|
||||
struct SQLRelation: Sendable {
|
||||
struct Child: Refinable, Sendable {
|
||||
enum Kind {
|
||||
// Record.including(optional: association)
|
||||
case oneOptional
|
||||
@@ -187,7 +187,7 @@ extension SQLRelation {
|
||||
/// Convenience factory methods which selects all rows from a table.
|
||||
static func all(
|
||||
fromTable tableName: String,
|
||||
selection: @escaping (Database) -> [SQLSelection] = { _ in [.allColumns] })
|
||||
selection: @escaping @Sendable (Database) -> [SQLSelection] = { _ in [.allColumns] })
|
||||
-> Self
|
||||
{
|
||||
SQLRelation(
|
||||
@@ -197,7 +197,7 @@ extension SQLRelation {
|
||||
}
|
||||
|
||||
extension SQLRelation: Refinable {
|
||||
func selectWhenConnected(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
|
||||
func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self {
|
||||
with {
|
||||
$0.selectionPromise = DatabasePromise(selection)
|
||||
}
|
||||
@@ -228,7 +228,7 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
func annotatedWhenConnected(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
|
||||
func annotatedWhenConnected(with selection: @escaping @Sendable (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 (Database) throws -> SQLExpression) -> Self {
|
||||
func filterWhenConnected(_ predicate: @escaping @Sendable (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 (Database) throws -> [SQLOrdering]) -> Self {
|
||||
func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) -> Self {
|
||||
with {
|
||||
$0.ordering = SQLRelation.Ordering(orderings: orderings)
|
||||
}
|
||||
@@ -313,13 +313,13 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
func groupWhenConnected(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
|
||||
func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self {
|
||||
with {
|
||||
$0.groupPromise = DatabasePromise(expressions)
|
||||
}
|
||||
}
|
||||
|
||||
func havingWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
|
||||
func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self {
|
||||
with {
|
||||
if let old = $0.havingExpressionPromise {
|
||||
$0.havingExpressionPromise = DatabasePromise { db in
|
||||
@@ -672,7 +672,7 @@ struct SQLLimit {
|
||||
|
||||
// MARK: - SQLSource
|
||||
|
||||
struct SQLSource {
|
||||
struct SQLSource: Sendable {
|
||||
var tableName: String
|
||||
var alias: TableAlias?
|
||||
|
||||
@@ -691,7 +691,7 @@ struct SQLSource {
|
||||
|
||||
extension SQLRelation {
|
||||
/// SQLRelation.Ordering provides the order clause to SQLRelation.
|
||||
struct Ordering {
|
||||
struct Ordering: Sendable {
|
||||
private enum Element {
|
||||
case terms(DatabasePromise<[SQLOrdering]>)
|
||||
case ordering(SQLRelation.Ordering)
|
||||
@@ -740,7 +740,7 @@ extension SQLRelation {
|
||||
isReversed: false)
|
||||
}
|
||||
|
||||
init(orderings: @escaping (Database) throws -> [SQLOrdering]) {
|
||||
init(orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) {
|
||||
self.init(
|
||||
elements: [.terms(DatabasePromise(orderings))],
|
||||
isReversed: false)
|
||||
@@ -796,7 +796,7 @@ extension SQLRelation {
|
||||
/// // SELECT * FROM book WHERE author.id = 1
|
||||
/// // ~~~~~~~~~~~~~
|
||||
/// author.request(for: Author.books)
|
||||
enum SQLAssociationCondition {
|
||||
enum SQLAssociationCondition: Sendable {
|
||||
/// A condition based on a foreign key.
|
||||
case foreignKey(SQLForeignKeyCondition)
|
||||
|
||||
@@ -814,7 +814,7 @@ enum SQLAssociationCondition {
|
||||
/// player[Column("id")] == bonus[Column("playerID")]
|
||||
/// })
|
||||
/// Player.with(bonus).joining(required: association)
|
||||
case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpression?)
|
||||
case expression(@Sendable (_ left: TableAlias, _ right: TableAlias) -> SQLExpression?)
|
||||
|
||||
/// The condition that does not constrain the two associated tables
|
||||
/// in any way.
|
||||
@@ -847,7 +847,7 @@ enum SQLAssociationCondition {
|
||||
}
|
||||
|
||||
/// An association condition based on a foreign key.
|
||||
struct SQLForeignKeyCondition: Equatable {
|
||||
struct SQLForeignKeyCondition: Equatable, Sendable {
|
||||
/// The destination table of an association.
|
||||
///
|
||||
/// In `Author.hasMany(Book.self)`, the destination is `book`.
|
||||
|
||||
@@ -19,7 +19,7 @@ public struct SQLSelection {
|
||||
private var impl: Impl
|
||||
|
||||
/// The private implementation of the public `SQLSelection`.
|
||||
private enum Impl {
|
||||
private enum Impl: Sendable {
|
||||
/// All columns: `*`
|
||||
case allColumns
|
||||
|
||||
@@ -301,7 +301,7 @@ enum SQLCount {
|
||||
///
|
||||
/// - ``AllColumns``
|
||||
/// - ``SQLSelection``
|
||||
public protocol SQLSelectable {
|
||||
public protocol SQLSelectable: Sendable {
|
||||
/// Returns an SQL selection.
|
||||
var sqlSelection: SQLSelection { get }
|
||||
}
|
||||
@@ -324,7 +324,7 @@ extension SQLSelection: SQLSelectable {
|
||||
/// let players = try Player.select(AllColumns()).fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public struct AllColumns: Sendable {
|
||||
public struct AllColumns {
|
||||
/// The `*` selection.
|
||||
public init() { }
|
||||
}
|
||||
|
||||
@@ -800,7 +800,7 @@ extension Table {
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
@Sendable 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.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
@Sendable 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.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
@Sendable 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.
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
@Sendable 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.
|
||||
public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
@Sendable 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.
|
||||
public func fetchOne(_ db: Database) throws -> Row? {
|
||||
@Sendable 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.
|
||||
public func fetchSet(_ db: Database) throws -> Set<Row> {
|
||||
@Sendable 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.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
@Sendable 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.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
@Sendable 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.
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
@Sendable 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.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
@Sendable 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.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
@Sendable 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.
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
try all().fetchSet(db)
|
||||
}
|
||||
}
|
||||
@@ -1297,7 +1297,7 @@ extension Table {
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to cte: CommonTableExpression<Destination>,
|
||||
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
{
|
||||
JoinAssociation(
|
||||
|
||||
@@ -547,7 +547,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
/// ORDER BY ... -- ordering
|
||||
/// LIMIT ... -- limit
|
||||
|
||||
private struct SQLQualifiedRelation {
|
||||
private struct SQLQualifiedRelation: Sendable {
|
||||
/// All aliases, including aliases of joined relations
|
||||
var allAliases: [TableAlias] {
|
||||
joins.reduce(into: [source.alias].compactMap { $0 }) {
|
||||
@@ -713,7 +713,7 @@ private struct SQLQualifiedRelation {
|
||||
extension SQLQualifiedRelation: Refinable { }
|
||||
|
||||
/// A "qualified" source, where all tables are identified with a table alias.
|
||||
private struct SQLQualifiedSource {
|
||||
private struct SQLQualifiedSource: Sendable {
|
||||
var tableName: String
|
||||
var alias: TableAlias
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ public final class ColumnDefinition {
|
||||
/// The kind of a generated column.
|
||||
///
|
||||
/// Related SQLite documentation: <https://sqlite.org/gencol.html#virtual_versus_stored_columns>
|
||||
public enum GeneratedColumnQualification: Sendable {
|
||||
public enum GeneratedColumnQualification {
|
||||
/// A `VIRTUAL` generated column.
|
||||
case virtual
|
||||
/// A `STORED` generated column.
|
||||
@@ -565,8 +565,3 @@ 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 { }
|
||||
@@ -365,7 +365,7 @@ extension Database {
|
||||
view name: String,
|
||||
options: ViewOptions = [],
|
||||
columns: [String]? = nil,
|
||||
as request: SQLSubqueryable)
|
||||
as request: some SQLSubqueryable)
|
||||
throws {
|
||||
var literal: SQL = "CREATE "
|
||||
|
||||
@@ -681,7 +681,7 @@ extension Database {
|
||||
}
|
||||
|
||||
/// View creation options
|
||||
public struct ViewOptions: OptionSet, Sendable {
|
||||
public struct ViewOptions: OptionSet {
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
|
||||
@@ -104,8 +104,3 @@ 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 { }
|
||||
@@ -7,7 +7,7 @@ struct IndexDefinition {
|
||||
}
|
||||
|
||||
/// Index creation options
|
||||
public struct IndexOptions: OptionSet, Sendable {
|
||||
public struct IndexOptions: OptionSet {
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
|
||||
@@ -161,8 +161,3 @@ public final class TableAlteration {
|
||||
alterations.append(.drop(name))
|
||||
}
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: `TableAlteration` is a mutable
|
||||
// class and there is no known reason for making it thread-safe.
|
||||
@available(*, unavailable)
|
||||
extension TableAlteration: Sendable { }
|
||||
@@ -1,5 +1,5 @@
|
||||
/// Table creation options.
|
||||
public struct TableOptions: OptionSet, Sendable {
|
||||
public struct TableOptions: OptionSet {
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
@@ -753,8 +753,3 @@ 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 { }
|
||||
@@ -339,7 +339,7 @@ extension TableRecord {
|
||||
/// - returns: An association to the common table expression.
|
||||
public static func association<Destination>(
|
||||
to cte: CommonTableExpression<Destination>,
|
||||
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
-> JoinAssociation<Self, Destination>
|
||||
{
|
||||
JoinAssociation(
|
||||
@@ -540,6 +540,7 @@ extension TableRecord {
|
||||
// MARK: - Request for associated records
|
||||
|
||||
extension TableRecord where Self: EncodableRecord {
|
||||
// TODO: GRDB7: require that Self is Sendable
|
||||
/// Returns a request for the associated record(s).
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -29,11 +29,11 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
func unkeyedContainer() -> any UnkeyedEncodingContainer {
|
||||
fatalError("unkeyed encoding is not supported")
|
||||
}
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
func singleValueContainer() -> any SingleValueEncodingContainer {
|
||||
// @itaiferber on https://forums.swift.org/t/how-to-encode-objects-of-unknown-type/12253/11
|
||||
//
|
||||
// > Encoding a value into a single-value container is equivalent to
|
||||
@@ -109,15 +109,15 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer {
|
||||
func nestedUnkeyedContainer(forKey key: Key) -> any UnkeyedEncodingContainer {
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
|
||||
func superEncoder() -> Encoder {
|
||||
func superEncoder() -> any Encoder {
|
||||
recordEncoder
|
||||
}
|
||||
|
||||
func superEncoder(forKey key: Key) -> Encoder {
|
||||
func superEncoder(forKey key: Key) -> any Encoder {
|
||||
recordEncoder
|
||||
}
|
||||
}
|
||||
@@ -195,7 +195,7 @@ private class ColumnEncoder<Record: EncodableRecord>: Encoder {
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
func unkeyedContainer() -> any UnkeyedEncodingContainer {
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
@@ -205,7 +205,7 @@ private class ColumnEncoder<Record: EncodableRecord>: Encoder {
|
||||
return JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer { self }
|
||||
func singleValueContainer() -> any SingleValueEncodingContainer { self }
|
||||
}
|
||||
|
||||
extension ColumnEncoder: SingleValueEncodingContainer {
|
||||
|
||||
@@ -7,7 +7,6 @@ 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`
|
||||
@@ -80,7 +79,7 @@ public class FetchableRecordDecoder {
|
||||
/// The decoder that decodes a record from a database row
|
||||
private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
var row: Row
|
||||
var codingPath: [CodingKey]
|
||||
var codingPath: [any CodingKey]
|
||||
var columnDecodingStrategy: DatabaseColumnDecodingStrategy
|
||||
var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo }
|
||||
|
||||
@@ -88,7 +87,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
KeyedDecodingContainer(KeyedContainer<Key>(decoder: self))
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
func unkeyedContainer() throws -> any UnkeyedDecodingContainer {
|
||||
guard let codingKey = codingPath.last else {
|
||||
fatalError("unkeyed decoding from database row is not supported")
|
||||
}
|
||||
@@ -106,7 +105,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
debugDescription: debugDescription))
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
func singleValueContainer() throws -> any SingleValueDecodingContainer {
|
||||
guard let key = codingPath.last else {
|
||||
// Decoding an array of scalars from rows: pick the first column
|
||||
return ColumnDecoder<R>(row: row, columnIndex: 0, codingPath: codingPath)
|
||||
@@ -124,8 +123,8 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
|
||||
class KeyedContainer<Key: CodingKey>: KeyedDecodingContainerProtocol {
|
||||
private let decoder: _RowDecoder
|
||||
var codingPath: [CodingKey] { decoder.codingPath }
|
||||
private var decodedRootKey: CodingKey?
|
||||
var codingPath: [any CodingKey] { decoder.codingPath }
|
||||
private var decodedRootKey: (any CodingKey)?
|
||||
// Not nil iff decoder has a columnDecodingStrategy
|
||||
private let _columnForKey: [String: String]?
|
||||
|
||||
@@ -379,17 +378,17 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
fatalError("not implemented")
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
|
||||
func nestedUnkeyedContainer(forKey key: Key) throws -> any UnkeyedDecodingContainer {
|
||||
throw DecodingError.typeMismatch(
|
||||
UnkeyedDecodingContainer.self,
|
||||
(any UnkeyedDecodingContainer).self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
|
||||
}
|
||||
|
||||
func superDecoder() throws -> Decoder {
|
||||
func superDecoder() throws -> any Decoder {
|
||||
decoder
|
||||
}
|
||||
|
||||
func superDecoder(forKey key: Key) throws -> Decoder {
|
||||
func superDecoder(forKey key: Key) throws -> any Decoder {
|
||||
decoder
|
||||
}
|
||||
|
||||
@@ -398,7 +397,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
private func decode<T>(
|
||||
_ type: T.Type,
|
||||
fromRow row: Row,
|
||||
codingPath: [CodingKey])
|
||||
codingPath: [any CodingKey])
|
||||
throws -> T
|
||||
where T: Decodable
|
||||
{
|
||||
@@ -450,11 +449,11 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
|
||||
private struct PrefetchedRowsDecoder<R: FetchableRecord>: Decoder {
|
||||
var rows: [Row]
|
||||
var codingPath: [CodingKey]
|
||||
var codingPath: [any CodingKey]
|
||||
var currentIndex: Int
|
||||
var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo }
|
||||
|
||||
init(rows: [Row], codingPath: [CodingKey]) {
|
||||
init(rows: [Row], codingPath: [any CodingKey]) {
|
||||
self.rows = rows
|
||||
self.codingPath = codingPath
|
||||
self.currentIndex = 0
|
||||
@@ -464,9 +463,9 @@ private struct PrefetchedRowsDecoder<R: FetchableRecord>: Decoder {
|
||||
fatalError("keyed decoding from prefetched rows is not supported")
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer { self }
|
||||
func unkeyedContainer() throws -> any UnkeyedDecodingContainer { self }
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
func singleValueContainer() throws -> any SingleValueDecodingContainer {
|
||||
fatalError("single value decoding from prefetched rows is not supported")
|
||||
}
|
||||
}
|
||||
@@ -502,11 +501,11 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer {
|
||||
fatalError("not implemented")
|
||||
}
|
||||
|
||||
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
mutating func nestedUnkeyedContainer() throws -> any UnkeyedDecodingContainer {
|
||||
fatalError("not implemented")
|
||||
}
|
||||
|
||||
mutating func superDecoder() throws -> Decoder {
|
||||
mutating func superDecoder() throws -> any Decoder {
|
||||
fatalError("not implemented")
|
||||
}
|
||||
}
|
||||
@@ -517,7 +516,7 @@ extension PrefetchedRowsDecoder: UnkeyedDecodingContainer {
|
||||
private struct ColumnDecoder<R: FetchableRecord>: Decoder {
|
||||
var row: Row
|
||||
var columnIndex: Int
|
||||
var codingPath: [CodingKey]
|
||||
var codingPath: [any CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { R.databaseDecodingUserInfo }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
|
||||
@@ -525,12 +524,12 @@ private struct ColumnDecoder<R: FetchableRecord>: Decoder {
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
func unkeyedContainer() throws -> any UnkeyedDecodingContainer {
|
||||
// We need to switch to JSON decoding
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer { self }
|
||||
func singleValueContainer() throws -> any SingleValueDecodingContainer { self }
|
||||
}
|
||||
|
||||
extension ColumnDecoder: SingleValueDecodingContainer {
|
||||
|
||||
@@ -52,7 +52,7 @@ extension FetchableRecord where Self: TableRecord {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: Database) throws -> [Self] {
|
||||
@Sendable 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.
|
||||
public static func fetchOne(_ db: Database) throws -> Self? {
|
||||
@Sendable 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.
|
||||
public static func fetchSet(_ db: Database) throws -> Set<Self> {
|
||||
@Sendable 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.
|
||||
public static func fetchAll<Keys>(_ db: Database, keys: Keys)
|
||||
@Sendable 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.
|
||||
public static func fetchOne(_ db: Database, key: some DatabaseValueConvertible) throws -> Self? {
|
||||
@Sendable 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.
|
||||
public static func fetchAll<IDS>(_ db: Database, ids: IDS) throws -> [Self]
|
||||
@Sendable 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.
|
||||
public static func fetchOne(_ db: Database, id: ID) throws -> Self? {
|
||||
@Sendable 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.
|
||||
public static func fetchSet<Keys>(_ db: Database, keys: Keys)
|
||||
@Sendable 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.
|
||||
public static func fetchSet<IDS>(_ db: Database, ids: IDS) throws -> Set<Self>
|
||||
@Sendable public static func fetchSet<IDS>(_ db: Database, ids: IDS) throws -> Set<Self>
|
||||
where IDS: Collection, IDS.Element == ID
|
||||
{
|
||||
if ids.isEmpty {
|
||||
@@ -449,7 +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.
|
||||
public static func fetchAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] {
|
||||
@Sendable public static func fetchAll(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> [Self] {
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return []
|
||||
@@ -473,7 +473,7 @@ extension FetchableRecord where Self: TableRecord {
|
||||
/// - key: A key dictionary.
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? {
|
||||
@Sendable public static func fetchOne(_ db: Database, key: [String: (any DatabaseValueConvertible)?]?) throws -> Self? {
|
||||
guard let key else {
|
||||
// Avoid hitting the database
|
||||
return nil
|
||||
@@ -527,7 +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.
|
||||
public static func fetchSet(_ db: Database, keys: [[String: (any DatabaseValueConvertible)?]]) throws -> Set<Self> {
|
||||
@Sendable 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.
|
||||
public static func fetchAll(
|
||||
@Sendable 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.
|
||||
public static func fetchOne(
|
||||
@Sendable 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.
|
||||
public static func fetchSet(
|
||||
@Sendable 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.
|
||||
public static func fetchAll(
|
||||
@Sendable 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.
|
||||
public static func fetchOne(
|
||||
@Sendable 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.
|
||||
public static func fetchSet(
|
||||
@Sendable 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.
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
@Sendable 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.
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
@Sendable 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.
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
@Sendable 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.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
@Sendable 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.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
@Sendable 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.
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
@Sendable public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
try RowDecoder.fetchSet(db, self)
|
||||
}
|
||||
}
|
||||
@@ -854,11 +854,6 @@ 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
|
||||
@@ -972,7 +967,7 @@ public enum DatabaseColumnDecodingStrategy {
|
||||
case convertFromSnakeCase
|
||||
|
||||
/// A key decoding strategy defined by the closure you supply.
|
||||
case custom((String) -> CodingKey)
|
||||
case custom((String) -> any CodingKey)
|
||||
|
||||
func key<K: CodingKey>(forColumn column: String) -> K? {
|
||||
switch self {
|
||||
|
||||
@@ -348,7 +348,7 @@ extension MutablePersistableRecord {
|
||||
/// See `MutablePersistableRecord.persistenceConflictPolicy`.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_conflict.html>
|
||||
public struct PersistenceConflictPolicy: Sendable {
|
||||
public struct PersistenceConflictPolicy {
|
||||
/// The conflict resolution algorithm for insertions
|
||||
public let conflictResolutionForInsert: Database.ConflictResolution
|
||||
|
||||
|
||||
@@ -224,7 +224,7 @@ extension TableRecord {
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public static func fetchCount(_ db: Database) throws -> Int {
|
||||
@Sendable public static func fetchCount(_ db: Database) throws -> Int {
|
||||
try all().fetchCount(db)
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 178 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user