Compare commits

...
Author SHA1 Message Date
Tim De Jong 3dd3bbf0c5 vscode config 2025-10-12 18:03:57 +02:00
Tim De Jong d7cf0f9e59 NSError bridging is not available, or doesn't work the same on non-Darwin platforms. Skip testNSErrorBridging on these platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong 389c3e0d4a Use #if !canImport(Combine) per test case (as done by @marcprux) and throw an XCTSkip for these test cases. This gives a better impression how many tests are skipped on Linux/non-Darwin platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong a212bf9e89 It should be canImport(Darwin) not os(Darwin) 2025-10-12 18:03:57 +02:00
Tim De Jong 65186104cc Integrated upstream changes.
Some tests depend on Combine which is not available on non-Darwin platforms. Fix this.
2025-10-12 18:03:57 +02:00
Tim De Jong 2f108508fa Fixed DatabaseSnapshotTests on non-darwin platforms 2025-10-12 18:03:57 +02:00
Tim De Jong 5513eab099 Fixed the tests in DatabaseQueueTests.swift 2025-10-12 18:03:57 +02:00
Tim De Jong 2ad2d20a89 Fixed the unit tests in DatabasePoolConcurrencyTests. 2025-10-12 18:03:57 +02:00
Tim De Jong dd90fe6e62 Ignore ValueObservationRecorderTests.swift on non-Darwin platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong 691207567a Ignore FailureTestCase.swift entirely on non-Darwin platforms for now. 2025-10-12 18:03:57 +02:00
Tim De Jong c7f1dd7470 Fixed import in CGFloatTests.swift to work under non-Darwin platforms. 2025-10-12 18:03:57 +02:00
Tim De Jong 8e5b9ca9bd Fixed UUID fromDatabaseValue for non-Darwin platforms 2025-10-12 18:03:56 +02:00
Tim De Jong dc7d47c066 Fixed databaseValue build for non-Darwin platforms. 2025-10-12 18:03:56 +02:00
Tim De Jong 14f60ad48f Fixed fromDatabaseValue build under non-Darwin platforms 2025-10-12 18:03:56 +02:00
Tim De Jong e758fde941 Removed #if !os(Linux) in NSString.swift, NSData.swift and Date.swift. 2025-10-12 17:43:25 +02:00
Tim De Jong 7477e1cff8 Removed the #if !os(Linux) compiler directive in the Decimal extension, as it compiles fine under swift 6 2025-10-12 17:43:15 +02:00
Tim De Jong 2d6fe172c3 Import Foundation for CGFloat on non-Darwin platforms 2025-10-12 17:43:02 +02:00
Tim De Jong 0526853dde Fixed some linker errors caused by WAL absence on Linux. 2025-10-12 17:42:49 +02:00
Gwendal Roué a60810f28e Merge pull request #1819 from groue/dev/SQLCipher-cleanup
Accept multiple SQLCipher libraries
2025-10-12 15:46:52 +02:00
Gwendal Roué c35095c6da Enable more tests 2025-10-12 14:58:06 +02:00
Gwendal Roué f878d99733 Use SQLITE_HAS_CODEC instead of GRDBCIPHER when testing for SQLCipher availability
GRDBCIPHER is now just a marker for importing SQLCipher with CocoaPods.

Also, enable all APIs that used to be disabled with SQLCipher, and skip tests that require a specific SQLite version.
2025-10-12 14:49:59 +02:00
Gwendal Roué 48a17ce490 Merge pull request #1826 from groue/dev/snapshot-cleanup
Simplify the compiler checks for the availability of SQLite snapshots
2025-10-12 14:27:06 +02:00
Gwendal Roué 361a482b1e Enable SQLITE_ENABLE_SNAPSHOT by default and introduce SQLITE_DISABLE_SNAPSHOT 2025-10-12 14:03:09 +02:00
Gwendal Roué 8cba324d6e Refactor the SQLite import
We can not use `#if Trait` because Xcode does not enable those compiler flags. Always count on Apple for delivering the best quality software.

So now we import the default SPM SQLite last, after all other cases have been excluded.

