mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-01 04:38:44 +00:00
Compare commits
102
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3dd3bbf0c5 | ||
|
|
d7cf0f9e59 | ||
|
|
389c3e0d4a | ||
|
|
a212bf9e89 | ||
|
|
65186104cc | ||
|
|
2f108508fa | ||
|
|
5513eab099 | ||
|
|
2ad2d20a89 | ||
|
|
dd90fe6e62 | ||
|
|
691207567a | ||
|
|
c7f1dd7470 | ||
|
|
8e5b9ca9bd | ||
|
|
dc7d47c066 | ||
|
|
14f60ad48f | ||
|
|
e758fde941 | ||
|
|
7477e1cff8 | ||
|
|
2d6fe172c3 | ||
|
|
0526853dde | ||
|
|
a60810f28e | ||
|
|
c35095c6da | ||
|
|
f878d99733 | ||
|
|
48a17ce490 | ||
|
|
361a482b1e | ||
|
|
8cba324d6e | ||
|
|
17e1683b66 | ||
|
|
b1b83abd8b | ||
|
|
d06c9ed6b5 | ||
|
|
9a98ed6292 | ||
|
|
5cc85a98f3 | ||
|
|
edc1d646f0 | ||
|
|
ab09078842 | ||
|
|
267e1ea5a6 | ||
|
|
18497b68fd | ||
|
|
19e33e2e7d | ||
|
|
76e0815907 | ||
|
|
85ad232b0b | ||
|
|
db695cf7dc | ||
|
|
76a7be8404 | ||
|
|
196c33ba63 | ||
|
|
50a74f7b03 | ||
|
|
3f27fb9289 | ||
|
|
62fdd41d75 | ||
|
|
c5d02eac32 | ||
|
|
d1bfce829b | ||
|
|
edd292bcbd | ||
|
|
a0e101e683 | ||
|
|
9ef5e2c8eb | ||
|
|
f5dc68fc6f | ||
|
|
b210ec7428 | ||
|
|
a7e3acf409 | ||
|
|
ca27f75760 | ||
|
|
99ecf76a77 | ||
|
|
f4991273c2 | ||
|
|
1b98a964d7 | ||
|
|
1095d21abd | ||
|
|
eb2378a741 | ||
|
|
37dde39557 | ||
|
|
5786391dc9 | ||
|
|
e1abafaae3 | ||
|
|
93d0baeade | ||
|
|
26ebd7e147 | ||
|
|
75e99861af | ||
|
|
2e433a3cb2 | ||
|
|
9518d74fa6 | ||
|
|
c7bbebc80f | ||
|
|
38f5226e95 | ||
|
|
2b19803644 | ||
|
|
d7d61add23 | ||
|
|
d040588849 | ||
|
|
30313623eb | ||
|
|
aab2664431 | ||
|
|
f3acfecc16 | ||
|
|
aa2cdb7ec3 | ||
|
|
d90ba851fe | ||
|
|
7eea8ccb91 | ||
|
|
6a25b3538e | ||
|
|
7ec88b76e0 | ||
|
|
1a3842e4bc | ||
|
|
32ed290a1b | ||
|
|
f88c7202cd | ||
|
|
79ce0ff5f3 | ||
|
|
f435715f75 | ||
|
|
cf1702630f | ||
|
|
fd7adf7fb3 | ||
|
|
be0f0c6f25 | ||
|
|
cd84db3873 | ||
|
|
4cfa692ddd | ||
|
|
8dfbbb50f6 | ||
|
|
3f69614405 | ||
|
|
b4f3a83755 | ||
|
|
7cd2a4563c | ||
|
|
2698c55654 | ||
|
|
37065fb503 | ||
|
|
3801ab9ac6 | ||
|
|
26abd8ad79 | ||
|
|
827ab62bb6 | ||
|
|
fdeb88a6bd | ||
|
|
8ba1bc9a96 | ||
|
|
c4e39285a0 | ||
|
|
1622b72b62 | ||
|
|
215128390d | ||
|
|
c5283a0bd9 |
No files matched your search
+30
-30
@@ -1,4 +1,4 @@
|
||||
# https://github.com/actions/runner-images/blob/main/images/macos/macos-14-Readme.md
|
||||
# https://github.com/actions/runner-images/blob/main/images/macos/macos-15-Readme.md
|
||||
|
||||
name: "GRDB CI"
|
||||
|
||||
@@ -40,20 +40,20 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.1,name=iPhone 16 Pro"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
destination: "OS=18.5,name=iPhone 16 Pro"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.1,name=Apple TV"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
destination: "OS=18.5,name=Apple TV"
|
||||
name: "tvOS"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
|
||||
SPM:
|
||||
@@ -66,11 +66,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_SPM test_install_SPM
|
||||
SQLCipher3:
|
||||
@@ -83,11 +83,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher3Encrypted
|
||||
SQLCipher4:
|
||||
@@ -100,11 +100,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher4Encrypted
|
||||
CustomSQLite:
|
||||
@@ -117,11 +117,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBCustomSQLiteOSX
|
||||
XCFramework:
|
||||
@@ -134,11 +134,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_universal_xcframework
|
||||
|
||||
@@ -2,4 +2,4 @@ version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [GRDB]
|
||||
swift_version: 6.0
|
||||
swift_version: 6.1
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"editor.formatOnSave": false,
|
||||
"editor.insertSpaces": true,
|
||||
"editor.tabSize": 4,
|
||||
"editor.detectIndentation": false,
|
||||
"editor.trimAutoWhitespace": false
|
||||
}
|
||||
+30
-1
@@ -7,7 +7,9 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 7.x Releases
|
||||
|
||||
- `7.6.x` Releases - [7.6.0](#760)
|
||||
- `7.8.x` Releases - [7.8.0](#780)
|
||||
- `7.7.x` Releases - [7.7.0](#770) - [7.7.1](#771)
|
||||
- `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761)
|
||||
- `7.5.x` Releases - [7.5.0](#750)
|
||||
- `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741)
|
||||
- `7.3.x` Releases - [7.3.0](#730)
|
||||
@@ -138,6 +140,33 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 7.8.0
|
||||
|
||||
Released October 2, 2025
|
||||
|
||||
- **New**: Merged Migrations by [@groue](https://github.com/groue) in [#1818](https://github.com/groue/GRDB.swift/pull/1818)
|
||||
|
||||
## 7.7.1
|
||||
|
||||
Released September 29, 2025
|
||||
|
||||
- **Fixed**: Fix the save() method for record types with attached triggers by [@groue](https://github.com/groue) in [#1822](https://github.com/groue/GRDB.swift/pull/1822)
|
||||
|
||||
## 7.7.0
|
||||
|
||||
Released September 23, 2025
|
||||
|
||||
- **New**: Update GRDB7MigrationGuide.md reference by [@emmanuel-ferdman](https://github.com/emmanuel-ferdman) in [#1807](https://github.com/groue/GRDB.swift/pull/1807)
|
||||
- **New**: Persistable Database Views by [@groue](https://github.com/groue) in [#1810](https://github.com/groue/GRDB.swift/pull/1810)
|
||||
- **New**: Support for Xcode 26 by [@groue](https://github.com/groue) in [#1813](https://github.com/groue/GRDB.swift/pull/1813)
|
||||
- **Fixed**: Fix another race condition regarding Task cancellation, completing [#1797](https://github.com/groue/GRDB.swift/pull/1797)
|
||||
|
||||
## 7.6.1
|
||||
|
||||
Released July 23, 2025
|
||||
|
||||
- **Fixed**: Fix race condition regarding Task cancellation by [@groue](https://github.com/groue) in [#1797](https://github.com/groue/GRDB.swift/pull/1797)
|
||||
|
||||
## 7.6.0
|
||||
|
||||
Released July 20, 2025
|
||||
|
||||
@@ -9,6 +9,8 @@ A custom SQLite build can activate extra SQLite features, and extra GRDB feature
|
||||
|
||||
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
|
||||
|
||||
> Warning: The technique described here is not compatible with the Swift Package Manager (SPM). It will create [build issues](https://github.com/groue/GRDB.swift/issues/1709) with SPM companion librairies such as [GRDBQuery](https://github.com/groue/GRDBQuery) or [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting).
|
||||
|
||||
**To install GRDB with a custom SQLite build:**
|
||||
|
||||
1. Clone the GRDB git repository, checkout the latest tagged version:
|
||||
|
||||
@@ -158,7 +158,7 @@
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 1600;
|
||||
LastUpgradeCheck = 2600;
|
||||
TargetAttributes = {
|
||||
56CFC6432C9F1DC9000B5023 = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
@@ -293,6 +293,7 @@
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
@@ -350,6 +351,7 @@
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
@@ -380,7 +382,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
SWIFT_VERSION = 6.1;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -409,7 +411,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.0;
|
||||
SWIFT_VERSION = 6.1;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Release;
|
||||
@@ -425,7 +427,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
||||
SWIFT_VERSION = 6.0;
|
||||
SWIFT_VERSION = 6.1;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
|
||||
};
|
||||
@@ -442,7 +444,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
||||
SWIFT_VERSION = 6.0;
|
||||
SWIFT_VERSION = 6.1;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
|
||||
};
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1600"
|
||||
LastUpgradeVersion = "2600"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -56,7 +56,7 @@ import GRDB
|
||||
|
||||
// Start observing the database.
|
||||
// Previous observation, if any, is cancelled.
|
||||
cancellable = observation.start(in: appDatabase.reader) { error in
|
||||
cancellable = observation.start(in: appDatabase.reader, scheduling: .immediate) { error in
|
||||
// Handle error
|
||||
} onChange: { [unowned self] players in
|
||||
self.players = players
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '7.6.0'
|
||||
s.version = '7.8.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
@@ -9,7 +9,7 @@ Pod::Spec.new do |s|
|
||||
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
|
||||
s.module_name = 'GRDB'
|
||||
|
||||
s.swift_versions = ['6']
|
||||
s.swift_versions = ['6.1']
|
||||
s.ios.deployment_target = '13.0'
|
||||
s.osx.deployment_target = '10.15'
|
||||
s.watchos.deployment_target = '7.0'
|
||||
@@ -21,7 +21,7 @@ Pod::Spec.new do |s|
|
||||
ss.framework = 'Foundation'
|
||||
ss.library = 'sqlite3'
|
||||
ss.xcconfig = {
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5',
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5 -D GRDBFRAMEWORK',
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
@@ -81,6 +81,7 @@
|
||||
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */; };
|
||||
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; };
|
||||
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
|
||||
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
|
||||
@@ -223,6 +224,7 @@
|
||||
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
|
||||
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; };
|
||||
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; };
|
||||
568515A42E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
|
||||
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */; };
|
||||
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
|
||||
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
|
||||
@@ -288,6 +290,7 @@
|
||||
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; };
|
||||
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */; };
|
||||
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
|
||||
56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */; };
|
||||
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF2281241781C5003D86EB /* UtilsTests.swift */; };
|
||||
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
|
||||
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
|
||||
@@ -503,6 +506,7 @@
|
||||
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
|
||||
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
|
||||
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
|
||||
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSource.swift; sourceTree = "<group>"; };
|
||||
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
|
||||
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
|
||||
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
|
||||
@@ -674,6 +678,7 @@
|
||||
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = "<group>"; };
|
||||
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = "<group>"; };
|
||||
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = "<group>"; };
|
||||
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
|
||||
56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
|
||||
@@ -792,6 +797,7 @@
|
||||
56B964C11DA521450002DA19 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = "<group>"; };
|
||||
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TableBuilderTests.swift; sourceTree = "<group>"; };
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = "<group>"; };
|
||||
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = "<group>"; };
|
||||
56BF2281241781C5003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = "<group>"; };
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
|
||||
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
|
||||
@@ -997,6 +1003,7 @@
|
||||
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
|
||||
563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */,
|
||||
563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */,
|
||||
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */,
|
||||
);
|
||||
name = PersistableRecord;
|
||||
sourceTree = "<group>";
|
||||
@@ -1486,6 +1493,7 @@
|
||||
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
|
||||
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
|
||||
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */,
|
||||
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */,
|
||||
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
|
||||
@@ -1592,6 +1600,7 @@
|
||||
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */,
|
||||
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
|
||||
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
@@ -1842,8 +1851,9 @@
|
||||
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastSwiftUpdateCheck = 0730;
|
||||
LastUpgradeCheck = 1400;
|
||||
LastUpgradeCheck = 2600;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
56E5D7F81B4D422D00430942 = {
|
||||
@@ -2009,6 +2019,7 @@
|
||||
56677C15241D14450050755D /* FailureTestCase.swift in Sources */,
|
||||
5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
|
||||
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
|
||||
568515A42E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
|
||||
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
|
||||
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
|
||||
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
|
||||
@@ -2113,6 +2124,7 @@
|
||||
D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
|
||||
5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */,
|
||||
56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */,
|
||||
56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
|
||||
56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */,
|
||||
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
|
||||
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
|
||||
@@ -2207,6 +2219,7 @@
|
||||
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */,
|
||||
56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
|
||||
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
|
||||
@@ -2539,6 +2552,7 @@
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = 1;
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_MODULE_VERIFIER = YES;
|
||||
INFOPLIST_FILE = Support/Info.plist;
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
@@ -2546,6 +2560,7 @@
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
|
||||
SKIP_INSTALL = YES;
|
||||
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
|
||||
SUPPORTS_MACCATALYST = YES;
|
||||
@@ -2570,6 +2585,7 @@
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = 1;
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_MODULE_VERIFIER = YES;
|
||||
INFOPLIST_FILE = Support/Info.plist;
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
@@ -2577,6 +2593,7 @@
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
|
||||
SKIP_INSTALL = YES;
|
||||
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
|
||||
SUPPORTS_MACCATALYST = YES;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1400"
|
||||
LastUpgradeVersion = "2600"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
#if !canImport(Darwin)
|
||||
@@ -87,7 +90,7 @@ public struct Configuration: Sendable {
|
||||
/// with the number of snapshots.
|
||||
///
|
||||
/// The default configuration label is nil.
|
||||
public var label: String? = nil
|
||||
public var label: String?
|
||||
|
||||
/// A boolean value indicating whether SQLite 3.29+ interprets
|
||||
/// double-quoted strings as string literals when they does not match any
|
||||
@@ -329,7 +332,7 @@ public struct Configuration: Sendable {
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
|
||||
/// If nil, GRDB picks a default one.
|
||||
var readonlyBusyMode: Database.BusyMode? = nil
|
||||
var readonlyBusyMode: Database.BusyMode?
|
||||
|
||||
/// The maximum number of concurrent reader connections.
|
||||
///
|
||||
@@ -387,7 +390,7 @@ public struct Configuration: Sendable {
|
||||
/// ``qos`` property.
|
||||
///
|
||||
/// The default is nil.
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
public var targetQueue: DispatchQueue?
|
||||
|
||||
/// The target dispatch queue for write database accesses.
|
||||
///
|
||||
@@ -395,7 +398,7 @@ public struct Configuration: Sendable {
|
||||
/// by ``targetQueue``.
|
||||
///
|
||||
/// The default is nil.
|
||||
public var writeTargetQueue: DispatchQueue? = nil
|
||||
public var writeTargetQueue: DispatchQueue?
|
||||
|
||||
#if os(iOS)
|
||||
/// A boolean value indicating whether the database connection releases
|
||||
@@ -421,6 +424,22 @@ public struct Configuration: Sendable {
|
||||
/// reveals that a lot of time is spent opening new SQLite connections.
|
||||
public var persistentReadOnlyConnections = false
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// A custom schema source.
|
||||
///
|
||||
/// The use case for a custom schema source is enabling GRDB features that
|
||||
/// would not work with the built-in schema introspection that is provided
|
||||
/// by SQLite. For example, a custom schema source can help record types
|
||||
/// that read or write in a database view.
|
||||
///
|
||||
/// The schema source is automatically disabled during database
|
||||
/// migrations performed by ``DatabaseMigrator``: those access the raw
|
||||
/// SQLite schema, unaltered. If a migration needs a schema source,
|
||||
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
|
||||
/// the body of a migration.
|
||||
public var schemaSource: (any DatabaseSchemaSource)?
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration.
|
||||
|
||||
+401
-229
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -387,7 +390,7 @@ extension SQLStatementCursor: Cursor {
|
||||
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
|
||||
|
||||
// Compile next statement
|
||||
var statementEnd: UnsafePointer<CChar>? = nil
|
||||
var statementEnd: UnsafePointer<CChar>?
|
||||
let statement = try Statement(
|
||||
database: database,
|
||||
statementStart: baseAddress + offset,
|
||||
|
||||
+61
-11
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -113,6 +116,11 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``resumeNotification``
|
||||
/// - ``suspendNotification``
|
||||
///
|
||||
/// ### The Schema Source
|
||||
///
|
||||
/// - ``schemaSource``
|
||||
/// - ``withSchemaSource(_:execute:)``
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``add(tokenizer:)``
|
||||
@@ -169,7 +177,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// connection has been opened is an SQLite misuse, and has no effect.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
|
||||
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
|
||||
nonisolated(unsafe) public static var logError: LogErrorFunction? {
|
||||
didSet {
|
||||
if logError != nil {
|
||||
_registerErrorLogCallback { (_, code, message) in
|
||||
@@ -187,6 +195,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// The database configuration.
|
||||
public let configuration: Configuration
|
||||
|
||||
/// The current schema source.
|
||||
///
|
||||
/// By default, it is the ``Configuration/schemaSource``
|
||||
/// of ``configuration``. To modify the schema source,
|
||||
/// use ``withSchemaSource(_:execute:)``.
|
||||
///
|
||||
/// The schema source is automatically disabled (nil) during database
|
||||
/// migrations performed by ``DatabaseMigrator``: those access the raw
|
||||
/// SQLite schema, unaltered. If a migration needs a schema source,
|
||||
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
|
||||
/// the body of a migration.
|
||||
public internal(set) var schemaSource: (any DatabaseSchemaSource)?
|
||||
|
||||
/// A description of this database connection.
|
||||
///
|
||||
/// The returned string is based on the ``Configuration/label``
|
||||
@@ -442,6 +463,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.description = description
|
||||
self.configuration = configuration
|
||||
self.schemaSource = configuration.schemaSource
|
||||
self.path = path
|
||||
|
||||
// We do not report read-only transactions to transaction observers, so
|
||||
@@ -459,7 +481,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
private static func openConnection(path: String, flags: CInt) throws -> SQLiteConnection {
|
||||
// See <https://www.sqlite.org/c3ref/open.html>
|
||||
var sqliteConnection: SQLiteConnection? = nil
|
||||
var sqliteConnection: SQLiteConnection?
|
||||
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// https://www.sqlite.org/c3ref/open.html
|
||||
@@ -806,7 +828,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
collationPointer,
|
||||
{ (collationPointer, length1, buffer1, length2, buffer2) in
|
||||
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
|
||||
return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue)
|
||||
return collation.xCompare(length1, buffer1.unsafelyUnwrapped, length2, buffer2.unsafelyUnwrapped)
|
||||
}, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
@@ -1286,7 +1308,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so
|
||||
// that we don't create an infinite loop in checkForSuspensionViolation(from:)
|
||||
var statement: SQLiteStatement? = nil
|
||||
var statement: SQLiteStatement?
|
||||
let sql = "PRAGMA journal_mode"
|
||||
sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
|
||||
defer { sqlite3_finalize(statement) }
|
||||
@@ -1483,7 +1505,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: Error?
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -1626,7 +1648,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: Error?
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -1744,7 +1766,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
if isInsideTransaction {
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
}
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
|
||||
assert(!isInsideTransaction)
|
||||
}
|
||||
|
||||
/// Commits a database transaction.
|
||||
@@ -1999,6 +2021,34 @@ extension Database {
|
||||
}
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
/// Returns the count of changes executed by one statement execution.
|
||||
func countChanges<T>(_ count: inout Int, forTable tableName: String, updates: () throws -> T) throws -> T {
|
||||
// Database.changesCount calls sqlite3_changes(), whose documentation says:
|
||||
//
|
||||
// > https://sqlite.org/c3ref/changes.html
|
||||
// > Changes to a view that are intercepted by INSTEAD OF triggers are not counted.
|
||||
//
|
||||
// We want to support INSTEAD OF triggers, so we prefer to use
|
||||
// sqlite3_total_changes() for views.
|
||||
//
|
||||
// At the same time, FTS5 has sqlite3_total_changes() report changes
|
||||
// even when database is not changed (https://github.com/groue/GRDB.swift/issues/1820)
|
||||
//
|
||||
// Well, let's do our best:
|
||||
if try viewExists(tableName) {
|
||||
let prevCount = totalChangesCount
|
||||
let result = try updates()
|
||||
count = totalChangesCount - prevCount
|
||||
return result
|
||||
} else {
|
||||
let result = try updates()
|
||||
count = changesCount
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database-Related Types
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -53,12 +56,21 @@ public final class DatabaseCollation: Identifiable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xCompare` parameter of sqlite3_create_collation_v2
|
||||
/// <https://www.sqlite.org/c3ref/create_collation.html>
|
||||
typealias XCompare = @Sendable (
|
||||
_ length1: CInt,
|
||||
_ buffer1: UnsafeRawPointer,
|
||||
_ length2: CInt,
|
||||
_ buffer2: UnsafeRawPointer
|
||||
) -> CInt
|
||||
|
||||
/// The identifier of the collation.
|
||||
public var id: ID { ID(name: name) }
|
||||
|
||||
/// The name of the collation.
|
||||
public let name: String
|
||||
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
|
||||
let xCompare: XCompare
|
||||
|
||||
/// Creates a collation.
|
||||
///
|
||||
@@ -75,21 +87,16 @@ public final class DatabaseCollation: Identifiable, Sendable {
|
||||
/// - parameters:
|
||||
/// - name: The collation name.
|
||||
/// - function: A function that compares two strings.
|
||||
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
|
||||
public convenience init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
|
||||
self.init(name, xCompare: { (length1, buffer1, length2, buffer2) in
|
||||
let string1 = String(decoding: UnsafeRawBufferPointer(start: buffer1, count: Int(length1)), as: UTF8.self)
|
||||
let string2 = String(decoding: UnsafeRawBufferPointer(start: buffer2, count: Int(length2)), as: UTF8.self)
|
||||
return CInt(function(string1, string2).rawValue)
|
||||
})
|
||||
}
|
||||
|
||||
init(_ name: String, xCompare: @escaping XCompare) {
|
||||
self.name = name
|
||||
self.function = { (length1, buffer1, length2, buffer2) in
|
||||
// Buffers are not C strings: they do not end with \0.
|
||||
let string1 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
|
||||
length: Int(length1),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
let string2 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
|
||||
length: Int(length2),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
return function(string1, string2)
|
||||
}
|
||||
self.xCompare = xCompare
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A custom SQL function or aggregate.
|
||||
@@ -82,20 +85,43 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// such as `Int`, `String`, `Date`, etc. The array is guaranteed to
|
||||
/// have exactly `argumentCount` elements, provided `argumentCount` is
|
||||
/// not nil.
|
||||
public init(
|
||||
public convenience init(
|
||||
_ name: String,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.init(name, argumentCount: argumentCount, pure: pure) { (argc, argv, context) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv[index]!)
|
||||
}
|
||||
let result = try function(arguments)
|
||||
switch result?.databaseValue.storage ?? .null {
|
||||
case .null:
|
||||
sqlite3_result_null(context)
|
||||
case .int64(let int64):
|
||||
sqlite3_result_int64(context, int64)
|
||||
case .double(let double):
|
||||
sqlite3_result_double(context, double)
|
||||
case .string(let string):
|
||||
sqlite3_result_text(context, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(context, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init(
|
||||
_ name: String,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
xFunc: @escaping XFunc)
|
||||
{
|
||||
self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.isPure = pure
|
||||
self.kind = .function { (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
}
|
||||
return try function(arguments)
|
||||
}
|
||||
self.kind = .function(xFunc)
|
||||
}
|
||||
|
||||
/// Creates an SQL aggregate function.
|
||||
@@ -256,11 +282,10 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class FunctionDefinition {
|
||||
let compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
|
||||
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
|
||||
throws -> (any DatabaseValueConvertible)?)
|
||||
let xFunc: XFunc
|
||||
init(xFunc: @escaping XFunc)
|
||||
{
|
||||
self.compute = compute
|
||||
self.xFunc = xFunc
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,11 +308,19 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
typealias XFunc = @Sendable (
|
||||
_ argc: CInt,
|
||||
_ argv: UnsafeMutablePointer<OpaquePointer?>,
|
||||
_ context: OpaquePointer?
|
||||
) throws -> Void
|
||||
|
||||
/// A function kind: an "SQL function" or an "aggregate".
|
||||
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private enum Kind: Sendable {
|
||||
/// A regular function: SELECT f(1)
|
||||
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
|
||||
case function(XFunc)
|
||||
|
||||
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
|
||||
case aggregate(@Sendable () -> any DatabaseAggregate)
|
||||
@@ -296,8 +329,8 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var definition: AnyObject {
|
||||
switch self {
|
||||
case .function(let compute):
|
||||
return FunctionDefinition(compute: compute)
|
||||
case .function(let xFunc):
|
||||
return FunctionDefinition(xFunc: xFunc)
|
||||
case .aggregate(let makeAggregate):
|
||||
return AggregateDefinition(makeAggregate: makeAggregate)
|
||||
}
|
||||
@@ -312,9 +345,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
.fromOpaque(sqlite3_user_data(sqliteContext))
|
||||
.takeUnretainedValue()
|
||||
do {
|
||||
try DatabaseFunction.report(
|
||||
result: definition.compute(argc, argv),
|
||||
in: sqliteContext)
|
||||
try definition.xFunc(argc, argv.unsafelyUnwrapped, sqliteContext)
|
||||
} catch {
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
@@ -464,7 +495,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
/// ```
|
||||
public protocol DatabaseAggregate {
|
||||
public protocol DatabaseAggregate: GRDBSendableMetatype {
|
||||
/// Creates an aggregate.
|
||||
///
|
||||
/// A new instance is created for each aggregation.
|
||||
|
||||
@@ -361,8 +361,13 @@ extension DatabasePool: DatabaseReader {
|
||||
return try await readerPool.get { reader in
|
||||
try await reader.execute { db in
|
||||
defer {
|
||||
// Ignore commit error, but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
}
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
@@ -387,8 +392,13 @@ extension DatabasePool: DatabaseReader {
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
// Ignore commit error, but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
@@ -551,8 +561,13 @@ extension DatabasePool: DatabaseReader {
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
reader.async { db in
|
||||
defer {
|
||||
// Ignore commit error, but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
@@ -669,7 +684,7 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
// MARK: - WAL Snapshot Transactions
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
/// Returns a long-lived WAL snapshot transaction on a reader connection.
|
||||
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
|
||||
guard let readerPool else {
|
||||
@@ -803,6 +818,7 @@ extension DatabasePool: DatabaseWriter {
|
||||
try Task.checkCancellation()
|
||||
return try writer.sync { db in
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
}
|
||||
cancelMutex.store(db.cancel)
|
||||
@@ -934,7 +950,7 @@ extension DatabasePool {
|
||||
purpose: "snapshot.\(databaseSnapshotCountMutex.increment())")
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
/// Creates a database snapshot that allows concurrent accesses to an
|
||||
/// unchanging database content, as it exists at the moment the snapshot
|
||||
/// is created.
|
||||
|
||||
@@ -248,8 +248,13 @@ extension DatabaseQueue: DatabaseReader {
|
||||
) {
|
||||
writer.async { db in
|
||||
defer {
|
||||
// Ignore commit error (we can not notify it), but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
@@ -297,8 +302,13 @@ extension DatabaseQueue: DatabaseReader {
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
|
||||
defer {
|
||||
// Ignore commit error (we can not notify it), but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
@@ -256,8 +256,8 @@ extension DatabaseRegion {
|
||||
}
|
||||
} else {
|
||||
// full database
|
||||
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
|
||||
let schema = try db.schema(schemaIdentifier)
|
||||
return try db.fetchSchemaIdentifiers().flatMap { schemaID in
|
||||
let schema = try db.schema(schemaID)
|
||||
return try schema.objects
|
||||
.filter { $0.type == .table }
|
||||
.flatMap { table in
|
||||
|
||||
@@ -201,7 +201,11 @@ extension DatabasePublishers {
|
||||
self.observation = observation
|
||||
}
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
public func receive<S>(subscriber: S)
|
||||
where S: Subscriber & GRDBSendableMetatype,
|
||||
Failure == S.Failure,
|
||||
Output == S.Input
|
||||
{
|
||||
let subscription = DatabaseRegionSubscription(
|
||||
writer: writer,
|
||||
observation: observation,
|
||||
@@ -212,7 +216,7 @@ extension DatabasePublishers {
|
||||
|
||||
private class DatabaseRegionSubscription<Downstream>:
|
||||
Subscription, @unchecked Sendable
|
||||
where Downstream: Subscriber,
|
||||
where Downstream: Subscriber & GRDBSendableMetatype,
|
||||
Downstream.Failure == Error,
|
||||
Downstream.Input == Database
|
||||
{
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
/// A type that provides information about the database schema.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// The use case for a custom schema source is to enable GRDB features that
|
||||
/// would not work with the built-in schema introspection provided
|
||||
/// by SQLite.
|
||||
///
|
||||
/// For example, if your database schema contains a view and you wish to use
|
||||
/// GRDB features that need a primary key, such as the
|
||||
/// ``FetchableRecord/find(_:id:)`` record method, or the persistence
|
||||
/// methods of the ``PersistableRecord`` protocol, then use a schema source
|
||||
/// that implements the ``columnsForPrimaryKey(_:inView:)`` method. See
|
||||
/// <doc:ViewRecords> for a detailed guide about such views.
|
||||
///
|
||||
/// ## Enabling a Schema Source
|
||||
///
|
||||
/// To enable a schema source in a database connection, configure its
|
||||
/// ``Configuration/schemaSource``:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct MySchemaSource: DatabaseSchemaSource { ... }
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = MySchemaSource()
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
|
||||
/// ```
|
||||
///
|
||||
/// ## Schema Sources and Migrations
|
||||
///
|
||||
/// By default, schema sources are disabled during <doc:Migrations>. In
|
||||
/// migrations that need a schema source, you can use
|
||||
/// ``Database/withSchemaSource(_:execute:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// migrator.registerMigration("My migration") { db in
|
||||
/// // No schema source is enabled at this point.
|
||||
/// try db.withSchemaSource(MySchemaSource()) {
|
||||
/// // Here the provided schema source is in effect.
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Take care that **a good migration is a migration that is never
|
||||
/// modified once it has shipped**: check
|
||||
/// <doc:Migrations#Good-Practices-for-Defining-Migrations>.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Customizing the Database Schema
|
||||
///
|
||||
/// - ``columnsForPrimaryKey(_:inView:)``
|
||||
///
|
||||
/// ### Chaining Schema Sources
|
||||
///
|
||||
/// - ``then(_:)``
|
||||
public protocol DatabaseSchemaSource: Sendable {
|
||||
/// Returns the names of the columns for the primary key in the
|
||||
/// provided database view.
|
||||
///
|
||||
/// Return `nil` if no customization should happen. Return an empty
|
||||
/// array to specify that the view has no primary key. The default
|
||||
/// implementation returns `nil`.
|
||||
///
|
||||
/// In your implementation, make sure that the returned columns define
|
||||
/// a genuine **primary key**:
|
||||
///
|
||||
/// - All columns exist in the provided view.
|
||||
/// - The set of columns reliably identifies and distinguishes between
|
||||
/// each individual row in the view.
|
||||
/// - No column contains NULL values.
|
||||
///
|
||||
/// It is a programmer error with undefined consequences to miss
|
||||
/// those requirements.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A schema source that specifies that all views are identified by
|
||||
/// // their "id" column:
|
||||
/// struct MySchemaSource: DatabaseSchemaSource {
|
||||
/// func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) {
|
||||
/// ["id"]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // A database connection configured with the schema source.
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = MySchemaSource()
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
|
||||
///
|
||||
/// // A record type that feeds from a view.
|
||||
/// struct Player: Decodable, Identifiable, FetchableRecord {
|
||||
/// static let databaseTableName = "playerView"
|
||||
/// var id: String
|
||||
/// var name: String
|
||||
/// }
|
||||
///
|
||||
/// // Thanks to the schema source, we can fetch players by id:
|
||||
/// let player = try dbQueue.read { db in
|
||||
/// try Player.find(db, id: "alice")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Schema Sources in Libraries
|
||||
///
|
||||
/// When you are developing a schema source for a library, some extra
|
||||
/// care is necessary whenever the database file is owned by the users
|
||||
/// of your library. Your users may define views for their own purposes,
|
||||
/// and your library knows nothing about the eventual primary key of
|
||||
/// those views.
|
||||
///
|
||||
/// In this case, make your schema source `public`, and have this method
|
||||
/// return `nil` for those unknown views. If needed, use the `db`
|
||||
/// argument and query the database schema with
|
||||
/// <doc:DatabaseSchemaIntrospection> methods.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A well-behaved schema source defined by a library is public
|
||||
/// // and returns nil for unknown views.
|
||||
/// public struct MyLibrarySchemaSource: DatabaseSchemaSource {
|
||||
/// public func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) {
|
||||
/// if view.name == "playerView" {
|
||||
/// // This is a view managed by my library:
|
||||
/// return ["id"]
|
||||
/// } else if try db.tableExists(view.name + "MyLibrary") {
|
||||
/// // This is a view managed by my library:
|
||||
/// return ["uuid"]
|
||||
/// } else {
|
||||
/// // Not a view managed by my library:
|
||||
/// // don't mess with user's schema
|
||||
/// return nil
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// With such a setup, your user will be able to deal with their
|
||||
/// own views, by chaining your schema source with other ones
|
||||
/// (see ``DatabaseSchemaSource/then(_:)``):
|
||||
///
|
||||
/// ```swift
|
||||
/// // Application code
|
||||
/// import MyLibrary
|
||||
/// import GRDB
|
||||
///
|
||||
/// let myLibrarySchemaSource = MyLibrarySchemaSource()
|
||||
/// let customSchemaSource = TheirCustomSchemaSource()
|
||||
/// let schemaSource = myLibrarySchemaSource.then(customSchemaSource)
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = schemaSource
|
||||
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - db: A database connection.
|
||||
/// - view: The identifier of a database view.
|
||||
func columnsForPrimaryKey(
|
||||
_ db: Database,
|
||||
inView view: DatabaseObjectID
|
||||
) throws -> [String]?
|
||||
}
|
||||
|
||||
extension DatabaseSchemaSource {
|
||||
public func columnsForPrimaryKey(
|
||||
_ db: Database,
|
||||
inView view: DatabaseObjectID
|
||||
) throws -> [String]? {
|
||||
nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Combined2SchemaSource
|
||||
|
||||
extension DatabaseSchemaSource {
|
||||
/// Returns a schema source that queries `other` when this source does
|
||||
/// not perform a customization.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let schemaSource1 = SomeSchemaSource()
|
||||
/// let schemaSource2 = AnotherSchemaSource()
|
||||
/// let schemaSource = schemaSource1.then(schemaSource2)
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = schemaSource
|
||||
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
|
||||
/// ```
|
||||
public func then(_ other: some DatabaseSchemaSource) -> some DatabaseSchemaSource {
|
||||
Chained2SchemaSource(first: self, second: other)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: move to parameter packs eventually. Parameter packs in generic types
|
||||
// are only available in macOS 14.0.0 or newer.
|
||||
// This schema source is designed to tame bad citizens that customize tables
|
||||
// and views they do not own (such as insufficienly robust schema sources
|
||||
// exposed by external libraries). We should NEVER MERGE the results of the
|
||||
// schema sources.
|
||||
struct Chained2SchemaSource<Source1, Source2>: DatabaseSchemaSource
|
||||
where Source1: DatabaseSchemaSource,
|
||||
Source2: DatabaseSchemaSource
|
||||
{
|
||||
var first: Source1
|
||||
var second: Source2
|
||||
|
||||
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
|
||||
if let result = try first.columnsForPrimaryKey(db, inView: view) { return result }
|
||||
if let result = try second.columnsForPrimaryKey(db, inView: view) { return result }
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -113,8 +113,13 @@ public final class DatabaseSnapshot {
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
reader.reentrantSync { db in
|
||||
// Ignore commit error (we can not notify it), but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A database connection that allows concurrent accesses to an unchanging
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -552,7 +552,7 @@ extension DatabaseWriter {
|
||||
// This method is declared on DatabaseWriter instead of DatabaseReader,
|
||||
// so that it is not available on DatabaseSnaphot. VACUUM INTO is not
|
||||
// available inside the transaction that is kept open by DatabaseSnaphot.
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
@@ -665,7 +665,7 @@ extension DatabaseWriter {
|
||||
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
#if os(Linux)
|
||||
@preconcurrency import Dispatch
|
||||
#else
|
||||
import Dispatch
|
||||
#endif
|
||||
|
||||
/// An actor that runs in a DispatchQueue.
|
||||
///
|
||||
@@ -43,3 +47,7 @@ private final class DispatchQueueExecutor: SerialExecutor {
|
||||
dispatchPrecondition(condition: .onQueue(queue))
|
||||
}
|
||||
}
|
||||
|
||||
#if os(Linux)
|
||||
extension DispatchQueueExecutor: @unchecked Sendable {}
|
||||
#endif
|
||||
+7
-4
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A key that is used to decode a value in a row
|
||||
|
||||
@@ -256,6 +256,7 @@ final class SerializedDatabase {
|
||||
return try await withTaskCancellationHandler {
|
||||
try await actor.execute {
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
preconditionNoUnsafeTransactionLeft(db)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -141,7 +144,7 @@ public final class Statement {
|
||||
let authorizer = database.authorizer
|
||||
authorizer.reset()
|
||||
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
var sqliteStatement: SQLiteStatement?
|
||||
let code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, prepFlags,
|
||||
&sqliteStatement, statementEnd)
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
#if canImport(string_h)
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A type that can decode itself from the low-level C interface to
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
#if canImport(CoreGraphics)
|
||||
import CoreGraphics
|
||||
#elseif !canImport(Darwin)
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
/// CGFloat adopts DatabaseValueConvertible
|
||||
extension CGFloat: DatabaseValueConvertible {
|
||||
@@ -15,4 +18,3 @@ extension CGFloat: DatabaseValueConvertible {
|
||||
return CGFloat(double)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,15 +1,17 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSDate is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension NSDate: DatabaseValueConvertible {
|
||||
@@ -38,7 +40,6 @@ extension NSDate: DatabaseValueConvertible {
|
||||
return cast(date)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
#if !os(Linux)
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -65,4 +67,3 @@ extension Decimal: StatementColumnConvertible {
|
||||
|
||||
@usableFromInline
|
||||
let _posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
@@ -1,4 +1,3 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
@@ -24,4 +23,3 @@ extension NSData: DatabaseValueConvertible {
|
||||
return cast(data)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,4 +1,4 @@
|
||||
#if !os(Linux) && !os(Windows)
|
||||
#if !os(Windows)
|
||||
import Foundation
|
||||
|
||||
private let integerRoundingBehavior = NSDecimalNumberHandler(
|
||||
@@ -81,10 +81,18 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64) where self is NSDecimalNumber.Type:
|
||||
let number = NSDecimalNumber(value: int64)
|
||||
return number as? Self
|
||||
case .int64(let int64):
|
||||
return self.init(value: int64)
|
||||
let number = NSNumber(value: int64)
|
||||
return number as? Self
|
||||
case .double(let double) where self is NSDecimalNumber.Type:
|
||||
let number = NSDecimalNumber(value: double)
|
||||
return number as? Self
|
||||
case .double(let double):
|
||||
return self.init(value: double)
|
||||
let number = NSNumber(value: double)
|
||||
return number as? Self
|
||||
case let .string(string):
|
||||
// Must match Decimal.fromDatabaseValue(_:)
|
||||
guard let decimal = Decimal(string: string, locale: posixLocale) else { return nil }
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSString adopts DatabaseValueConvertible
|
||||
@@ -24,4 +23,3 @@ extension NSString: DatabaseValueConvertible {
|
||||
return self.init(string: string)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -1,12 +1,16 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux) && !os(Windows)
|
||||
#if !os(Windows)
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
extension NSURL: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a TEXT database value containing the absolute URL.
|
||||
public var databaseValue: DatabaseValue {
|
||||
absoluteString?.databaseValue ?? .null
|
||||
#if !canImport(Darwin)
|
||||
absoluteString.databaseValue
|
||||
#else
|
||||
absoluteString?.databaseValue ?? .null
|
||||
#endif
|
||||
}
|
||||
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
|
||||
@@ -1,15 +1,18 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux) && !os(Windows)
|
||||
#if !os(Windows)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
@@ -33,10 +36,17 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data) where data.count == 16:
|
||||
return data.withUnsafeBytes {
|
||||
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
|
||||
#if canImport(Darwin)
|
||||
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
|
||||
#else
|
||||
guard let uuidBytes = $0.bindMemory(to: UInt8.self).baseAddress else {
|
||||
return nil as Self?
|
||||
}
|
||||
return NSUUID(uuidBytes: uuidBytes) as? Self
|
||||
#endif
|
||||
}
|
||||
case .string(let string):
|
||||
return self.init(uuidString: string)
|
||||
return NSUUID(uuidString: string) as? Self
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
@@ -88,8 +98,8 @@ extension UUID: StatementColumnConvertible {
|
||||
self.init(uuid: uuid.uuid)
|
||||
case SQLITE_BLOB:
|
||||
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index) else
|
||||
{
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
extension Optional: StatementBinding where Wrapped: StatementBinding {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
// MARK: - Value Types
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
@@ -1494,7 +1497,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
|
||||
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
|
||||
-> DatabaseValue?
|
||||
{
|
||||
var value: SQLiteValue? = nil
|
||||
var value: SQLiteValue?
|
||||
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
|
||||
if let value {
|
||||
return DatabaseValue(sqliteValue: value)
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// An instance of WALSnapshot records the state of a WAL mode database for some
|
||||
@@ -16,18 +19,6 @@ import SQLite3
|
||||
/// actual observation. This class has no other purpose, and is not intended to
|
||||
/// become public.
|
||||
///
|
||||
/// It does not work with SQLCipher, because SQLCipher does not support
|
||||
/// `SQLITE_ENABLE_SNAPSHOT` correctly: we have linker errors.
|
||||
/// See <https://github.com/ericsink/SQLitePCL.raw/issues/452>.
|
||||
///
|
||||
/// With custom SQLite builds, it only works if `SQLITE_ENABLE_SNAPSHOT`
|
||||
/// is defined.
|
||||
///
|
||||
/// With system SQLite, it works because the SDK exposes the C apis and
|
||||
/// since XCode 14.
|
||||
///
|
||||
/// 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.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
/// A long-live read-only WAL transaction.
|
||||
///
|
||||
/// `WALSnapshotTransaction` **takes ownership** of its reader
|
||||
@@ -15,7 +15,13 @@ final class WALSnapshotTransaction: @unchecked Sendable {
|
||||
// WALSnapshotTransaction may be deinitialized in the dispatch
|
||||
// queue of its reader: allow reentrancy.
|
||||
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
|
||||
try? db.commit()
|
||||
// Commit or rollback, but try hard to leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
return db.isInsideTransaction
|
||||
}
|
||||
release(isInsideTransaction)
|
||||
|
||||
@@ -29,6 +29,8 @@ Get information about schema objects such as tables, columns, indexes, foreign k
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseSchemaID``
|
||||
- ``DatabaseObjectID``
|
||||
- ``ColumnInfo``
|
||||
- ``ForeignKeyInfo``
|
||||
- ``IndexInfo``
|
||||
|
||||
@@ -96,6 +96,7 @@ do {
|
||||
- ``persistentReadOnlyConnections``
|
||||
- ``prepareDatabase(_:)``
|
||||
- ``publicStatementArguments``
|
||||
- ``schemaSource``
|
||||
- ``transactionClock``
|
||||
- ``TransactionClock``
|
||||
|
||||
@@ -106,3 +107,7 @@ do {
|
||||
- ``writeQoS``
|
||||
- ``targetQueue``
|
||||
- ``writeTargetQueue``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseSchemaSource``
|
||||
@@ -94,6 +94,7 @@ let players: [Player] = try dbQueue.read { db in
|
||||
- <doc:RecordRecommendedPractices>
|
||||
- <doc:RecordTimestamps>
|
||||
- <doc:SingleRowTables>
|
||||
- <doc:ViewRecords>
|
||||
|
||||
### Application Tools
|
||||
|
||||
|
||||
@@ -229,5 +229,11 @@ Task {
|
||||
}
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``GRDBSendableMetatype``
|
||||
|
||||
[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
|
||||
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide/
|
||||
@@ -0,0 +1,383 @@
|
||||
# View Records
|
||||
|
||||
Define record types that target database views.
|
||||
|
||||
## Overview
|
||||
|
||||
A record type targets a [database view] as soon as its ``TableRecord/databaseTableName-3tcw2`` is the name of a view.
|
||||
|
||||
With such a record, some GRDB features will work out of the box, and some will throw errors without extra configuration:
|
||||
|
||||
```swift
|
||||
// OK: Works out of the box
|
||||
let captains = try Captain.fetchAll(db)
|
||||
let captainCount = try Captain.fetchCount(db)
|
||||
|
||||
// KO: Requires extra configuration
|
||||
// SQLite error 1: database view captain has no primary key
|
||||
var bob = try Captain.find(db, id: "bob")
|
||||
bob.name = "Bobby"
|
||||
// SQLite error 1: cannot modify captain because it is a view
|
||||
try bob.update(db)
|
||||
```
|
||||
|
||||
This article explains how to solve those errors:
|
||||
|
||||
- How to provide a primary key to a view.
|
||||
- How to define INSTEAD OF triggers that insert, update, and delete through a database view.
|
||||
|
||||
> important: GRDB is impacted by some SQLite limitations regarding INSTEAD OF triggers:
|
||||
>
|
||||
> - **Auto-incremented primary keys are not supported.** To be precise, SQLite won't expose the rowid of rows inserted via an INSTEAD OF trigger, so GRDB won't know the id of newly inserted rows. This has various nefarious consequences—see for example the important notice in the ``MutablePersistableRecord/didInsert(_:)`` callback. For more information, check this [SQLite forum thread](https://sqlite.org/forum/forumpost/707e7ed932).
|
||||
> - **INSTEAD OF triggers and the RETURNING clause do not play well together.** Those are SQLite bugs. All GRDB record methods with `andFetch` in their name may return unexpected or wrong results, depending on the SQLite version. For example, the SQLite version that ships with iOS 18 has bugs, and even more in iOS 17. If you intend to use the `RETURNING` clause, it is recommended that you write tests and run them in various target operation systems.
|
||||
|
||||
## Preliminary Setup
|
||||
|
||||
To support this documentation, we need a database that contains a view. The sample code below uses <doc:Migrations> and <doc:DatabaseSchemaModifications> methods.
|
||||
|
||||
The database schema contains teams and players. Some players are the captain of their team. We enforce in the database schema that a given team can't have multiple captains:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("Teams and players") { db in
|
||||
try db.create(table: "team") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
t.belongsTo("team", onDelete: .setNull)
|
||||
t.column("isCaptain", .boolean).notNull()
|
||||
}
|
||||
|
||||
// One unique captain per team
|
||||
try db.create(
|
||||
indexOn: "player", columns: ["teamId"],
|
||||
options: .unique,
|
||||
condition: Column("isCaptain"))
|
||||
}
|
||||
```
|
||||
|
||||
We define record types for the `team` and `player` tables, as described in <doc:RecordRecommendedPractices>:
|
||||
|
||||
```swift
|
||||
struct Team: Codable, Identifiable, FetchableRecord, PersistableRecord {
|
||||
var id: String
|
||||
var name: String
|
||||
}
|
||||
|
||||
struct Player: Codable, Identifiable, FetchableRecord, PersistableRecord {
|
||||
var id: String
|
||||
var name: String
|
||||
var teamId: String?
|
||||
var isCaptain: Bool
|
||||
}
|
||||
```
|
||||
|
||||
Let's define a view and a record type for captains. At this point, both the view and the record are read-only:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Read-only captains") { db in
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW captain AS
|
||||
SELECT id, name, teamId
|
||||
FROM player
|
||||
WHERE isCaptain AND teamId IS NOT NULL;
|
||||
""")
|
||||
}
|
||||
|
||||
struct Captain: Decodable, Identifiable, FetchableRecord {
|
||||
var id: String
|
||||
var name: String
|
||||
var teamId: String
|
||||
}
|
||||
```
|
||||
|
||||
✅ From now on, we can use the `Captain` record:
|
||||
|
||||
```swift
|
||||
let dbQueue = try DatabaseQueue()
|
||||
try migrator.migrate(dbQueue)
|
||||
try dbQueue.write { db in
|
||||
try Team(id: "red", name: "Red").insert(db)
|
||||
try Team(id: "blue", name: "Blue").insert(db)
|
||||
try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db)
|
||||
try Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true).insert(db)
|
||||
try Player(id: "craig", name: "Craig", teamId: "blue", isCaptain: false).insert(db)
|
||||
|
||||
let captains = try Captain.fetchAll(db)
|
||||
// Prints:
|
||||
// Captain(id: "alice", name: "Alice", teamId: "red")
|
||||
// Captain(id: "bob", name: "Bob", teamId: "blue")
|
||||
print(captains)
|
||||
}
|
||||
```
|
||||
|
||||
## Specifying the primary key of a view
|
||||
|
||||
SQLite views do not have any primary key, so GRDB cannot introspect the database schema and automatically find the eventual primary key.
|
||||
|
||||
To instruct GRDB about the primary key, define a **schema source**, a type that conforms to ``DatabaseSchemaSource``. In this sample code, the schema only contains the "captain" view, so our schema source does not need to be very complicated. Check the documentation of the protocol for more detailed instructions:
|
||||
|
||||
```swift
|
||||
struct GameSchemaSource: DatabaseSchemaSource {
|
||||
/// Returns the names of the columns for the primary key in the
|
||||
/// provided database view.
|
||||
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
|
||||
["id"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
We configure the database connection with this schema source:
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.schemaSource = GameSchemaSource()
|
||||
let dbQueue = try DatabaseQueue(configuration: config)
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
✅ We can now use the primary key of captains:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
// [Insert some teams and players...]
|
||||
let captains = try Captain.orderByPrimaryKey().fetchAll(db)
|
||||
let alice = try Captain.find(db, id: "alice")
|
||||
}
|
||||
```
|
||||
|
||||
## Associations between views
|
||||
|
||||
To define [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) between record types that target database views, the foreign key must be explicitly provided. We define the foreign key from `captain` to `team` with a column declared as recommended in <doc:RecordRecommendedPractices>:
|
||||
|
||||
```swift
|
||||
extension Captain {
|
||||
// Time to define some columns
|
||||
enum Columns {
|
||||
static let teamId = Column(CodingKeys.teamId)
|
||||
}
|
||||
|
||||
// The captain view has a foreign key to teams,
|
||||
// from the teamId column to the team primary key.
|
||||
// SQLite does not know about it, so we declare it explicitly:
|
||||
static let teamForeignKey = ForeignKey([Columns.teamId])
|
||||
|
||||
// A captain belongs to a team.
|
||||
static let team = belongsTo(Team.self, using: teamForeignKey)
|
||||
}
|
||||
|
||||
extension Team {
|
||||
// A team has a captain.
|
||||
static let captain = hasOne(Captain.self, using: Captain.teamForeignKey)
|
||||
}
|
||||
```
|
||||
|
||||
✅ We can now use those associations:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
// All teams with a captain
|
||||
let teamsWithCaptain: [Team] = try Team
|
||||
.joining(required: Team.captain)
|
||||
.fetchAll(db)
|
||||
|
||||
// All (captain, team) pairs
|
||||
struct CaptainWithTeam: Decodable, FetchableRecord {
|
||||
var captain: Captain
|
||||
var team: Team
|
||||
}
|
||||
let captainsWithTeam: [CaptainWithTeam] = try Captain
|
||||
.including(required: Captain.team)
|
||||
.asRequest(of: CaptainWithTeam.self)
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
## Inserting rows into a view
|
||||
|
||||
SQLite views are read-only unless we define an [INSTEAD OF trigger] that specifies which statements to run when we insert a row into a view.
|
||||
|
||||
INSTEAD OF triggers are very versatile, and applications can define the behavior that best fits their needs. In our sample code, inserting a captain will insert a player with the `isCaptain` flag set, and we'll also remove the `isCaptain` flag of the previous captain, if any:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Captain insert") { db in
|
||||
try db.execute(sql: """
|
||||
-- Insert trigger
|
||||
CREATE TRIGGER captain_insert
|
||||
INSTEAD OF INSERT ON captain
|
||||
BEGIN
|
||||
-- Remove previous captain
|
||||
UPDATE player SET isCaptain = 0
|
||||
WHERE teamId = NEW.teamId AND isCaptain;
|
||||
|
||||
-- Insert new captain
|
||||
INSERT INTO player(id, name, teamId, isCaptain)
|
||||
VALUES (NEW.id, NEW.name, NEW.teamId, 1);
|
||||
END;
|
||||
""")
|
||||
}
|
||||
|
||||
// Apply the new migration
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
Let's also give an `insert()` method to the Captain record, with the ``PersistableRecord`` protocol:
|
||||
|
||||
```swift
|
||||
extension Captain: Encodable, PersistableRecord { }
|
||||
```
|
||||
|
||||
- note: Remember that auto-incremented primary keys are not supported, as described at the beginning of this article. Our captain view is backed by the player table which has a string primary key, so we're fine.
|
||||
|
||||
✅ We can directly insert captains:
|
||||
|
||||
```swift
|
||||
try dbQueue.write {
|
||||
try Team(id: "green", name: "Green").insert(db)
|
||||
// Diane is the captain
|
||||
try Captain(id: "diane", name: "Diane", teamId: "green").insert(db)
|
||||
// Well, no: Eugene is the captain
|
||||
try Captain(id: "eugene", name: "Eugene", teamId: "green").insert(db)
|
||||
|
||||
// Prints:
|
||||
// team player captain
|
||||
// green|Green diane|Diane|green|0 eugene|Eugene|green
|
||||
// eugene|Eugene|green|1
|
||||
try db.dumpTables(["team", "player", "captain"])
|
||||
}
|
||||
```
|
||||
|
||||
## Updating rows in a view
|
||||
|
||||
Just like for inserts, an INSTEAD OF trigger can specify how to update rows in a view.
|
||||
|
||||
In our sample code, updating a captain will update the player with the same id, and remove the `isCaptain` flag from the previous captain of the team, if any:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Captain update") { db in
|
||||
try db.execute(sql: """
|
||||
-- Update trigger
|
||||
CREATE TRIGGER captain_update
|
||||
INSTEAD OF UPDATE ON captain
|
||||
BEGIN
|
||||
-- Remove previous captain
|
||||
UPDATE player SET isCaptain = 0
|
||||
WHERE teamId = NEW.teamId AND isCaptain AND id <> NEW.id;
|
||||
|
||||
-- Update captain
|
||||
UPDATE player SET name = NEW.name, teamId = NEW.teamId, isCaptain = 1
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
""")
|
||||
}
|
||||
|
||||
// Apply the new migration
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
✅ Let's update captains:
|
||||
|
||||
```swift
|
||||
try dbQueue.write {
|
||||
try Team(id: "red", name: "Red").insert(db)
|
||||
try Team(id: "blue", name: "Blue").insert(db)
|
||||
try Captain(id: "alice", name: "Alice", teamId: "red").insert(db)
|
||||
|
||||
// Bob is the Blue captain.
|
||||
var bob = Captain(id: "bob", name: "Bob", teamId: "blue")
|
||||
try bob.insert(db)
|
||||
|
||||
// Bob is now Bobby, the Red captain.
|
||||
// Alice is no longer the Red captain.
|
||||
try bob.updateChanges(db) {
|
||||
$0.name = "Bobby"
|
||||
$0.teamId = "red"
|
||||
}
|
||||
|
||||
// Prints:
|
||||
// team player captain
|
||||
// blue|Blue alice|Alice|red|0 bob|Bobby|red
|
||||
// red|Red bob|Bobby|red|1
|
||||
try db.dumpTables(["team", "player", "captain"])
|
||||
}
|
||||
```
|
||||
|
||||
## Deleting rows from a view
|
||||
|
||||
The last missing INSTEAD OF trigger deals with deletes:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Captain delete") { db in
|
||||
try db.execute(sql: """
|
||||
-- Delete trigger
|
||||
CREATE TRIGGER captain_delete
|
||||
INSTEAD OF DELETE ON captain
|
||||
BEGIN
|
||||
DELETE FROM player WHERE id = OLD.id;
|
||||
END;
|
||||
""")
|
||||
}
|
||||
|
||||
// Apply the new migration
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
✅ Let's delete some captains:
|
||||
|
||||
```swift
|
||||
try dbQueue.write {
|
||||
// Delete Alice
|
||||
try Captain.deleteOne(db, id: "alice")
|
||||
|
||||
// Delete Bob
|
||||
let bob = try Captain.find(db, id: "bob")
|
||||
try bob.delete(db)
|
||||
|
||||
// Delete all captains
|
||||
try Captain.deleteAll()
|
||||
}
|
||||
```
|
||||
|
||||
## Going further
|
||||
|
||||
To exercise the techniques described here, try to define record types for these other views:
|
||||
|
||||
- The `enrolledPlayer` view that only contains players that belong to a team:
|
||||
|
||||
```swift
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW enrolledPlayer AS
|
||||
SELECT id, name, teamId, isCaptain
|
||||
FROM player
|
||||
WHERE teamId IS NOT NULL;
|
||||
""")
|
||||
```
|
||||
|
||||
- The `teamWithCaptainId` view that contains a `captainId` column:
|
||||
|
||||
```swift
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW teamWithCaptainId AS
|
||||
SELECT team.id, team.name, player.id AS captainId
|
||||
FROM team
|
||||
JOIN player ON player.teamId = team.id AND player.isCaptain;
|
||||
""")
|
||||
```
|
||||
|
||||
- A refactored `captain` view whose primary key is the team id—this is valid, since the schema enforces that there's a single captain for each team:
|
||||
|
||||
```swift
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW captain AS
|
||||
SELECT teamId, name
|
||||
FROM player
|
||||
WHERE isCaptain AND teamId IS NOT NULL;
|
||||
""")
|
||||
```
|
||||
|
||||
[database view]: https://www.sqlite.org/lang_createview.html
|
||||
[INSTEAD OF trigger]: https://sqlite.org/lang_createtrigger.html#instead_of_triggers
|
||||
@@ -324,7 +324,7 @@ extension Database {
|
||||
}
|
||||
|
||||
private func isShadowTable(_ tableName: String) throws -> Bool {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
// Maybe SQLCipher is too old: check actual version
|
||||
if Database.sqliteLibVersionNumber >= 3037000 {
|
||||
guard let table = try table(tableName) else {
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A format that prints one line per database row, formatting values
|
||||
|
||||
+2
-2
@@ -40,11 +40,11 @@ public struct FTS3 {
|
||||
/// the `remove_diacritics=1` tokenizer argument.
|
||||
case removeLegacy
|
||||
|
||||
#if GRDBCUSTOMSQLITE
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Remove diacritics from Latin script characters. This option matches
|
||||
/// the `remove_diacritics=2` tokenizer argument.
|
||||
case remove
|
||||
#elseif !GRDBCIPHER
|
||||
#else
|
||||
/// Remove diacritics from Latin script characters. This option matches
|
||||
/// the `remove_diacritics=2` tokenizer argument.
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.27+
|
||||
|
||||
@@ -95,10 +95,10 @@ public struct FTS3TokenizerDescriptor: Sendable {
|
||||
break
|
||||
case .keep:
|
||||
arguments.append("remove_diacritics=0")
|
||||
#if GRDBCUSTOMSQLITE
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
case .remove:
|
||||
arguments.append("remove_diacritics=2")
|
||||
#elseif !GRDBCIPHER
|
||||
#else
|
||||
case .remove:
|
||||
arguments.append("remove_diacritics=2")
|
||||
#endif
|
||||
|
||||
+11
-8
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -60,12 +63,12 @@ public struct FTS5 {
|
||||
/// Remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=1" tokenizer argument.
|
||||
case removeLegacy
|
||||
#if GRDBCUSTOMSQLITE
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=2" tokenizer argument,
|
||||
/// available from SQLite 3.27.0
|
||||
case remove
|
||||
#elseif !GRDBCIPHER
|
||||
#else
|
||||
/// Remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=2" tokenizer argument,
|
||||
/// available from SQLite 3.27.0
|
||||
@@ -117,8 +120,8 @@ public struct FTS5 {
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/fts5.html#extending_fts5>
|
||||
public static func api(_ db: Database) -> UnsafePointer<fts5_api> {
|
||||
var statement: SQLiteStatement? = nil
|
||||
var api: UnsafePointer<fts5_api>? = nil
|
||||
var statement: SQLiteStatement?
|
||||
var api: UnsafePointer<fts5_api>?
|
||||
let type: StaticString = "fts5_api_ptr"
|
||||
|
||||
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
/// A type that implements a custom tokenizer for the ``FTS5`` full-text engine.
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -208,7 +211,7 @@ extension Database {
|
||||
|
||||
self.xTokenizer = xTokenizer
|
||||
|
||||
var tokenizerPointer: OpaquePointer? = nil
|
||||
var tokenizerPointer: OpaquePointer?
|
||||
let code: CInt
|
||||
if arguments.isEmpty {
|
||||
code = xCreate(contextPointer, nil, 0, &tokenizerPointer)
|
||||
|
||||
@@ -182,10 +182,10 @@ public struct FTS5TokenizerDescriptor: Sendable {
|
||||
break
|
||||
case .keep:
|
||||
components.append(contentsOf: ["remove_diacritics", "0"])
|
||||
#if GRDBCUSTOMSQLITE
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
case .remove:
|
||||
components.append(contentsOf: ["remove_diacritics", "2"])
|
||||
#elseif !GRDBCIPHER
|
||||
#else
|
||||
case .remove:
|
||||
components.append(contentsOf: ["remove_diacritics", "2"])
|
||||
#endif
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -154,7 +154,7 @@ extension SQLSpecificExpressible {
|
||||
}
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
extension SQLJSONExpressible {
|
||||
/// The `->>` SQL operator.
|
||||
///
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
// MARK: - JSON
|
||||
|
||||
extension Database {
|
||||
|
||||
@@ -18,6 +18,7 @@ import Foundation
|
||||
/// ### Registering Migrations
|
||||
///
|
||||
/// - ``registerMigration(_:foreignKeyChecks:migrate:)``
|
||||
/// - ``registerMigration(_:foreignKeyChecks:merging:migrate:)``
|
||||
/// - ``ForeignKeyChecks``
|
||||
///
|
||||
/// ### Configuring a DatabaseMigrator
|
||||
@@ -161,9 +162,8 @@ public struct DatabaseMigrator: Sendable {
|
||||
|
||||
/// Registers a migration.
|
||||
///
|
||||
/// The registered migration is appended to the list of migrations to run:
|
||||
/// it will execute after previously registered migrations, and before
|
||||
/// migrations that are registered later.
|
||||
/// The registered migration is appended to the list of migrations. It
|
||||
/// will execute after previously registered migrations.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -214,6 +214,107 @@ public struct DatabaseMigrator: Sendable {
|
||||
_ identifier: String,
|
||||
foreignKeyChecks: ForeignKeyChecks = .deferred,
|
||||
migrate: @escaping @Sendable (Database) throws -> Void)
|
||||
{
|
||||
registerMigration(identifier, foreignKeyChecks: foreignKeyChecks, merging: []) { db, ids in
|
||||
precondition(ids.isEmpty)
|
||||
try migrate(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers a merged migration.
|
||||
///
|
||||
/// Like migrations registered with ``registerMigration(_:foreignKeyChecks:migrate:)``,
|
||||
/// the merged migration is appended to the list of migrations. It
|
||||
/// will execute after previously registered migrations.
|
||||
///
|
||||
/// A merged migration merges and replaces a set of migrations defined
|
||||
/// in a previous version of the application. For example, to merge the
|
||||
/// migrations "v1", "v2" and "v3", redefine the "v3" migration so that
|
||||
/// it merges "v1" and "v2", as in the example below.
|
||||
///
|
||||
/// The second argument of the `migrate` closure is the subset of merged
|
||||
/// migrations that have already been applied when the merged
|
||||
/// migration runs.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Old code
|
||||
/// migrator.registerMigration("v1") { db in
|
||||
/// // Apply schema version 1
|
||||
/// }
|
||||
/// migrator.registerMigration("v2") { db in
|
||||
/// // Apply schema version 2
|
||||
/// }
|
||||
/// migrator.registerMigration("v3") { db in
|
||||
/// // Apply schema version 3
|
||||
/// }
|
||||
///
|
||||
/// // New code:
|
||||
/// // - Migrations v1 and v2 are deleted.
|
||||
/// // - Migration v3 is redefined and merges v1 and v2:
|
||||
/// migrator.registerMigration("v3", merging: ["v1", "v2"]) { db, appliedIDs in
|
||||
/// if !appliedIDs.contains("v1") {
|
||||
/// // Apply schema version 1
|
||||
/// }
|
||||
/// if !appliedIDs.contains("v2") {
|
||||
/// // Apply schema version 2
|
||||
/// }
|
||||
/// // Apply schema version 3
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// In the above sample code, the merged migration is named like the
|
||||
/// last one of the merged set. You can also give it a brand new name,
|
||||
/// as in the alternative below. Notice the different logic in the
|
||||
/// migration code.
|
||||
///
|
||||
/// **In all cases avoid naming the merged migration like the first
|
||||
/// elements in the merged set** (`v1` or `v2` in our example).
|
||||
///
|
||||
/// ```swift
|
||||
/// // Alternative new code:
|
||||
/// // - Migrations v1, v2 and v3 are deleted.
|
||||
/// // - The new migration v3-new merges v1, v2 and v3:
|
||||
/// migrator.registerMigration("v3-new", merging: ["v1", "v2", "v3"]) { db, appliedIDs in
|
||||
/// if !appliedIDs.contains("v1") {
|
||||
/// // Apply schema version 1
|
||||
/// }
|
||||
/// if !appliedIDs.contains("v2") {
|
||||
/// // Apply schema version 2
|
||||
/// }
|
||||
/// if !appliedIDs.contains("v3") {
|
||||
/// // Apply schema version 3
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - identifier: The migration identifier.
|
||||
/// - mergedIdentifiers: A set of previous migration identifiers
|
||||
/// that are merged in this migration.
|
||||
/// - foreignKeyChecks: This parameter is ignored if the database
|
||||
/// ``Configuration`` has disabled foreign keys.
|
||||
///
|
||||
/// The default `.deferred` checks have the migration run with
|
||||
/// disabled foreign keys, until foreign keys are checked right before
|
||||
/// changes are committed on disk. These deferred checks are not
|
||||
/// executed if the migrator is the result of
|
||||
/// ``disablingDeferredForeignKeyChecks()``.
|
||||
///
|
||||
/// The `.immediate` checks have the migration run with foreign
|
||||
/// keys enabled. Make sure you only use `.immediate` if the migration
|
||||
/// does not perform schema changes described in
|
||||
/// <https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes>
|
||||
/// - migrate: A closure that performs database operations. The
|
||||
/// first argument is a database connection. The second argument
|
||||
/// is the set of previous migrations that has been applied when
|
||||
/// the merged migration runs.
|
||||
/// - precondition: No migration with the same identifier as already
|
||||
/// been registered.
|
||||
public mutating func registerMigration(
|
||||
_ identifier: String,
|
||||
foreignKeyChecks: ForeignKeyChecks = .deferred,
|
||||
merging mergedIdentifiers: Set<String> = [],
|
||||
migrate: @escaping @Sendable (_ db: Database, _ appliedIdentifiers: Set<String>) throws -> Void)
|
||||
{
|
||||
let migrationChecks: Migration.ForeignKeyChecks
|
||||
switch foreignKeyChecks {
|
||||
@@ -226,7 +327,18 @@ public struct DatabaseMigrator: Sendable {
|
||||
case .immediate:
|
||||
migrationChecks = .immediate
|
||||
}
|
||||
registerMigration(Migration(identifier: identifier, foreignKeyChecks: migrationChecks, migrate: migrate))
|
||||
|
||||
// Remove the migration identifier from the list of merged identifiers.
|
||||
// Arguably, the semantics are ambiguous. And raising a fatal error
|
||||
// is a high price when we can just fix the input.
|
||||
var mergedIdentifiers = mergedIdentifiers
|
||||
mergedIdentifiers.remove(identifier)
|
||||
|
||||
registerMigration(Migration(
|
||||
identifier: identifier,
|
||||
mergedIdentifiers: mergedIdentifiers,
|
||||
foreignKeyChecks: migrationChecks,
|
||||
migrate: migrate))
|
||||
}
|
||||
|
||||
// MARK: - Applying Migrations
|
||||
@@ -450,6 +562,16 @@ public struct DatabaseMigrator: Sendable {
|
||||
|
||||
// MARK: - Non public
|
||||
|
||||
private struct Execution {
|
||||
enum Mode {
|
||||
case run(mergedIdentifiers: Set<String>)
|
||||
case deleteMergedIdentifiers
|
||||
}
|
||||
|
||||
var migration: Migration
|
||||
var mode: Mode
|
||||
}
|
||||
|
||||
private mutating func registerMigration(_ migration: Migration) {
|
||||
GRDBPrecondition(
|
||||
!_migrations.map({ $0.identifier }).contains(migration.identifier),
|
||||
@@ -457,8 +579,8 @@ public struct DatabaseMigrator: Sendable {
|
||||
_migrations.append(migration)
|
||||
}
|
||||
|
||||
/// Returns unapplied migration identifier,
|
||||
private func unappliedMigrations(upTo targetIdentifier: String, appliedIdentifiers: [String]) -> [Migration] {
|
||||
/// Returns unapplied migration executions
|
||||
private func unappliedExecutions(upTo targetIdentifier: String, appliedIdentifiers: Set<String>) -> [Execution] {
|
||||
var expectedMigrations: [Migration] = []
|
||||
for migration in _migrations {
|
||||
expectedMigrations.append(migration)
|
||||
@@ -472,32 +594,52 @@ public struct DatabaseMigrator: Sendable {
|
||||
expectedMigrations.last?.identifier == targetIdentifier,
|
||||
"undefined migration: \(String(reflecting: targetIdentifier))")
|
||||
|
||||
return expectedMigrations.filter { !appliedIdentifiers.contains($0.identifier) }
|
||||
return expectedMigrations.compactMap { migration in
|
||||
if appliedIdentifiers.contains(migration.identifier) {
|
||||
if migration.mergedIdentifiers.isDisjoint(with: appliedIdentifiers) {
|
||||
// Nothing to do
|
||||
return nil
|
||||
} else {
|
||||
// Migration is applied, but we have some merged identifiers to delete
|
||||
return Execution(migration: migration, mode: .deleteMergedIdentifiers)
|
||||
}
|
||||
} else {
|
||||
// Migration is not applied yet.
|
||||
let appliedMergedIdentifiers = migration.mergedIdentifiers.intersection(appliedIdentifiers)
|
||||
return Execution(migration: migration, mode: .run(mergedIdentifiers: appliedMergedIdentifiers))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws {
|
||||
try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
|
||||
let appliedIdentifiers = try self.appliedMigrations(db)
|
||||
|
||||
// Subsequent migration must not be applied
|
||||
let appliedMigrations = try self.appliedMigrations(db) // Only known ids
|
||||
if let targetIndex = _migrations.firstIndex(where: { $0.identifier == targetIdentifier }),
|
||||
let lastAppliedIdentifier = appliedIdentifiers.last,
|
||||
let lastAppliedIndex = _migrations.firstIndex(where: { $0.identifier == lastAppliedIdentifier }),
|
||||
let lastAppliedMigration = appliedMigrations.last,
|
||||
let lastAppliedIndex = _migrations.firstIndex(where: { $0.identifier == lastAppliedMigration }),
|
||||
targetIndex < lastAppliedIndex
|
||||
{
|
||||
fatalError("database is already migrated beyond migration \(String(reflecting: targetIdentifier))")
|
||||
}
|
||||
|
||||
let unappliedMigrations = self.unappliedMigrations(
|
||||
let appliedIdentifiers = try self.appliedIdentifiers(db) // All ids, even unknown ones
|
||||
let unappliedExecutions = self.unappliedExecutions(
|
||||
upTo: targetIdentifier,
|
||||
appliedIdentifiers: appliedIdentifiers)
|
||||
|
||||
if unappliedMigrations.isEmpty {
|
||||
if unappliedExecutions.isEmpty {
|
||||
return
|
||||
}
|
||||
|
||||
for migration in unappliedMigrations {
|
||||
try migration.run(db)
|
||||
for execution in unappliedExecutions {
|
||||
switch execution.mode {
|
||||
case .run(let mergedIdentifiers):
|
||||
try execution.migration.run(db, mergedIdentifiers: mergedIdentifiers)
|
||||
case .deleteMergedIdentifiers:
|
||||
try execution.migration.deleteMergedIdentifiers(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,40 +6,68 @@ struct Migration: Sendable {
|
||||
case disabled
|
||||
}
|
||||
|
||||
let identifier: String
|
||||
var foreignKeyChecks: ForeignKeyChecks
|
||||
let migrate: @Sendable (Database) throws -> Void
|
||||
typealias Migrate = @Sendable (_ db: Database, _ mergedIdentifiers: Set<String>) throws -> Void
|
||||
|
||||
func run(_ db: Database) throws {
|
||||
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
|
||||
switch foreignKeyChecks {
|
||||
case .deferred:
|
||||
try runWithDeferredForeignKeysChecks(db)
|
||||
case .immediate:
|
||||
try runWithImmediateForeignKeysChecks(db)
|
||||
case .disabled:
|
||||
try runWithDisabledForeignKeysChecks(db)
|
||||
let identifier: String
|
||||
let mergedIdentifiers: Set<String>
|
||||
var foreignKeyChecks: ForeignKeyChecks
|
||||
// Private so that the guarantees of `run(_:)` are enforced.
|
||||
private let migrate: Migrate
|
||||
|
||||
init(
|
||||
identifier: String,
|
||||
mergedIdentifiers: Set<String>,
|
||||
foreignKeyChecks: ForeignKeyChecks,
|
||||
migrate: @escaping Migrate
|
||||
) {
|
||||
self.identifier = identifier
|
||||
self.mergedIdentifiers = mergedIdentifiers
|
||||
self.foreignKeyChecks = foreignKeyChecks
|
||||
self.migrate = migrate
|
||||
}
|
||||
|
||||
func run(_ db: Database, mergedIdentifiers: Set<String>) throws {
|
||||
// Migrations access the raw SQLite schema, without alteration due
|
||||
// to the schemaSource. The goal is to ensure that migrations are
|
||||
// immutable, immune from spooky actions at a distance.
|
||||
try db.withSchemaSource(nil) {
|
||||
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
|
||||
switch foreignKeyChecks {
|
||||
case .deferred:
|
||||
try runWithDeferredForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
|
||||
case .immediate:
|
||||
try runWithImmediateForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
|
||||
case .disabled:
|
||||
try runWithDisabledForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
|
||||
}
|
||||
} else {
|
||||
try runWithImmediateForeignKeysChecks(db, mergedIdentifiers: mergedIdentifiers)
|
||||
}
|
||||
} else {
|
||||
try runWithImmediateForeignKeysChecks(db)
|
||||
}
|
||||
}
|
||||
|
||||
private func runWithImmediateForeignKeysChecks(_ db: Database) throws {
|
||||
|
||||
func deleteMergedIdentifiers(_ db: Database) throws {
|
||||
if mergedIdentifiers.isEmpty == false {
|
||||
try db.execute(literal: "DELETE FROM grdb_migrations WHERE identifier IN \(mergedIdentifiers)")
|
||||
}
|
||||
}
|
||||
|
||||
private func runWithImmediateForeignKeysChecks(_ db: Database, mergedIdentifiers: Set<String>) throws {
|
||||
try db.inTransaction(.immediate) {
|
||||
try migrate(db)
|
||||
try insertAppliedIdentifier(db)
|
||||
try migrate(db, mergedIdentifiers)
|
||||
try updateAppliedIdentifier(db)
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
|
||||
private func runWithDisabledForeignKeysChecks(_ db: Database) throws {
|
||||
private func runWithDisabledForeignKeysChecks(_ db: Database, mergedIdentifiers: Set<String>) throws {
|
||||
try db.execute(sql: "PRAGMA foreign_keys = OFF")
|
||||
try throwingFirstError(
|
||||
execute: {
|
||||
try db.inTransaction(.immediate) {
|
||||
try migrate(db)
|
||||
try insertAppliedIdentifier(db)
|
||||
try migrate(db, mergedIdentifiers)
|
||||
try updateAppliedIdentifier(db)
|
||||
return .commit
|
||||
}
|
||||
},
|
||||
@@ -48,7 +76,7 @@ struct Migration: Sendable {
|
||||
})
|
||||
}
|
||||
|
||||
private func runWithDeferredForeignKeysChecks(_ db: Database) throws {
|
||||
private func runWithDeferredForeignKeysChecks(_ db: Database, mergedIdentifiers: Set<String>) throws {
|
||||
// Support for database alterations described at
|
||||
// https://www.sqlite.org/lang_altertable.html#otheralter
|
||||
//
|
||||
@@ -60,8 +88,8 @@ struct Migration: Sendable {
|
||||
execute: {
|
||||
// > 2. Start a transaction.
|
||||
try db.inTransaction(.immediate) {
|
||||
try migrate(db)
|
||||
try insertAppliedIdentifier(db)
|
||||
try migrate(db, mergedIdentifiers)
|
||||
try updateAppliedIdentifier(db)
|
||||
|
||||
// > 10. If foreign key constraints were originally enabled
|
||||
// > then run PRAGMA foreign_key_check to verify that the
|
||||
@@ -80,7 +108,8 @@ struct Migration: Sendable {
|
||||
})
|
||||
}
|
||||
|
||||
private func insertAppliedIdentifier(_ db: Database) throws {
|
||||
try db.execute(sql: "INSERT INTO grdb_migrations (identifier) VALUES (?)", arguments: [identifier])
|
||||
private func updateAppliedIdentifier(_ db: Database) throws {
|
||||
try deleteMergedIdentifiers(db)
|
||||
try db.execute(literal: "INSERT INTO grdb_migrations (identifier) VALUES (\(identifier))")
|
||||
}
|
||||
}
|
||||
@@ -636,7 +636,7 @@ public struct AssociationAggregate<RowDecoder> {
|
||||
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
|
||||
|
||||
/// The SQL name for the value of this aggregate. See forKey(_:).
|
||||
var key: String? = nil
|
||||
var key: String?
|
||||
|
||||
/// Extends the request with the associated records used to compute the
|
||||
/// aggregate, and returns the aggregated expression.
|
||||
|
||||
@@ -362,11 +362,13 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
|
||||
where RowDecoder: Identifiable
|
||||
{
|
||||
selectWhenConnected { db in
|
||||
let primaryKey = try db.primaryKey(self.databaseTableName)
|
||||
let databaseTableName = self.databaseTableName
|
||||
|
||||
return selectWhenConnected { db in
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
|
||||
"selectID requires a single-column primary key in the table \(databaseTableName)")
|
||||
return [Column(primaryKey.columns[0])]
|
||||
}.asRequest(of: RowDecoder.ID.self)
|
||||
}
|
||||
@@ -633,15 +635,18 @@ extension QueryInterfaceRequest {
|
||||
@discardableResult
|
||||
public func deleteAll(_ db: Database) throws -> Int {
|
||||
let statement = try SQLQueryGenerator(relation: relation).makeDeleteStatement(db)
|
||||
try statement.execute()
|
||||
return db.changesCount
|
||||
var changesCount = 0
|
||||
try db.countChanges(&changesCount, forTable: relation.source.tableName) {
|
||||
try statement.execute()
|
||||
}
|
||||
return changesCount
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Batch Delete and Fetch
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Returns a `DELETE RETURNING` prepared statement.
|
||||
///
|
||||
/// For example:
|
||||
@@ -1133,8 +1138,11 @@ extension QueryInterfaceRequest {
|
||||
// database not hit
|
||||
return 0
|
||||
}
|
||||
try updateStatement.execute()
|
||||
return db.changesCount
|
||||
var changesCount = 0
|
||||
try db.countChanges(&changesCount, forTable: relation.source.tableName) {
|
||||
try updateStatement.execute()
|
||||
}
|
||||
return changesCount
|
||||
}
|
||||
|
||||
/// Updates matching rows, and returns the number of updated rows.
|
||||
@@ -1168,7 +1176,7 @@ extension QueryInterfaceRequest {
|
||||
// MARK: - Batch Update and Fetch
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Returns an `UPDATE RETURNING` prepared statement.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -826,10 +826,17 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
// ("foo", "bar") do not contain a unique key (primary key
|
||||
// or unique index).
|
||||
guard let columns = try db.columnsForUniqueKey(key.keys, in: databaseTableName) else {
|
||||
fatalError("""
|
||||
table \(databaseTableName) has no unique key on column(s) \
|
||||
\(key.keys.sorted().joined(separator: ", "))
|
||||
""")
|
||||
if (try? db.viewExists(databaseTableName)) == true {
|
||||
fatalError("""
|
||||
database view \(databaseTableName) has no unique key on column(s) \
|
||||
\(key.keys.sorted().joined(separator: ", "))
|
||||
""")
|
||||
} else {
|
||||
fatalError("""
|
||||
table \(databaseTableName) has no unique key on column(s) \
|
||||
\(key.keys.sorted().joined(separator: ", "))
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
let lowercaseColumns = columns.map { $0.lowercased() }
|
||||
|
||||
@@ -517,7 +517,7 @@ public struct SQLExpression: Sendable {
|
||||
/// The `>>` bitwise right shift operator
|
||||
static let rightShift = BinaryOperator(">>")
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// The `->` SQL operator
|
||||
static let jsonExtractJSON = BinaryOperator("->", isJSONValue: true)
|
||||
|
||||
@@ -1592,7 +1592,7 @@ extension SQLExpression {
|
||||
case let .associativeBinary(op, expressions):
|
||||
assert(expressions.count > 1)
|
||||
if op == .and {
|
||||
var result: Set<Int64>? = nil
|
||||
var result: Set<Int64>?
|
||||
for expression in expressions {
|
||||
if let expressionRowIDs = try expression.identifyingRowIDs(db, for: alias) {
|
||||
if var rowIDs = result {
|
||||
@@ -2020,8 +2020,8 @@ struct SQLAggregateFunctionInvocation {
|
||||
var name: String
|
||||
var arguments: [SQLExpression]
|
||||
var isDistinct = false
|
||||
var ordering: SQLOrdering? = nil // SQLite 3.44.0+
|
||||
var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
|
||||
var ordering: SQLOrdering? // SQLite 3.44.0+
|
||||
var filter: SQLExpression? // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
|
||||
|
||||
/// A boolean value indicating if a function is known to return a
|
||||
/// JSON value.
|
||||
@@ -2121,7 +2121,7 @@ extension SQLExpression {
|
||||
}
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Returns an expression suitable in JSON building contexts.
|
||||
var jsonBuilderExpression: SQLExpression {
|
||||
switch preferredJSONInterpretation {
|
||||
@@ -2373,7 +2373,7 @@ extension SQLSpecificExpressible {
|
||||
.desc(sqlExpression)
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// An ordering term for ascending order (nulls last).
|
||||
public var ascNullsLast: SQLOrdering {
|
||||
.ascNullsLast(sqlExpression)
|
||||
@@ -2383,7 +2383,7 @@ extension SQLSpecificExpressible {
|
||||
public var descNullsFirst: SQLOrdering {
|
||||
.descNullsFirst(sqlExpression)
|
||||
}
|
||||
#elseif !GRDBCIPHER
|
||||
#else
|
||||
/// An ordering term for ascending order (nulls last).
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
|
||||
public var ascNullsLast: SQLOrdering {
|
||||
|
||||
@@ -123,7 +123,7 @@ struct SQLForeignKeyRequest {
|
||||
}
|
||||
|
||||
private func tableType(_ db: Database, for name: String) throws -> TableType? {
|
||||
for schemaID in try db.schemaIdentifiers() {
|
||||
for schemaID in try db.fetchSchemaIdentifiers() {
|
||||
if try db.schema(schemaID).containsObjectNamed(name, ofType: .table) {
|
||||
return TableType(isView: false)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.function("ABS", [value.sqlExpression])
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// The `AVG` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
@@ -163,7 +163,7 @@ public func max(
|
||||
.simpleFunction("MAX", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// The `MAX` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
@@ -224,7 +224,7 @@ public func min(
|
||||
.simpleFunction("MIN", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// The `MIN` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
@@ -269,7 +269,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// The `SUM` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
@@ -333,7 +333,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// The `TOTAL` SQL aggregate function.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -285,12 +285,14 @@ extension SQLRelation: Refinable {
|
||||
func withStableOrder() -> Self {
|
||||
with { relation in
|
||||
relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in
|
||||
if try db.tableExists(source.tableName) {
|
||||
do {
|
||||
// Order by primary key. Don't order by rowid because those are
|
||||
// not stable: rowids can change after a vacuum.
|
||||
return try db.primaryKey(source.tableName).columns.map { SQLExpression.column($0).sqlOrdering }
|
||||
} else {
|
||||
// Support for views: create a stable order from all columns:
|
||||
} catch {
|
||||
// Could not find the primary key. Assume we're ordering
|
||||
// a view that is not customized with the schemaSource.
|
||||
// Create a stable order from all columns:
|
||||
// ORDER BY 1, 2, 3, ...
|
||||
let columnCount = try SQLQueryGenerator(relation: relation).columnCount(db)
|
||||
return (1...columnCount).map { SQL(sql: $0.description).sqlOrdering }
|
||||
|
||||
@@ -120,7 +120,7 @@ struct SQLTableGenerator {
|
||||
|
||||
var tableOptions: [String] = []
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
if options.contains(.strict) {
|
||||
tableOptions.append("STRICT")
|
||||
}
|
||||
|
||||
@@ -350,7 +350,7 @@ public final class ColumnDefinition {
|
||||
return self
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Defines the column as a generated column.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -79,7 +79,7 @@ public final class TableAlteration {
|
||||
alterations.append(.addColumnLiteral(literal))
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Renames a column.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -15,7 +15,7 @@ public struct TableOptions: OptionSet, Sendable {
|
||||
/// Such tables can not be tracked with <doc:DatabaseObservation> tools.
|
||||
public static let withoutRowID = TableOptions(rawValue: 1 << 2)
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Creates a [STRICT](https://www.sqlite.org/stricttables.html) table.
|
||||
public static let strict = TableOptions(rawValue: 1 << 3)
|
||||
#else
|
||||
|
||||
@@ -39,7 +39,7 @@ import Foundation // For JSONEncoder
|
||||
/// - ``databaseChanges(from:)``
|
||||
/// - ``databaseChanges(modify:)``
|
||||
/// - ``databaseEquals(_:)``
|
||||
public protocol EncodableRecord {
|
||||
public protocol EncodableRecord: GRDBSendableMetatype {
|
||||
/// Encodes the record into the provided persistence container.
|
||||
///
|
||||
/// In your implementation of this method, store in the `container` argument
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
// #elseif SomeTrait
|
||||
// import ...
|
||||
#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
import GRDBSQLite
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -519,20 +522,16 @@ private struct SingleValueRowDecoder<R: FetchableRecord>: SingleValueDecodingCon
|
||||
func decode(_ type: Int16.Type) throws -> Int16 { try columnDecoder.decode(type) }
|
||||
func decode(_ type: Int32.Type) throws -> Int32 { try columnDecoder.decode(type) }
|
||||
func decode(_ type: Int64.Type) throws -> Int64 { try columnDecoder.decode(type) }
|
||||
#if compiler(>=6)
|
||||
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
|
||||
func decode(_ type: Int128.Type) throws -> Int128 { try columnDecoder.decode(type) }
|
||||
#endif
|
||||
func decode(_ type: UInt.Type) throws -> UInt { try columnDecoder.decode(type) }
|
||||
func decode(_ type: UInt8.Type) throws -> UInt8 { try columnDecoder.decode(type) }
|
||||
func decode(_ type: UInt16.Type) throws -> UInt16 { try columnDecoder.decode(type) }
|
||||
func decode(_ type: UInt32.Type) throws -> UInt32 { try columnDecoder.decode(type) }
|
||||
func decode(_ type: UInt64.Type) throws -> UInt64 { try columnDecoder.decode(type) }
|
||||
#if compiler(>=6)
|
||||
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
|
||||
func decode(_ type: UInt128.Type) throws -> UInt128 { try columnDecoder.decode(type) }
|
||||
#endif
|
||||
|
||||
|
||||
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
|
||||
if let type = T.self as? any FetchableRecord.Type {
|
||||
// Prefer FetchableRecord decoding over Decodable.
|
||||
|
||||
@@ -53,7 +53,10 @@ extension MutablePersistableRecord {
|
||||
// Nil primary key
|
||||
return false
|
||||
}
|
||||
try statement.execute()
|
||||
return db.changesCount > 0
|
||||
var changesCount = 0
|
||||
try db.countChanges(&changesCount, forTable: type(of: self).databaseTableName) {
|
||||
try statement.execute()
|
||||
}
|
||||
return changesCount > 0
|
||||
}
|
||||
}
|
||||
@@ -90,7 +90,7 @@ extension MutablePersistableRecord {
|
||||
// MARK: - Insert and Fetch
|
||||
|
||||
extension MutablePersistableRecord {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Executes an `INSERT RETURNING` statement, and returns a new record built
|
||||
/// from the inserted row.
|
||||
///
|
||||
|
||||
@@ -86,7 +86,7 @@ extension MutablePersistableRecord {
|
||||
// MARK: - Save and Fetch
|
||||
|
||||
extension MutablePersistableRecord {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
|
||||
/// returns a new record built from the saved row.
|
||||
///
|
||||
|
||||
@@ -213,7 +213,7 @@ extension MutablePersistableRecord {
|
||||
// MARK: - Update and Fetch
|
||||
|
||||
extension MutablePersistableRecord {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
|
||||
/// new record built from the updated row.
|
||||
///
|
||||
@@ -839,7 +839,7 @@ extension MutablePersistableRecord {
|
||||
// MARK: - Internals
|
||||
|
||||
extension MutablePersistableRecord {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
@inlinable // allow specialization so that empty callbacks are removed
|
||||
func updateChangesAndFetch<T>(
|
||||
_ db: Database,
|
||||
@@ -956,8 +956,11 @@ extension MutablePersistableRecord {
|
||||
// Nil primary key
|
||||
try dao.recordNotFound()
|
||||
}
|
||||
let returned = try fetch(statement)
|
||||
if db.changesCount == 0 {
|
||||
var changesCount = 0
|
||||
let returned = try db.countChanges(&changesCount, forTable: type(of: self).databaseTableName) {
|
||||
try fetch(statement)
|
||||
}
|
||||
if changesCount == 0 {
|
||||
// No row was updated
|
||||
try dao.recordNotFound()
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// MARK: - Upsert
|
||||
|
||||
extension MutablePersistableRecord {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Executes an `INSERT ON CONFLICT DO UPDATE` statement.
|
||||
///
|
||||
/// The upsert behavior is triggered by a violation of any uniqueness
|
||||
|
||||
@@ -184,6 +184,11 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - important: Due to an SQLite limitation, this callback is
|
||||
/// unreliable when the record type writes into a database view
|
||||
/// through an INSTEAD OF trigger. The `inserted.rowID` value is
|
||||
/// not the rowid of the inserted row.
|
||||
///
|
||||
/// - parameter inserted: Information about the inserted row.
|
||||
mutating func didInsert(_ inserted: InsertionSuccess)
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ extension PersistableRecord {
|
||||
// MARK: - Insert and Fetch
|
||||
|
||||
extension PersistableRecord {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Executes an `INSERT RETURNING` statement, and returns a new record built
|
||||
/// from the inserted row.
|
||||
///
|
||||
|
||||
@@ -38,7 +38,7 @@ extension PersistableRecord {
|
||||
// MARK: - Save and Fetch
|
||||
|
||||
extension PersistableRecord {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
|
||||
/// returns a new record built from the saved row.
|
||||
///
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// MARK: - Upsert
|
||||
|
||||
extension PersistableRecord {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
/// Executes an `INSERT ON CONFLICT DO UPDATE` statement.
|
||||
///
|
||||
/// The upsert behavior is triggered by a violation of any uniqueness
|
||||
|
||||
@@ -73,6 +73,11 @@ public protocol PersistableRecord: MutablePersistableRecord {
|
||||
/// - note: If you need a mutating variant of this method, adopt the
|
||||
/// ``MutablePersistableRecord`` protocol instead.
|
||||
///
|
||||
/// - important: Due to an SQLite limitation, this callback is
|
||||
/// unreliable when the record type writes into a database view
|
||||
/// through an INSTEAD OF trigger. The `inserted.rowID` value is
|
||||
/// not the rowid of the inserted row.
|
||||
///
|
||||
/// - parameter inserted: Information about the inserted row.
|
||||
func didInsert(_ inserted: InsertionSuccess)
|
||||
}
|
||||
@@ -134,7 +134,7 @@ import Foundation
|
||||
/// - ``select(_:as:)-tjh0``
|
||||
/// - ``updateAll(_:onConflict:_:)-7vv9x``
|
||||
/// - ``updateAll(_:onConflict:_:)-7atfw``
|
||||
public protocol TableRecord {
|
||||
public protocol TableRecord: GRDBSendableMetatype {
|
||||
/// A type that defines columns.
|
||||
///
|
||||
/// For example:
|
||||
@@ -209,6 +209,10 @@ public protocol TableRecord {
|
||||
/// // SELECT * FROM player
|
||||
/// try Player.fetchAll(db)
|
||||
/// ```
|
||||
///
|
||||
/// You can specify the name of a database table, or the name of a
|
||||
/// database view. When you target a database view, some extra
|
||||
/// configuration might be needed. Please check <doc:ViewRecords>.
|
||||
static var databaseTableName: String { get }
|
||||
|
||||
/// The columns selected by the record.
|
||||
|
||||
@@ -27,7 +27,7 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
|
||||
self.attemptToFulfill = attemptToFulfill
|
||||
}
|
||||
|
||||
func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
func receive<S>(subscriber: S) where S: Subscriber & GRDBSendableMetatype, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = OnDemandFutureSubscription(
|
||||
attemptToFulfill: attemptToFulfill,
|
||||
downstream: subscriber)
|
||||
@@ -35,7 +35,9 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
|
||||
}
|
||||
}
|
||||
|
||||
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable {
|
||||
private class OnDemandFutureSubscription<Downstream>: Subscription, @unchecked Sendable
|
||||
where Downstream: Subscriber & GRDBSendableMetatype
|
||||
{
|
||||
// @unchecked because `state` is protected with `lock`.
|
||||
typealias Promise = @Sendable (Result<Downstream.Input, Downstream.Failure>) -> Void
|
||||
|
||||
|
||||
@@ -23,6 +23,16 @@ public func databaseQuestionMarks(count: Int) -> String {
|
||||
repeatElement("?", count: count).joined(separator: ",")
|
||||
}
|
||||
|
||||
#if compiler(>=6.2)
|
||||
/// A synonym for the standard `SendableMetatype` protocol in Swift 6.2,
|
||||
/// and `Any` in previous compiler versions.
|
||||
public typealias GRDBSendableMetatype = SendableMetatype
|
||||
#else
|
||||
/// A synonym for the standard `SendableMetatype` protocol in Swift 6.2,
|
||||
/// and `Any` in previous compiler versions.
|
||||
public typealias GRDBSendableMetatype = Any
|
||||
#endif
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
/// Reserved for GRDB: do not use.
|
||||
|
||||
@@ -276,7 +276,7 @@ extension ValueConcurrentObserver {
|
||||
}
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
extension ValueConcurrentObserver {
|
||||
/// Synchronously starts the observation, and returns the initial value.
|
||||
///
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
// which is its `Fetcher`.
|
||||
|
||||
/// Implementation details of `ValueReducer`.
|
||||
public protocol _ValueReducer {
|
||||
public protocol _ValueReducer: GRDBSendableMetatype {
|
||||
/// The Sendable type that fetches database values
|
||||
associatedtype Fetcher: _ValueReducerFetcher
|
||||
|
||||
|
||||
@@ -511,7 +511,11 @@ extension DatabasePublishers {
|
||||
self.start = start
|
||||
}
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
public func receive<S>(subscriber: S)
|
||||
where S: Subscriber & GRDBSendableMetatype,
|
||||
Failure == S.Failure,
|
||||
Output == S.Input
|
||||
{
|
||||
let subscription = ValueSubscription(
|
||||
start: start,
|
||||
downstream: subscriber)
|
||||
@@ -521,7 +525,7 @@ extension DatabasePublishers {
|
||||
|
||||
private class ValueSubscription<Downstream>:
|
||||
Subscription, @unchecked Sendable
|
||||
where Downstream: Subscriber,
|
||||
where Downstream: Subscriber & GRDBSendableMetatype,
|
||||
Downstream.Failure == Error
|
||||
{
|
||||
// @unchecked Sendable because `cancellable` and `state` are
|
||||
|
||||
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user