The GRDB framework (GRDB.xcodeproj and GRDB via CocoaPods) is distinct from the default SPM trait, so we detect it with GRDBFRAMEWORK.
2025-10-04 17:56:06 +02:00
Gwendal Roué 17e1683b66 Bump CI to macOS 15 and Xcode 16.4 2025-10-04 17:56:06 +02:00
Gwendal Roué b1b83abd8b Simplify the compiler checks for the availability of SQLite snapshots 2025-10-04 14:15:13 +02:00
Gwendal Roué d06c9ed6b5 Enable SQLITE_ENABLE_SNAPSHOT in the Xcode GRDB framework 2025-10-04 14:15:13 +02:00
Gwendal Roué 9a98ed6292 Enable SQLITE_ENABLE_SNAPSHOT in the GRDBSQLite trait, on Darwin platforms 2025-10-04 14:15:13 +02:00
Gwendal Roué 5cc85a98f3 Only depend on GRDBSQLite when the default GRDBSQLite trait is active. 2025-10-04 13:53:38 +02:00
Gwendal Roué edc1d646f0 [BREAKING] Bump minimum Swift version to 6.1 2025-10-04 13:53:38 +02:00
Gwendal Roué ab09078842 Fix failing test for merged migration that merges itself 2025-10-03 09:36:22 +02:00
Gwendal Roué 267e1ea5a6 Add failing test for merged migration that merges itself 2025-10-03 09:34:26 +02:00
Gwendal Roué 18497b68fd Merge branch 'development' 2025-10-02 08:11:07 +02:00
Gwendal Roué 19e33e2e7d v7.8.0 2025-10-02 08:10:52 +02:00
Gwendal Roué 76e0815907 Merge pull request #1818 from groue/dev/obsolete-migrations
Merged Migrations
2025-10-02 08:06:24 +02:00
Gwendal Roué 85ad232b0b Support for migrations that merge previous migrations 2025-10-01 17:24:00 +02:00
Gwendal Roué db695cf7dc Merge branch 'development' 2025-09-29 21:14:01 +02:00
Gwendal Roué 76a7be8404 v7.7.1 2025-09-29 20:29:44 +02:00
Gwendal Roué 196c33ba63 Merge pull request #1822 from groue/dev/issue-1820
Fix the save() method for record types with attached triggers
2025-09-29 20:26:12 +02:00
Gwendal Roué 50a74f7b03 Cleanup 2025-09-29 19:43:41 +02:00
Gwendal Roué 3f27fb9289 Fix #1820
The regression was introduced by c7bbebc
2025-09-29 19:35:00 +02:00
Gwendal Roué 62fdd41d75 Failing regression test for #1820 2025-09-29 19:34:15 +02:00
Gwendal Roué c5d02eac32 Merge branch 'development' 2025-09-23 20:14:27 +02:00
Gwendal Roué d1bfce829b v7.7.0 2025-09-23 19:30:13 +02:00
Gwendal Roué edd292bcbd CHANGELOG 2025-09-23 17:44:05 +02:00
Gwendal Roué a0e101e683 Merge pull request #1810 from groue/dev/persistable-views
Persistable Database Views
2025-09-23 17:38:30 +02:00
Gwendal Roué 9ef5e2c8eb Simplify error messages 2025-09-23 17:12:27 +02:00
Gwendal Roué f5dc68fc6f Fix typos 2025-09-23 17:12:27 +02:00
Gwendal Roué b210ec7428 View Records guide 2025-09-23 17:12:27 +02:00
Gwendal Roué a7e3acf409 Remove TODO warnings 2025-09-23 17:12:27 +02:00
Gwendal Roué ca27f75760 Test the stable order of views with a primary key 2025-09-23 17:12:27 +02:00
Gwendal Roué 99ecf76a77 Support primary key when testing the existence of an association to a view 2025-09-23 17:12:27 +02:00
Gwendal Roué f4991273c2 DatabaseSchemaSource tests 2025-09-23 17:12:27 +02:00
Gwendal Roué 1b98a964d7 Documentation 2025-09-23 17:12:27 +02:00
Gwendal Roué 1095d21abd Default implementation for schema source chaining.
When GRDB eventually adds methods to the DatabaseSchemaSource protocol, our chained schema source will implement chaining on those new methods.

When users write their own custom chaining schema source, the compiler will not tell them that they have to chain the new methods when they upgrade GRDB. The built-in (and correct) implementation of chaining helps avoiding this scenario.
2025-09-23 17:12:27 +02:00
Gwendal Roué eb2378a741 DatabaseSchemaSource documentation 2025-09-23 17:12:27 +02:00
Gwendal Roué 37dde39557 Public Database.schemaSource and withSchemaSource(_:execute:) 2025-09-23 17:12:27 +02:00
Gwendal Roué 5786391dc9 RecordMappedOnMutableViewTests 2025-09-23 17:12:27 +02:00
Gwendal Roué e1abafaae3 Ignore schema source during migrations 2025-09-23 17:12:27 +02:00
Gwendal Roué 93d0baeade The stable order for views is provided by the schemaSource, if any 2025-09-23 17:12:27 +02:00
Gwendal Roué 26ebd7e147 Update outdated comments 2025-09-23 17:12:27 +02:00
Gwendal Roué 75e99861af Update TableRecordUpdateTests with record types based on database views 2025-09-23 17:12:27 +02:00
Gwendal Roué 2e433a3cb2 Update TableRecordDeleteTests with record types based on database views 2025-09-23 17:12:27 +02:00
Gwendal Roué 9518d74fa6 Improve error message 2025-09-23 17:12:27 +02:00
Gwendal Roué c7bbebc80f Change the way we count changes in order to support INSTEAD OF triggers
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.

Since we want to support INSTEAD OF triggers well, so that record types can be based on views, we switch to sqlite3_total_changes().
2025-09-23 17:12:27 +02:00
Gwendal Roué 38f5226e95 Database.table(_:hasUniqueKey:) now accept views 2025-09-23 17:12:27 +02:00
Gwendal Roué 2b19803644 DatabaseSchemaSource tests 2025-09-23 17:12:27 +02:00
Gwendal Roué d7d61add23 DatabaseSchemaSource customizes the primary key of database views 2025-09-23 17:12:27 +02:00
Gwendal Roué d040588849 Database.fetchPrimitivePrimaryKey(forTable:)
This method is necessary for the customization of schema introspection: it must be possible to fallback on the primitive SQLite schema introspection when needed.
2025-09-23 17:12:27 +02:00
Gwendal Roué 30313623eb Make DatabaseSchemaID and DatabaseObjectID public
This is also a big cleanup opportunity.

We need public schema identifiers in order to support the customization of schema introspection.
2025-09-23 17:12:27 +02:00
149 changed files with 4327 additions and 947 deletions

No files matched your search

+24 -24
View File
@@ -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,17 +40,17 @@ 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@v5
@@ -66,9 +66,9 @@ 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@v5
- name: ${{ matrix.name }}
@@ -83,9 +83,9 @@ 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@v5
- name: ${{ matrix.name }}
@@ -100,9 +100,9 @@ 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@v5
- name: ${{ matrix.name }}
@@ -117,9 +117,9 @@ 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@v5
- name: ${{ matrix.name }}
@@ -134,9 +134,9 @@ 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@v5
- name: ${{ matrix.name }}
+1 -1
View File
@@ -2,4 +2,4 @@ version: 1
builder:
configs:
- documentation_targets: [GRDB]
swift_version: 6.0
swift_version: 6.1
+7
View File
@@ -0,0 +1,7 @@
{
"editor.formatOnSave": false,
"editor.insertSpaces": true,
"editor.tabSize": 4,
"editor.detectIndentation": false,
"editor.trimAutoWhitespace": false
}
+23
View File
@@ -7,6 +7,8 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `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)
@@ -138,6 +140,27 @@ 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
@@ -382,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;
@@ -411,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;
@@ -427,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";
};
@@ -444,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";
};
+3 -3
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.6.1'
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
+12
View File
@@ -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 */,
@@ -2010,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 */,
@@ -2114,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 */,
@@ -2208,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 */,
+23 -4
View File
@@ -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)
@@ -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.
File diff suppressed because it is too large. Load diff
+7 -4
View File
@@ -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
+54 -4
View File
@@ -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:)``
@@ -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
@@ -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
+7 -4
View File
@@ -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
+7 -4
View File
@@ -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
+7 -4
View File
@@ -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.
+2 -2
View File
@@ -684,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 {
@@ -950,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.
+2 -2
View File
@@ -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
+218
View File
@@ -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
}
}
+8 -5
View File
@@ -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
+7 -4
View File
@@ -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
+2 -2
View File
@@ -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.
///
+4
View File
@@ -1,4 +1,8 @@
#if os(Linux)
@preconcurrency import Dispatch
#else
import Dispatch
#endif
/// An actor that runs in a DispatchQueue.
///
+7 -4
View File
@@ -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
+7 -4
View File
@@ -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
+7 -4
View File
@@ -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
+7 -4
View File
@@ -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)
+7 -4
View File
@@ -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
+3 -1
View File
@@ -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
+7 -4
View File
@@ -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
+7 -6
View File
@@ -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.
+7 -6
View File
@@ -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
+11 -3
View File
@@ -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
+6 -2
View File
@@ -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? {
+19 -9
View File
@@ -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
+7 -4
View File
@@ -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 {
+8 -17
View File
@@ -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 -1
View File
@@ -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
@@ -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``
+1
View File
@@ -94,6 +94,7 @@ let players: [Player] = try dbQueue.read { db in
- <doc:RecordRecommendedPractices>
- <doc:RecordTimestamps>
- <doc:SingleRowTables>
- <doc:ViewRecords>
### Application Tools
+383
View File
@@ -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
+1 -1
View File
@@ -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 {
+7 -4
View File
@@ -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
+7 -4
View File
@@ -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
+7 -4
View File
@@ -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
+7 -4
View File
@@ -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
+7 -4
View File
@@ -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
View File
@@ -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+
+2 -2
View File
@@ -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
+9 -6
View File
@@ -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
+7 -4
View File
@@ -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.
+7 -4
View File
@@ -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
+2 -2
View File
@@ -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
+7 -4
View File
@@ -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
+1 -1
View File
@@ -154,7 +154,7 @@ extension SQLSpecificExpressible {
}
}
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
extension SQLJSONExpressible {
/// The `->>` SQL operator.
///
+1 -1
View File
@@ -1,4 +1,4 @@
#if GRDBCUSTOMSQLITE || GRDBCIPHER
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
// MARK: - JSON
extension Database {
+156 -14
View File
@@ -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)
}
}
}
+54 -25
View File
@@ -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))")
}
}
@@ -635,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:
@@ -1135,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.
@@ -1170,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() }
+4 -4
View File
@@ -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)
@@ -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)
}
+5 -5
View File
@@ -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:
+5 -3
View File
@@ -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
+8 -9
View File
@@ -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)
+1 -1
View File
@@ -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.
///
+1 -1
View File
@@ -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 -1
View File
@@ -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
+5
View File
@@ -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)
}
+4
View File
@@ -209,6 +209,10 @@ public protocol TableRecord: GRDBSendableMetatype {
/// // 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.
@@ -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.
///
+12
View File
@@ -60,6 +60,7 @@
5623B61A2AED39C300436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6182AED39C200436239 /* DatabaseQueueTemporaryCopyTests.swift */; };
56256EDE25D1BC07008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256EDD25D1BC07008C2BDD /* ForeignKey.swift */; };
562756461E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
562822FC2E631F3200B5A627 /* DatabaseSchemaSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */; };
562B58CE2A29BC0700E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CC2A29BC0700E8C75D /* Issue1383.sqlite */; };
562EA8291F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
562EA8321F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
@@ -219,6 +220,7 @@
567E420A242AB3CB00CAAD2C /* FailureTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */; };
567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
568515A62E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A52E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
5685C1962AD52EF200DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1942AD52EF200DA4B7A /* ListDumpFormat.swift */; };
56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; };
56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; };
@@ -279,6 +281,7 @@
56B964D61DA521450002DA19 /* FTS5TableBuilderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */; };
56B964DB1DA5216B0002DA19 /* FTS5RecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C11DA521450002DA19 /* FTS5RecordTests.swift */; };
56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
56BCA2642E6C291200E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2632E6C291200E4F08D /* DatabaseSchemaSourceTests.swift */; };
56BF22882417821F003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF22862417821F003D86EB /* UtilsTests.swift */; };
56C0539322ACEECD0029D27D /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538A22ACEECD0029D27D /* Fetch.swift */; };
56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538C22ACEECD0029D27D /* ValueReducer.swift */; };
@@ -516,6 +519,7 @@
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
56256EDD25D1BC07008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSource.swift; sourceTree = "<group>"; };
562B58CC2A29BC0700E8C75D /* 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>"; };
@@ -698,6 +702,7 @@
567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailureTestCase.swift; sourceTree = "<group>"; };
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
568515A52E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = "<group>"; };
5685C1942AD52EF200DA4B7A /* 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>"; };
56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
@@ -801,6 +806,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>"; };
56BCA2632E6C291200E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = "<group>"; };
56BF22862417821F003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = "<group>"; };
56C0538A22ACEECD0029D27D /* Fetch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fetch.swift; sourceTree = "<group>"; };
56C0538C22ACEECD0029D27D /* ValueReducer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = "<group>"; };
@@ -1011,6 +1017,7 @@
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */,
563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */,
568515A52E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift */,
);
name = PersistableRecord;
sourceTree = "<group>";
@@ -1491,6 +1498,7 @@
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
564CE5C521B8FFE500652B19 /* DatabaseRegionObservationTests.swift */,
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
56BCA2632E6C291200E4F08D /* DatabaseSchemaSourceTests.swift */,
568EB71F2921235E00E59445 /* DatabaseSnapshotPoolTests.swift */,
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */,
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */,
@@ -1597,6 +1605,7 @@
569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */,
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */,
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
562822FB2E631F3200B5A627 /* DatabaseSchemaSource.swift */,
566A842B20413D9A00E50BFD /* DatabaseSnapshot.swift */,
568EB71A2921232200E59445 /* DatabaseSnapshotPool.swift */,
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
@@ -2029,6 +2038,7 @@
566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
5698AD371DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
562822FC2E631F3200B5A627 /* DatabaseSchemaSource.swift in Sources */,
5656A8732295BD56001FF3FF /* QueryInterfaceRequest.swift in Sources */,
566B91151FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
F3BA80741CFB2E55003DC1BA /* SerializedDatabase.swift in Sources */,
@@ -2253,6 +2263,7 @@
563B06D32185E04600B38F35 /* ValueObservationReadonlyTests.swift in Sources */,
567F45AB1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
F3BA80A61CFB2F91003DC1BA /* GRDBTestCase.swift in Sources */,
568515A62E66C2C60082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
56959621222C458A002CB7C9 /* AssociationHasManyThroughSQLTests.swift in Sources */,
5657AB411D108BA9006283EF /* FoundationNSDataTests.swift in Sources */,
560233CF2724339A00529DF3 /* SharedValueObservationTests.swift in Sources */,
@@ -2369,6 +2380,7 @@
566A84432041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */,
569BBA2B228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */,
56BCA2642E6C291200E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
56F34FBF24B094D2007513FC /* SQLExpressionIsConstantTests.swift in Sources */,
56DFC3AE2C84794400DFE5DC /* AsyncSemaphore.swift in Sources */,
5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */,
+25 -2
View File
@@ -1,11 +1,28 @@
// swift-tools-version:6.0
// swift-tools-version:6.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import Foundation
import PackageDescription
let darwinPlatforms: [Platform] = [
.iOS,
.macOS,
.macCatalyst,
.tvOS,
.visionOS,
.watchOS,
]
var swiftSettings: [SwiftSetting] = [
.define("SQLITE_ENABLE_FTS5"),
// Until Xcode has proper support for package traits, we must enable
// SQLITE_ENABLE_SNAPSHOT by default so that Xcode projects that build
// a Darwin app can depend on GRDB and profit from WAL snapshots.
// Package traits who want to disable snapshots must set SQLITE_DISABLE_SNAPSHOT.
// TODO: when Xcode support traits, remove all mentions of SQLITE_DISABLE_SNAPSHOT and update as below:
// .define("SQLITE_ENABLE_SNAPSHOT", .when(platforms: darwinPlatforms, traits: ["GRDBSQLite"])),
.define("SQLITE_ENABLE_SNAPSHOT"),
// Not all Linux distributions have support for WAL snapshots.
.define("SQLITE_DISABLE_SNAPSHOT", .when(platforms: [.linux])),
]
var cSettings: [CSetting] = []
var dependencies: [PackageDescription.Package.Dependency] = []
@@ -41,6 +58,10 @@ let package = Package(
.library(name: "GRDB", targets: ["GRDB"]),
.library(name: "GRDB-dynamic", type: .dynamic, targets: ["GRDB"]),
],
traits: [
"GRDBSQLite",
.default(enabledTraits: ["GRDBSQLite"]),
],
dependencies: dependencies,
targets: [
.systemLibrary(
@@ -48,7 +69,9 @@ let package = Package(
providers: [.apt(["libsqlite3-dev"])]),
.target(
name: "GRDB",
dependencies: ["GRDBSQLite"],
dependencies: [
.target(name: "GRDBSQLite", condition: .when(traits: ["GRDBSQLite"])),
],
path: "GRDB",
resources: [.copy("PrivacyInfo.xcprivacy")],
cSettings: cSettings,
+3 -3
View File
@@ -10,7 +10,7 @@
</p>
<p align="center">
<a href="https://developer.apple.com/swift/"><img alt="Swift 6" src="https://img.shields.io/badge/swift-6-orange.svg?style=flat"></a>
<a href="https://developer.apple.com/swift/"><img alt="Swift 6.1" src="https://img.shields.io/badge/swift-6.1-orange.svg?style=flat"></a>
<a href="https://github.com/groue/GRDB.swift/blob/master/LICENSE"><img alt="License" src="https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000"></a>
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
</p>
@@ -25,9 +25,9 @@
---
**Latest release**: July 23, 2025 • [version 7.6.1](https://github.com/groue/GRDB.swift/tree/v7.6.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Latest release**: October 2, 2025 • [version 7.8.0](https://github.com/groue/GRDB.swift/tree/v7.8.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ &bull; SQLite 3.20.0+ &bull; Swift 6+ / Xcode 16+
**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ &bull; SQLite 3.20.0+ &bull; Swift 6.1+ / Xcode 16.3+
**Contact**:
+1 -1
View File
@@ -13,4 +13,4 @@ OTHER_CFLAGS = -DUSING_BUILTIN_SQLITE -DGRDBCUSTOMSQLITE $(CUSTOM_SQLLIBRARY_CFL
GCC_PREPROCESSOR_DEFINITIONS = "GRDBCUSTOMSQLITE=1"
OTHER_SWIFT_FLAGS = -D USING_BUILTIN_SQLITE -D GRDBCUSTOMSQLITE $(CUSTOM_OTHER_SWIFT_FLAGS)
HEADER_SEARCH_PATHS = $(SRCROOT)/SQLiteCustom/src
SWIFT_VERSION = 6.0
SWIFT_VERSION = 6.1
+2 -1
View File
@@ -3,7 +3,8 @@ INFOPLIST_FILE = Support/Info.plist
PRODUCT_NAME = GRDB
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.$(PRODUCT_NAME:rfc1034identifier)
MODULEMAP_FILE = $(SRCROOT)/Support/module.modulemap
SWIFT_VERSION = 6.0
SWIFT_VERSION = 6.1
OTHER_SWIFT_FLAGS = $(inherited) -D GRDBFRAMEWORK
// Slow compilation hunt:
// OTHER_SWIFT_FLAGS = $(inherited) -Xfrontend -warn-long-expression-type-checking=100 -Xfrontend -warn-long-function-bodies=100
+1 -1
View File
@@ -2,7 +2,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 13.0
MACOSX_DEPLOYMENT_TARGET = 10.15
TVOS_DEPLOYMENT_TARGET = 13.0
WATCHOS_DEPLOYMENT_TARGET = 7.0
OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5
OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_SNAPSHOT
//// Compile with all opt-in APIs
//GCC_PREPROCESSOR_DEFINITIONS = $(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1
+1
View File
@@ -2,4 +2,5 @@
// Tests still use the Swift 5 language mode.
SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES = YES
OTHER_SWIFT_FLAGS = $(inherited) -D GRDBFRAMEWORK
OTHER_SWIFT_FLAGS = $(inherited) -enable-upcoming-feature GlobalActorIsolatedTypesUsability
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>7.6.1</string>
<string>7.8.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -491,15 +491,19 @@
567B5C4C2AD32F7000629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C492AD32F7000629622 /* DatabaseDumpTests.swift */; };
567B5C4D2AD32F7000629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */; };
567B5C4E2AD32F7000629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */; };
568515AB2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
568515AC2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
568C3F7F2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; };
568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; };
5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; };
56BCA2662E6C294600E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */; };
56BCA2672E6C294600E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */; };
56DFC3B32C84798300DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */; };
56DFC3B42C84798300DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */; };
56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; };
56F61DF1283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; };
5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; };
5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */ = {isa = PBXBuildFile; };
98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FE2436BF42B9FCD6552E7076 /* Pods_GRDBTests.framework */; };
F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; };
/* End PBXBuildFile section */
@@ -752,8 +756,10 @@
567B5C282AD32A2D00629622 /* SharedValueObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SharedValueObservationTests.swift; sourceTree = "<group>"; };
567B5C492AD32F7000629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = "<group>"; };
567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = "<group>"; };
568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = "<group>"; };
568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = "<group>"; };
56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = "<group>"; };
56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
@@ -769,7 +775,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
5B33E6E34F941B4C839A714F /* (null) in Frameworks */,
5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */,
98AB0B01EB11B33719AE412E /* Pods_GRDBTests.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -935,6 +941,7 @@
56419CF724A5405A004967E1 /* DatabaseRegionObservationTests.swift */,
56419D2624A5405D004967E1 /* DatabaseRegionTests.swift */,
56419CB324A54055004967E1 /* DatabaseSavepointTests.swift */,
56BCA2652E6C294600E4F08D /* DatabaseSchemaSourceTests.swift */,
567B5C222AD32A2D00629622 /* DatabaseSnapshotPoolTests.swift */,
56419CE624A54058004967E1 /* DatabaseSnapshotTests.swift */,
56419CD624A54057004967E1 /* DatabaseSuspensionTests.swift */,
@@ -1019,6 +1026,7 @@
56419C9F24A54054004967E1 /* Record+QueryInterfaceRequestTests.swift */,
56419D0C24A5405B004967E1 /* RecordEditedTests.swift */,
56419CAE24A54054004967E1 /* RecordInitializersTests.swift */,
568515AA2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift */,
567B5C262AD32A2D00629622 /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */,
56419D4224A5405F004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */,
56419D0824A5405B004967E1 /* RecordMinimalPrimaryKeySingleTests.swift */,
@@ -1380,6 +1388,7 @@
56419E4F24A54062004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */,
567B5C412AD32A2D00629622 /* SharedValueObservationTests.swift in Sources */,
56419E9F24A54063004967E1 /* FetchableRecordTests.swift in Sources */,
568515AB2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
56419E3324A54062004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */,
56419DFF24A54062004967E1 /* DatabaseCollationTests.swift in Sources */,
56419E9B24A54063004967E1 /* FTS3RecordTests.swift in Sources */,
@@ -1484,6 +1493,7 @@
56419DD124A54062004967E1 /* ValueObservationRecordTests.swift in Sources */,
56419E1124A54062004967E1 /* ForeignKeyInfoTests.swift in Sources */,
56419DC724A54062004967E1 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56BCA2672E6C294600E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
56419EF524A54063004967E1 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
56419D6F24A54062004967E1 /* DatabaseQueueInMemoryTests.swift in Sources */,
56419E7324A54062004967E1 /* TruncateOptimizationTests.swift in Sources */,
@@ -1630,6 +1640,7 @@
56419E5024A54062004967E1 /* DatabaseValueConvertibleEscapingTests.swift in Sources */,
567B5C422AD32A2D00629622 /* SharedValueObservationTests.swift in Sources */,
56419EA024A54063004967E1 /* FetchableRecordTests.swift in Sources */,
568515AC2E66C2F40082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
56419E3424A54062004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */,
56419E0024A54062004967E1 /* DatabaseCollationTests.swift in Sources */,
56419E9C24A54063004967E1 /* FTS3RecordTests.swift in Sources */,
@@ -1734,6 +1745,7 @@
56419DD224A54062004967E1 /* ValueObservationRecordTests.swift in Sources */,
56419E1224A54062004967E1 /* ForeignKeyInfoTests.swift in Sources */,
56419DC824A54062004967E1 /* DatabaseAfterNextTransactionCommitTests.swift in Sources */,
56BCA2662E6C294600E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
56419EF624A54063004967E1 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
56419D7024A54062004967E1 /* DatabaseQueueInMemoryTests.swift in Sources */,
56419E7424A54062004967E1 /* TruncateOptimizationTests.swift in Sources */,
@@ -479,6 +479,8 @@
567B5C462AD32F5900629622 /* DatabaseDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C432AD32F5900629622 /* DatabaseDumpTests.swift */; };
567B5C472AD32F5900629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */; };
567B5C482AD32F5900629622 /* DatabaseReaderDumpTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */; };
568515A82E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
568515A92E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
568C3F822A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */; };
568C3F832A5AB38300A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */; };
568C3F8B2A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */; };
@@ -497,11 +499,13 @@
568C3F982A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; };
5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; };
56BCA2692E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */; };
56BCA26A2E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */; };
56DFC3B02C84797400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */; };
56DFC3B12C84797400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */; };
56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; };
56F61DF7283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; };
5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; };
5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */ = {isa = PBXBuildFile; };
E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 67377FE4CDAD675809F93AD4 /* Pods_GRDBTests.framework */; };
F2B3C4250D67969FF3948955 /* Pods_GRDBTestsEncrypted.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7D5C7999E7D9CE7145687F5D /* Pods_GRDBTestsEncrypted.framework */; };
/* End PBXBuildFile section */
@@ -748,6 +752,7 @@
567B5C0F2AD32A0000629622 /* TableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableTests.swift; sourceTree = "<group>"; };
567B5C432AD32F5900629622 /* DatabaseDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDumpTests.swift; sourceTree = "<group>"; };
567B5C442AD32F5900629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = "<group>"; };
568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = "<group>"; };
568C3F812A5AB38300A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = "<group>"; };
568C3F842A5AB3A800A2309D /* AssociationPrefetchingRelationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRelationTests.swift; sourceTree = "<group>"; };
568C3F852A5AB3A800A2309D /* DatabaseColumnEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseColumnEncodingStrategyTests.swift; sourceTree = "<group>"; };
@@ -757,6 +762,7 @@
568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = "<group>"; };
568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = "<group>"; };
5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = "<group>"; };
56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = "<group>"; };
56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = "<group>"; };
56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
@@ -772,7 +778,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
5B33E6E34F941B4C839A714F /* (null) in Frameworks */,
5B33E6E34F941B4C839A714F /* BuildFile in Frameworks */,
E158370AAEED49ECD53CE24A /* Pods_GRDBTests.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -939,6 +945,7 @@
56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */,
56419F0424A54093004967E1 /* DatabaseRegionTests.swift */,
56419F0D24A54093004967E1 /* DatabaseSavepointTests.swift */,
56BCA2682E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift */,
568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */,
56419FB424A5409F004967E1 /* DatabaseSnapshotTests.swift */,
56419F1D24A54094004967E1 /* DatabaseSuspensionTests.swift */,
@@ -1023,6 +1030,7 @@
56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */,
56419F2124A54094004967E1 /* RecordEditedTests.swift */,
56419F4824A54097004967E1 /* RecordInitializersTests.swift */,
568515A72E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift */,
568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */,
56419F0C24A54093004967E1 /* RecordMinimalPrimaryKeyRowIDTests.swift */,
56419F6124A54099004967E1 /* RecordMinimalPrimaryKeySingleTests.swift */,
@@ -1386,6 +1394,7 @@
5641A0C424A540A1004967E1 /* MapCursorTests.swift in Sources */,
5641A06E24A540A1004967E1 /* AssociationRowScopeSearchTests.swift in Sources */,
56419FE424A540A1004967E1 /* AssociationHasOneSQLTests.swift in Sources */,
568515A92E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
56419FDE24A540A1004967E1 /* NumericOverflowTests.swift in Sources */,
5641A0E224A540A1004967E1 /* DatabaseAggregateTests.swift in Sources */,
5641A07E24A540A1004967E1 /* DatabaseErrorTests.swift in Sources */,
@@ -1490,6 +1499,7 @@
5641A00024A540A1004967E1 /* StatementArguments+FoundationTests.swift in Sources */,
5641A0BE24A540A1004967E1 /* AssociationHasManyRowScopeTests.swift in Sources */,
5641A07224A540A1004967E1 /* FoundationNSNullTests.swift in Sources */,
56BCA26A2E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
5641A14E24A540A2004967E1 /* DatabaseFunctionTests.swift in Sources */,
5641A0C024A540A1004967E1 /* ValueObservationRecorderTests.swift in Sources */,
5641A08024A540A1004967E1 /* ResultCodeTests.swift in Sources */,
@@ -1636,6 +1646,7 @@
5641A0C524A540A1004967E1 /* MapCursorTests.swift in Sources */,
5641A06F24A540A1004967E1 /* AssociationRowScopeSearchTests.swift in Sources */,
56419FE524A540A1004967E1 /* AssociationHasOneSQLTests.swift in Sources */,
568515A82E66C2EC0082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
56419FDF24A540A1004967E1 /* NumericOverflowTests.swift in Sources */,
5641A0E324A540A1004967E1 /* DatabaseAggregateTests.swift in Sources */,
5641A07F24A540A1004967E1 /* DatabaseErrorTests.swift in Sources */,
@@ -1740,6 +1751,7 @@
5641A00124A540A1004967E1 /* StatementArguments+FoundationTests.swift in Sources */,
5641A0BF24A540A1004967E1 /* AssociationHasManyRowScopeTests.swift in Sources */,
5641A07324A540A1004967E1 /* FoundationNSNullTests.swift in Sources */,
56BCA2692E6C296E00E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
5641A14F24A540A2004967E1 /* DatabaseFunctionTests.swift in Sources */,
5641A0C124A540A1004967E1 /* ValueObservationRecorderTests.swift in Sources */,
5641A08124A540A1004967E1 /* ResultCodeTests.swift in Sources */,
@@ -40,7 +40,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() }
#endif
}
@@ -141,7 +141,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshotPool() }
#endif
}
@@ -177,7 +177,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() }
#endif
}
@@ -213,7 +213,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() }
#endif
}
@@ -250,7 +250,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) }
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() }
#endif
}
@@ -274,7 +274,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase {
try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) }
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() }
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshotPool() }
#endif
}
@@ -122,7 +122,6 @@ class AssociationAggregateTests: GRDBTestCase {
}
}
#if compiler(>=6.1)
func testAggregateWithGroup_swift61() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
@@ -139,7 +138,6 @@ class AssociationAggregateTests: GRDBTestCase {
""")
}
}
#endif
func testAnnotatedWithHasManyDefaultAverage() throws {
let dbQueue = try makeDatabaseQueue()
@@ -296,7 +294,6 @@ class AssociationAggregateTests: GRDBTestCase {
}
}
#if compiler(>=6.1)
func testAnnotatedWithHasManyDefaultMax_Swift61() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
@@ -333,7 +330,6 @@ class AssociationAggregateTests: GRDBTestCase {
XCTAssertEqual(teamInfos[3].maxPlayerScore, 0)
}
}
#endif
func testAnnotatedWithHasManyDefaultMaxJoiningRequired() throws {
// It is important to have an explicit test for this technique because
@@ -53,14 +53,12 @@ private extension QueryInterfaceRequest<Player> {
.order { [teamAlias[Team.Columns.name], $0.name] }
}
#if compiler(>=6.1)
func orderedByTeamName_swift61() -> QueryInterfaceRequest<Player> {
let teamAlias = TableAlias<Team>()
return self
.joining(optional: PlayerWithOptionalTeam.team.aliased(teamAlias))
.order { [teamAlias.name, $0.name] }
}
#endif
}
/// Test support for Decodable records
@@ -190,7 +188,6 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase {
XCTAssertEqual(records[0].team.name, "Reds")
}
#if compiler(>=6.1)
func testRequestRefining_swift61() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player
@@ -212,5 +209,4 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase {
XCTAssertEqual(records[0].team.id, 1)
XCTAssertEqual(records[0].team.name, "Reds")
}
#endif
}
@@ -119,7 +119,6 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
JOIN "b" ON "b"."id" = "a"."bid"
""")
}
#if compiler(>=6.1)
do {
let aAlias = TableAlias<A>()
let request = A
@@ -135,7 +134,6 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
JOIN "b" ON "b"."id" = "a"."bid"
""")
}
#endif
}
}
@@ -178,7 +176,6 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
JOIN "b" ON ("b"."id" = "a"."bid") AND ("b"."id" IN ("a"."id", "b"."id", 42))
""")
}
#if compiler(>=6.1)
do {
let alias = TableAlias<A>()
let request = A
@@ -191,7 +188,6 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
JOIN "b" ON ("b"."id" = "a"."bid") AND ("b"."id" IN ("a"."id", "b"."id", 42))
""")
}
#endif
do {
let request = A.including(required: A.b.filter(key: ["id": 1]))
try assertEqualSQL(db, request, """
@@ -237,7 +233,6 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
WHERE "b"."name" IS NOT NULL
""")
}
#if compiler(>=6.1)
do {
let bAlias = TableAlias<B>()
let request = A
@@ -250,7 +245,6 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
WHERE "b"."name" IS NOT NULL
""")
}
#endif
}
}
@@ -2359,5 +2359,41 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
""")
}
}
do {
// View with custom primary key.
// Existence check is performed on the primary key.
struct SchemaSource: DatabaseSchemaSource {
func columnsForPrimaryKey(_ db: Database, inView view: DatabaseObjectID) throws -> [String]? {
["id"]
}
}
dbConfiguration.schemaSource = SchemaSource()
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "author") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("authorID", .integer)
}
try db.execute(sql: """
CREATE VIEW authorView AS SELECT * FROM author
""")
let association = Book.belongsTo(Table("authorView"), using: ForeignKey(["authorId"], to: ["id"]))
let authorAlias = TableAlias()
let request = Book
.joining(optional: association.aliased(authorAlias))
.filter(!authorAlias.exists)
try assertEqualSQL(db, request, """
SELECT "book".* FROM "book" \
LEFT JOIN "authorView" ON "authorView"."id" = "book"."authorId" \
WHERE "authorView"."id" IS NULL
""")
}
}
}
}
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more