Compare commits

..
3 Commits
Author SHA1 Message Date
Gwendal Roué 45e58e64b7 TO REMOVE: raise SQLiteCustom 2026-11-30 10:06:25 +01:00
Gwendal Roué 8123704c56 TO REMOVE: raise deployment targets 2026-11-30 10:06:25 +01:00
Gwendal Roué b0e1be2e70 v7.12.1 2026-11-30 09:59:54 +01:00
123 changed files with 6580 additions and 443 deletions

No files matched your search

+52 -18
View File
@@ -1,4 +1,4 @@
# https://github.com/actions/runner-images/blob/main/images/macos/xcode-27-arm64-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_27.2.app"
runsOn: xcode-27
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
destination: "platform=macOS"
name: "macOS"
- xcode: "Xcode_27.2.app"
runsOn: xcode-27
destination: "OS=27.2,name=iPhone 17"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
destination: "OS=18.5,name=iPhone 16 Pro"
name: "iOS"
- xcode: "Xcode_27.2.app"
runsOn: xcode-27
destination: "OS=27.2,name=Apple TV 4K (4th generation)"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
destination: "OS=18.5,name=Apple TV"
name: "tvOS"
steps:
- uses: actions/checkout@v5
@@ -66,13 +66,47 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_27.2.app"
runsOn: xcode-27
name: "Xcode 27.2"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
steps:
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_SPM test_install_SPM
SQLCipher3:
name: SQLCipher3
runs-on: ${{ matrix.runsOn }}
env:
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
steps:
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher3Encrypted
SQLCipher4:
name: SQLCipher4
runs-on: ${{ matrix.runsOn }}
env:
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
include:
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
steps:
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
run: make test_framework_SQLCipher4Encrypted
# CustomSQLite:
# name: CustomSQLite
# runs-on: ${{ matrix.runsOn }}
@@ -83,9 +117,9 @@ jobs:
# fail-fast: false
# matrix:
# include:
# - xcode: "Xcode_27.2.app"
# runsOn: xcode-27
# name: "Xcode 27.2"
# - xcode: "Xcode_16.4.app"
# runsOn: macOS-15
# name: "Xcode 16.4"
# steps:
# - uses: actions/checkout@v5
# - name: ${{ matrix.name }}
@@ -100,9 +134,9 @@ jobs:
fail-fast: false
matrix:
include:
- xcode: "Xcode_27.2.app"
runsOn: xcode-27
name: "Xcode 27.2"
- xcode: "Xcode_16.4.app"
runsOn: macOS-15
name: "Xcode 16.4"
steps:
- uses: actions/checkout@v5
- name: ${{ matrix.name }}
+1 -1
View File
@@ -1,3 +1,3 @@
[submodule "SQLiteCustom/src"]
path = SQLiteCustom/src
url = https://github.com/groue/SQLiteLib
url = https://github.com/swiftlyfalling/SQLiteLib.git
+161
View File
@@ -0,0 +1,161 @@
# The OS X Build Environment
# https://docs.travis-ci.com/user/reference/osx/#xcode-version
branches:
only:
- master
- development
language: objective-c
xcode_project: GRDB.xcodeproj
# Caches
cache:
- bundler
- cocoapods
# Custom CocoaPods installation so that Podfile.lock is honored
install:
- bundle install
- bundle exec pod repo update
# Disable the default Travis-CI submodule logic
# The various make commands ensure that the appropriate submodules are retrieved
git:
submodules: false
jobs:
include:
###########################################
## Test GRDB Xcode 11.4
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_GRDBiOS_minTarget
###########################################
## Test GRDB Xcode 12.5
- name: "Test GRDB Xcode 12.5 - GRDBOSX - Swift 5.3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBOSX_maxSwift
- name: "Test GRDB Xcode 12.5 - GRDBOSX - Swift 5.2"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBOSX_minSwift
- name: "Test GRDB Xcode 12.5 - GRDBWatchOS"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBWatchOS
- name: "Test GRDB Xcode 12.5 - GRDBiOS iOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12.5 - GRDBiOS iOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBiOS_minTarget
- name: "Test GRDB Xcode 12.5 - GRDBtvOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12.5 - GRDBtvOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBtvOS_minTarget
- name: "Test GRDB Xcode 12.5 - SPM"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_SPM
###########################################
## Test GRDBCustom Xcode 12.5
- name: "Test GRDBCustom Xcode 12.5 - GRDBOSX"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBCustomSQLiteOSX
- name: "Test GRDBCustom Xcode 12.5 - GRDBiOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
- name: "Test GRDBCustom Xcode 12.5 - GRDBiOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test SQLCipher Xcode 12.5
- name: "Test SQLCipher Xcode 12.5 - SQLCipher 3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_SQLCipher3
- name: "Test SQLCipher Xcode 12.5 - SQLCipher 4"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_SQLCipher4
###########################################
## Test Installation Xcode 12.5
# Manual Install
- name: "Test Installation Xcode 12.5 - Manual Install"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_manual
# Travis is much too slow, and always fail this job
# # CocoaPods Lint
# - name: "Test Installation Xcode 12.5 - CocoaPods Lint"
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode12.5
# script: make test_CocoaPodsLint_GRDB
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.5 - CocoaPods Framework"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.5 - CocoaPods Static"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- name: "Test Installation Xcode 12.5 - SPM Package"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_SPM_Package
# SPM Install
- name: "Test Installation Xcode 12.5 - SPM Package in Xcode Project"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_SPM_Project
# Custom SQLite Install
- name: "Test Installation Xcode 12.5 - Custom SQLite"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_customSQLite
-10
View File
@@ -144,16 +144,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## Unreleased
- **New**: Xcode 27 compatibility
- **New**: Bump custom SQLite build to version 3.54.1
- **New**: `sum(_:orderBy:filter:)` and `total(_:orderBy:filter:)` are available with the system SQLite, from iOS 26, macOS 26, tvOS 26, watchOS 26, and visionOS 26.
- **Breaking Change**: Raise deployment targets for Xcode 27 compatibility: iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 9.0
- **Breaking Change**: Raise minimal Swift version to 6.4 (Xcode 27.0)
- **Breaking Change**: Raise minimal SQLite version to 3.36.0
- **Breaking Change**: Raise minimal SQLCipher version to 4.5.0
## 7.12.1
Released November 30, 2026
+2 -2
View File
@@ -3,11 +3,11 @@ Custom SQLite Builds
By default, GRDB uses the version of SQLite that ships with the target operating system.
**You can build GRDB with a custom build of [SQLite 3.54.1](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.47.2](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](FullTextSearch.md), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver).
GRDB builds SQLite with [groue/SQLiteLib](https://github.com/groue/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
> Warning: The technique described here is not compatible with the Swift Package Manager (SPM). It will create [build issues](https://github.com/groue/GRDB.swift/issues/1709) with SPM companion libraries such as [GRDBQuery](https://github.com/groue/GRDBQuery) or [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting).
@@ -287,7 +287,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 26.6;
IPHONEOS_DEPLOYMENT_TARGET = 17.6;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
@@ -346,7 +346,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 26.6;
IPHONEOS_DEPLOYMENT_TARGET = 17.6;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
@@ -381,7 +381,6 @@
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_APPROACHABLE_CONCURRENCY = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.1;
TARGETED_DEVICE_FAMILY = "1,2";
@@ -411,7 +410,6 @@
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_APPROACHABLE_CONCURRENCY = YES;
SWIFT_EMIT_LOC_STRINGS = YES;
SWIFT_VERSION = 6.1;
TARGETED_DEVICE_FAMILY = "1,2";
@@ -428,7 +426,6 @@
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_APPROACHABLE_CONCURRENCY = YES;
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 6.1;
TARGETED_DEVICE_FAMILY = "1,2";
@@ -446,7 +443,6 @@
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_APPROACHABLE_CONCURRENCY = YES;
SWIFT_EMIT_LOC_STRINGS = NO;
SWIFT_VERSION = 6.1;
TARGETED_DEVICE_FAMILY = "1,2";
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2720"
LastUpgradeVersion = "2600"
version = "1.7">
<BuildAction
parallelizeBuildables = "YES"
@@ -65,12 +65,18 @@
},
"Anonymous" : {
},
"Cancel" : {
},
"Name" : {
},
"New Player" : {
},
"Save" : {
},
"Score" : {
@@ -14,12 +14,10 @@ struct PlayerCreationSheet: View {
.navigationTitle("New Player")
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button(role: .cancel) {
dismiss()
}
Button("Cancel") { dismiss() }
}
ToolbarItem(placement: .confirmationAction) {
Button(role: .confirm) {
Button("Save") {
save()
}
}
@@ -1,6 +1,7 @@
import SwiftUI
struct PlayerEditView: View {
@Environment(\.isPresented) var isPresented
@Environment(\.appDatabase) var appDatabase
@State var form: PlayerForm
var player: Player
@@ -15,9 +16,11 @@ struct PlayerEditView: View {
PlayerFormView(form: $form)
}
.navigationTitle(player.name)
.onDisappear {
// Back button was pressed
save()
.onChange(of: isPresented) {
if !isPresented {
// Back button was pressed
save()
}
}
}
+6 -14
View File
@@ -9,11 +9,11 @@ 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.4']
s.ios.deployment_target = '15.0'
s.osx.deployment_target = '12.0'
s.watchos.deployment_target = '9.0'
s.tvos.deployment_target = '15.0'
s.swift_versions = ['6.1']
s.ios.deployment_target = '13.0'
s.osx.deployment_target = '10.15'
s.watchos.deployment_target = '7.0'
s.tvos.deployment_target = '13.0'
s.default_subspec = 'standard'
s.subspec 'standard' do |ss|
@@ -23,24 +23,16 @@ Pod::Spec.new do |s|
ss.xcconfig = {
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5 -D GRDBFRAMEWORK',
}
ss.pod_target_xcconfig = {
'SWIFT_UPCOMING_FEATURE_NONISOLATED_NONSENDING_BY_DEFAULT' => 'YES',
'SWIFT_UPCOMING_FEATURE_INFER_ISOLATED_CONFORMANCES' => 'YES',
}
end
s.subspec 'SQLCipher' do |ss|
ss.source_files = 'GRDB/**/*.swift', 'Support/SQLCipher_config.h'
ss.framework = 'Foundation'
ss.dependency 'SQLCipher', '>= 4.5.0'
ss.dependency 'SQLCipher', '>= 3.4.2'
ss.xcconfig = {
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_HAS_CODEC -D GRDBCIPHER -D SQLITE_ENABLE_FTS5',
'OTHER_CFLAGS' => '$(inherited) -DSQLITE_HAS_CODEC -DGRDBCIPHER -DSQLITE_ENABLE_FTS5',
'GCC_PREPROCESSOR_DEFINITIONS' => '$(inherited) SQLITE_HAS_CODEC=1 GRDBCIPHER=1 SQLITE_ENABLE_FTS5=1'
}
ss.pod_target_xcconfig = {
'SWIFT_UPCOMING_FEATURE_NONISOLATED_NONSENDING_BY_DEFAULT' => 'YES',
'SWIFT_UPCOMING_FEATURE_INFER_ISOLATED_CONFORMANCES' => 'YES',
}
end
end
+2 -6
View File
@@ -7,7 +7,7 @@
objects = {
/* Begin PBXBuildFile section */
567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Public, ); }; };
567DAF1C1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
56E5D7FE1B4D422E00430942 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = DC3773F319C8CBB3004FCF85 /* GRDB.framework */; };
DC2393C81ABE35F8003FF113 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; };
DC3773F919C8CBB3004FCF85 /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = DC3773F819C8CBB3004FCF85 /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; };
@@ -217,7 +217,7 @@
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 2720;
LastUpgradeCheck = 2600;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
56E5D7F81B4D422D00430942 = {
@@ -410,7 +410,6 @@
DEAD_CODE_STRIPPING = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
@@ -469,7 +468,6 @@
DEAD_CODE_STRIPPING = YES;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
@@ -504,7 +502,6 @@
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
INFOPLIST_FILE = Support/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -538,7 +535,6 @@
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
INFOPLIST_FILE = Support/Info.plist;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2720"
LastUpgradeVersion = "2600"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+5 -5
View File
@@ -92,8 +92,8 @@ public struct Configuration: Sendable {
/// The default configuration label is nil.
public var label: String?
/// A boolean value indicating whether SQLite interprets double-quoted
/// strings as string literals when they do not match any
/// A boolean value indicating whether SQLite 3.29+ interprets
/// double-quoted strings as string literals when they do not match any
/// valid identifier.
///
/// The default and recommended value is false:
@@ -105,9 +105,9 @@ public struct Configuration: Sendable {
/// """)
/// ```
///
/// When true, double-quoted strings that do not match any valid
/// identifier are interpreted as string literals, as in the
/// example below. This is an SQLite
/// When true, or before SQLite version 3.29.0, double-quoted strings that
/// do not match any valid identifier are interpreted as string literals,
/// as in the example below. This is an SQLite
/// [misfeature](https://sqlite.org/quirks.html#double_quoted_string_literals_are_accepted):
///
/// ```swift
+54 -7
View File
@@ -160,7 +160,7 @@ extension Database {
}
#else
/// Returns information about a table or a view
@available(iOS 15.4, macOS 12.4, tvOS 15.4, *) // SQLite 3.37+
@available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) // SQLite 3.37+
func table(_ tableName: String) throws -> TableInfo? {
for schemaID in try fetchSchemaIdentifiers() {
if let result = try table(for: DatabaseObjectID(name: tableName, schemaID: schemaID)) {
@@ -171,7 +171,7 @@ extension Database {
}
/// Returns information about a table or a view
@available(iOS 15.4, macOS 12.4, tvOS 15.4, *) // SQLite 3.37+
@available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) // SQLite 3.37+
func table(for table: DatabaseObjectID) throws -> TableInfo? {
try _table(for: table)
}
@@ -582,7 +582,7 @@ extension Database {
return try self.table(for: table)!.isWithoutRowIDTable == false
}
#else
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, *) { // SQLite 3.37+
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
return try self.table(for: table)!.isWithoutRowIDTable == false
}
#endif
@@ -1028,12 +1028,58 @@ extension Database {
/// Fetches the columns in the database table identified by `table`, or
/// returns nil if the database schema does not contain that table.
///
/// This method relies entirely on SQLite schema introspection. It
/// returns all columns, including
/// This method relies entirely on SQLite schema introspection. Starting with
/// SQLite 3.26.0, it returns all columns, including
/// [generated columns](https://www.sqlite.org/gencol.html) and
/// [hidden columns](https://www.sqlite.org/vtab.html#hiddencol).
func fetchPrimitiveColumns(in table: DatabaseObjectID) throws -> [ColumnInfo]? {
let columnInfoQuery = "PRAGMA \(table.schemaID.name).table_xinfo(\(table.name.quotedDatabaseIdentifier))"
// https://www.sqlite.org/pragma.html
//
// > PRAGMA database.table_info(table-name);
// >
// > This pragma returns one row for each column in the named table.
// > Columns in the result set include the column name, data type,
// > whether or not the column can be NULL, and the default value for
// > the column. The "pk" column in the result set is zero for columns
// > that are not part of the primary key, and is the index of the
// > column in the primary key for columns that are part of the primary
// > key.
//
// sqlite> CREATE TABLE players (
// id INTEGER PRIMARY KEY,
// firstName TEXT,
// lastName TEXT);
//
// sqlite> PRAGMA table_info("players");
// cid | name | type | notnull | dflt_value | pk |
// 0 | id | INTEGER | 0 | NULL | 1 |
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
//
//
// PRAGMA table_info does not expose hidden and generated columns. For
// that, we need PRAGMA table_xinfo, introduced in SQLite 3.26.0:
// https://sqlite.org/releaselog/3_26_0.html
//
// > PRAGMA schema.table_xinfo(table-name);
//
// > This pragma returns one row for each column in the named table,
// > including hidden columns in virtual tables. The output is the same
// > as for PRAGMA table_info except that hidden columns are shown
// > rather than being omitted.
//
// sqlite> PRAGMA table_xinfo("players");
// cid | name | type | notnull | dflt_value | pk | hidden
// 0 | id | INTEGER | 0 | NULL | 1 | 0
// 1 | firstName | TEXT | 0 | NULL | 0 | 0
// 2 | lastName | TEXT | 0 | NULL | 0 | 0
let columnInfoQuery: String
if sqlite3_libversion_number() < 3026000 {
columnInfoQuery = "PRAGMA \(table.schemaID.name).table_info(\(table.name.quotedDatabaseIdentifier))"
} else {
// Use PRAGMA table_xinfo so that we can load generated columns
columnInfoQuery = "PRAGMA \(table.schemaID.name).table_xinfo(\(table.name.quotedDatabaseIdentifier))"
}
let columns = try ColumnInfo
.fetchAll(self, sql: columnInfoQuery)
.sorted(by: { $0.cid < $1.cid })
@@ -1249,10 +1295,11 @@ public struct DatabaseObjectID: Hashable, Sendable {
///
/// Related SQLite documentation:
///
/// - [pragma `table_info`](https://www.sqlite.org/pragma.html#pragma_table_info)
/// - [pragma `table_xinfo`](https://www.sqlite.org/pragma.html#pragma_table_xinfo)
public struct ColumnInfo: FetchableRecord, Sendable {
let cid: Int
let hidden: Int
let hidden: Int?
/// The column name.
public let name: String
+2 -2
View File
@@ -92,8 +92,8 @@ extension Database {
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
/// - parameter sql: An SQL string.
/// - parameter prepFlags: Flags for `sqlite3_prepare_v3` see
/// <http://www.sqlite.org/c3ref/prepare.html>.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see <http://www.sqlite.org/c3ref/prepare.html>)
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
func makeStatement(sql: String, prepFlags: CUnsignedInt) throws -> Statement {
+1 -1
View File
@@ -334,7 +334,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// // Prints, for example, "3048000"
/// print(Database.sqliteLibVersionNumber)
/// ```
@inline(always)
@inline(__always)
@inlinable
public static var sqliteLibVersionNumber: CInt {
sqlite3_libversion_number()
+1 -1
View File
@@ -501,7 +501,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
/// }
/// ```
public protocol DatabaseAggregate: SendableMetatype {
public protocol DatabaseAggregate: GRDBSendableMetatype {
/// Creates an aggregate.
///
/// A new instance is created for each aggregation.
+4
View File
@@ -335,6 +335,7 @@ extension DatabasePool: DatabaseReader {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
@@ -416,6 +417,7 @@ extension DatabasePool: DatabaseReader {
}
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
@@ -782,6 +784,7 @@ extension DatabasePool: DatabaseReader {
extension DatabasePool: DatabaseWriter {
// MARK: - Writing in Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
try writer.sync(updates)
}
@@ -792,6 +795,7 @@ extension DatabasePool: DatabaseWriter {
try await writer.execute(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
guard let readerPool else {
throw DatabaseError.connectionIsClosed()
+4
View File
@@ -224,6 +224,7 @@ extension DatabaseQueue: DatabaseReader {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
try writer.sync { db in
try db.isolated(readOnly: true) {
@@ -271,6 +272,7 @@ extension DatabaseQueue: DatabaseReader {
}
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
try writer.sync(value)
}
@@ -389,6 +391,7 @@ extension DatabaseQueue: DatabaseWriter {
}
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
try writer.sync(updates)
}
@@ -399,6 +402,7 @@ extension DatabaseQueue: DatabaseWriter {
try await writer.execute(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
try writer.sync(updates)
}
+5
View File
@@ -185,6 +185,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database.
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func read<T>(_ value: (Database) throws -> T) throws -> T
/// Executes read-only database operations, and returns their result after
@@ -282,6 +283,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
/// - parameter value: A closure which accesses the database.
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
/// would happen while establishing the database access.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T
/// Executes database operations, and returns their result after they have
@@ -644,6 +646,7 @@ extension AnyDatabaseReader: DatabaseReader {
base.interrupt()
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
try base.read(value)
}
@@ -660,6 +663,7 @@ extension AnyDatabaseReader: DatabaseReader {
base.asyncRead(value)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
try base.unsafeRead(value)
}
@@ -737,6 +741,7 @@ extension DatabaseSnapshotReader {
}
// There is no such thing as an unsafe access to a snapshot.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
try read(value)
}
+2 -2
View File
@@ -202,7 +202,7 @@ extension DatabasePublishers {
}
public func receive<S>(subscriber: S)
where S: Subscriber & SendableMetatype,
where S: Subscriber & GRDBSendableMetatype,
Failure == S.Failure,
Output == S.Input
{
@@ -216,7 +216,7 @@ extension DatabasePublishers {
private class DatabaseRegionSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber & SendableMetatype,
where Downstream: Subscriber & GRDBSendableMetatype,
Downstream.Failure == Error,
Downstream.Input == Database
{
+2
View File
@@ -153,6 +153,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
// MARK: - Reading from Database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
try reader.sync(block)
}
@@ -169,6 +170,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
reader.async { value(.success($0)) }
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
try reader.sync(value)
}
+1
View File
@@ -272,6 +272,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
readerPool?.forEach { $0.interrupt() }
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
guard let readerPool else {
+2 -1
View File
@@ -237,7 +237,8 @@ extension DatabaseValue: StatementBinding {
extension DatabaseValue: Sendable { }
extension DatabaseValue.Storage: Sendable { }
// @unchecked Sendable because Data is not Sendable in all target OS
extension DatabaseValue.Storage: @unchecked Sendable { }
// MARK: - Hashable & Equatable
+50
View File
@@ -97,6 +97,7 @@ public protocol DatabaseWriter: DatabaseReader {
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
/// Executes database operations, and returns their result after they have
@@ -169,6 +170,7 @@ public protocol DatabaseWriter: DatabaseReader {
///
/// - parameter updates: A closure which accesses the database.
/// - throws: The error thrown by `updates`.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T
/// Executes database operations, and returns their result after they have
@@ -410,6 +412,7 @@ extension DatabaseWriter {
/// - throws: The error thrown by `updates`, or any ``DatabaseError`` that
/// would happen while establishing the database access or committing
/// the transaction.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func write<T>(_ updates: (Database) throws -> T) throws -> T {
try writeWithoutTransaction { db in
var result: T?
@@ -524,6 +527,7 @@ extension DatabaseWriter {
// MARK: - Erasing the content of the database
/// Erase the database: delete all content, drop all tables, etc.
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func erase() throws {
try barrierWriteWithoutTransaction { try $0.erase() }
}
@@ -534,10 +538,22 @@ extension DatabaseWriter {
/// disk space.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html>
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func vacuum() throws {
try writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
// VACUUM INTO was introduced in SQLite 3.27.0:
// https://www.sqlite.org/releaselog/3_27_0.html
//
// Old versions of SQLCipher won't have it, but I don't know how to perform
// availability checks that depend on the version of the SQLCipher CocoaPod
// chosen by the application. So let's just have the method fail at runtime.
//
// 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 || SQLITE_HAS_CODEC
/// Creates a new database file at the specified path with a minimum
/// amount of disk space.
///
@@ -547,11 +563,27 @@ extension DatabaseWriter {
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
///
/// - Parameter filePath: file path for new database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func vacuum(into filePath: String) throws {
try writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
}
}
#else
/// Creates a new database file at the specified path with a minimum
/// amount of disk space.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
///
/// - Parameter filePath: file path for new database
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
@available(iOS 14, macOS 10.16, tvOS 14, *)
public func vacuum(into filePath: String) throws {
try writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
}
}
#endif
// MARK: - Database Observation
@@ -634,6 +666,7 @@ extension DatabaseWriter {
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Creates a new database file at the specified path with a minimum
/// amount of disk space.
///
@@ -648,6 +681,19 @@ extension DatabaseWriter {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
}
}
#else
/// Creates a new database file at the specified path with a minimum
/// amount of disk space.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_vacuum.html#vacuuminto>
///
/// - Parameter filePath: file path for new database
public func vacuum(into filePath: String) async throws {
try await writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
}
}
#endif
}
#if canImport(Combine)
@@ -834,6 +880,7 @@ extension AnyDatabaseWriter: DatabaseReader {
base.interrupt()
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func read<T>(_ value: (Database) throws -> T) throws -> T {
try base.read(value)
}
@@ -850,6 +897,7 @@ extension AnyDatabaseWriter: DatabaseReader {
base.asyncRead(value)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
try base.unsafeRead(value)
}
@@ -883,6 +931,7 @@ extension AnyDatabaseWriter: DatabaseReader {
}
extension AnyDatabaseWriter: DatabaseWriter {
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
try base.writeWithoutTransaction(updates)
}
@@ -893,6 +942,7 @@ extension AnyDatabaseWriter: DatabaseWriter {
try await base.writeWithoutTransaction(updates)
}
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
try base.barrierWriteWithoutTransaction(updates)
}
+4 -4
View File
@@ -321,8 +321,8 @@ extension Row {
// MARK: - Extracting Values
/// Fatal errors if index is out of bounds
@inline(always)
@inlinable
@inline(__always)
@usableFromInline
/* private */ func _checkIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line)
}
@@ -425,7 +425,7 @@ extension Row {
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
/// let name: String? = row[0] // nil
/// ```
@inline(always)
@inline(__always)
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
try! decode(Value.self, atIndex: index)
@@ -1253,7 +1253,7 @@ extension Row {
/// ```
///
/// - throws: Any error that happens during the decoding.
@inline(always)
@inline(__always)
@inlinable
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type = Value.self,
+2 -2
View File
@@ -163,8 +163,8 @@ public final class Statement {
/// containing SQL.
/// - parameter statementEnd: Upon success, the pointer to the next
/// statement in the C string.
/// - parameter prepFlags: Flags for `sqlite3_prepare_v3` see
/// <http://www.sqlite.org/c3ref/prepare.html>.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see <http://www.sqlite.org/c3ref/prepare.html>)
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
+1 -1
View File
@@ -213,7 +213,7 @@ final class StatementAuthorizer {
private func insertUpdateEventKind(tableName: String, columnName: String) {
for (index, eventKind) in databaseEventKinds.enumerated() {
if case let .update(t, columnNames) = eventKind, t == tableName {
if case .update(let t, let columnNames) = eventKind, t == tableName {
var columnNames = columnNames
columnNames.insert(columnName)
databaseEventKinds[index] = .update(tableName: tableName, columnNames: columnNames)
+4 -4
View File
@@ -126,7 +126,7 @@ public protocol StatementColumnConvertible {
extension StatementColumnConvertible {
// `Optional` overrides this default behavior.
/// Default implementation fails on decoding NULL.
@inline(always)
@inline(__always)
@inlinable
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
@@ -153,7 +153,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
context: context())
}
@inline(always)
@inline(__always)
@inlinable
static func fastDecode(
fromRow row: Row,
@@ -170,7 +170,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
return try row.fastDecode(Self.self, atUncheckedIndex: index)
}
@inline(always)
@inline(__always)
@inlinable
static func fastDecode(
fromStatement sqliteStatement: SQLiteStatement,
@@ -186,7 +186,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
}
// Support for Decodable
@inline(always)
@inline(__always)
@inlinable
static func fastDecodeIfPresent(
fromRow row: Row,
@@ -79,7 +79,7 @@ extension DatabaseDateComponents: StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
+1 -1
View File
@@ -132,7 +132,7 @@ extension Date: StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
+1 -1
View File
@@ -47,7 +47,7 @@ extension Decimal: DatabaseValueConvertible {
/// Decimal adopts StatementColumnConvertible
extension Decimal: StatementColumnConvertible {
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
+1 -1
View File
@@ -84,7 +84,7 @@ extension UUID: DatabaseValueConvertible {
}
extension UUID: StatementColumnConvertible {
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
switch sqlite3_column_type(sqliteStatement, index) {
@@ -39,7 +39,7 @@ extension StatementBinding where Self: RawRepresentable, Self.RawValue: Statemen
/// // adopt StatementColumnConvertible:
/// extension Color: StatementColumnConvertible { }
extension StatementColumnConvertible where Self: RawRepresentable, Self.RawValue: StatementColumnConvertible {
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
guard let rawValue = RawValue(sqliteStatement: sqliteStatement, index: index) else {
@@ -85,7 +85,7 @@ extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvert
}
extension Optional: StatementColumnConvertible where Wrapped: StatementColumnConvertible {
@inline(always)
@inline(__always)
@inlinable
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
if let value = Wrapped.fromStatement(sqliteStatement, atUncheckedIndex: index) {
@@ -117,7 +117,7 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
@@ -156,7 +156,7 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
@@ -195,7 +195,7 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
@@ -234,7 +234,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
@@ -316,7 +316,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
@@ -355,7 +355,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
@@ -394,7 +394,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
@@ -433,7 +433,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
@@ -472,7 +472,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inline(always)
@inline(__always)
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
+1 -2
View File
@@ -1028,8 +1028,7 @@ final class TransactionObservation {
guard let observer else {
return false
}
return !observer.databaseEventObservationStrategy.requiresDatabaseEventKind ||
observer.observes(eventsOfKind: eventKind)
return !observer.databaseEventObservationStrategy.requiresDatabaseEventKind || observer.observes(eventsOfKind: eventKind)
}
func statementObservation(for statement: Statement) -> StatementObservation? {
@@ -229,5 +229,11 @@ Task {
}
```
## Topics
### Supporting Types
- ``GRDBSendableMetatype``
[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide/
+1 -1
View File
@@ -334,7 +334,7 @@ extension Database {
return table.kind == .shadow
}
#else
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, *) { // SQLite 3.37+
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
guard let table = try table(tableName) else {
// Not a table
return false
+7
View File
@@ -40,9 +40,16 @@ public struct FTS3 {
/// the `remove_diacritics=1` tokenizer argument.
case removeLegacy
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Remove diacritics from Latin script characters. This option matches
/// the `remove_diacritics=2` tokenizer argument.
case remove
#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+
case remove
#endif
}
/// Creates an FTS3 module.
+5
View File
@@ -95,8 +95,13 @@ public struct FTS3TokenizerDescriptor: Sendable {
break
case .keep:
arguments.append("remove_diacritics=0")
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
case .remove:
arguments.append("remove_diacritics=2")
#else
case .remove:
arguments.append("remove_diacritics=2")
#endif
}
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with
+10 -1
View File
@@ -63,9 +63,18 @@ public struct FTS5 {
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=1" tokenizer argument.
case removeLegacy
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=2" tokenizer argument.
/// option matches the raw "remove_diacritics=2" tokenizer argument,
/// available from SQLite 3.27.0
case remove
#else
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=2" tokenizer argument,
/// available from SQLite 3.27.0
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.27+
case remove
#endif
}
/// Creates an FTS5 module.
+5
View File
@@ -182,8 +182,13 @@ public struct FTS5TokenizerDescriptor: Sendable {
break
case .keep:
components.append(contentsOf: ["remove_diacritics", "0"])
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
case .remove:
components.append(contentsOf: ["remove_diacritics", "2"])
#else
case .remove:
components.append(contentsOf: ["remove_diacritics", "2"])
#endif
}
if !categories.isEmpty {
components.append("categories")
-8
View File
@@ -18,11 +18,3 @@ extension DatabasePool {
}
// swiftlint:enable all
// Fixits for changes introduced by GRDB 8.0.0
// swiftlint:disable all
@available(*, unavailable, renamed: "SendableMetatype")
public typealias GRDBSendableMetatype = SendableMetatype
// swiftlint:enable all
+7 -7
View File
@@ -308,7 +308,7 @@ extension SQLJSONExpressible {
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
/// or a JSON object field label, or an array index.
@available(iOS 16, macOS 13.2, tvOS 17, *) // SQLite 3.38+
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
public subscript(_ path: some SQLExpressible) -> SQLExpression {
.binary(.jsonExtractSQL, sqlExpression, path.sqlExpression)
}
@@ -340,7 +340,7 @@ extension SQLJSONExpressible {
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public func jsonExtract(atPath path: some SQLExpressible) -> SQLExpression {
Database.jsonExtract(self, atPath: path)
}
@@ -366,7 +366,7 @@ extension SQLJSONExpressible {
/// Related SQL documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public func jsonExtract(
atPaths paths: some Collection<some SQLExpressible>
) -> SQLExpression {
@@ -401,7 +401,7 @@ extension SQLJSONExpressible {
///
/// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments),
/// or a JSON object field label, or an array index.
@available(iOS 16, macOS 13.2, tvOS 17, *) // SQLite 3.38+
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
public func jsonRepresentation(atPath path: some SQLExpressible) -> SQLExpression {
.binary(.jsonExtractJSON, sqlExpression, path.sqlExpression)
}
@@ -421,7 +421,7 @@ extension SQLJSONExpressible {
// /// ```
// ///
// /// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
// @available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
// @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
// public func jsonPatch(
// with patch: some SQLExpressible)
// -> ColumnAssignment
@@ -444,7 +444,7 @@ extension SQLJSONExpressible {
// ///
// /// - Parameters:
// /// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
// @available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
// @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
// public func jsonRemove(atPath path: some SQLExpressible) -> ColumnAssignment {
// .init(columnName: name, value: Database.jsonRemove(self, atPath: path))
// }
@@ -464,7 +464,7 @@ extension SQLJSONExpressible {
// ///
// /// - Parameters:
// /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
// @available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
// @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
// public func jsonRemove(
// atPaths paths: some Collection<some SQLExpressible>
// ) -> ColumnAssignment {
+20 -20
View File
@@ -802,7 +802,7 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jmini>
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func json(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON", [value.sqlExpression])
}
@@ -817,7 +817,7 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonArray(
_ values: some Collection<some SQLExpressible>
) -> SQLExpression {
@@ -834,7 +834,7 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonArray(
_ values: some Collection<any SQLExpressible>
) -> SQLExpression {
@@ -852,7 +852,7 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarraylen>
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonArrayLength(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_ARRAY_LENGTH", [value.sqlExpression])
}
@@ -872,7 +872,7 @@ extension Database {
/// - Parameters:
/// - value: A JSON array.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonArrayLength(
_ value: some SQLExpressible,
atPath path: some SQLExpressible)
@@ -895,7 +895,7 @@ extension Database {
/// - Parameters:
/// - value: A JSON value.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_EXTRACT", [value.sqlExpression, path.sqlExpression])
}
@@ -914,7 +914,7 @@ extension Database {
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonExtract(
_ value: some SQLExpressible,
atPaths paths: some Collection<some SQLExpressible>
@@ -937,7 +937,7 @@ extension Database {
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonInsert(
_ value: some SQLExpressible,
_ assignments: some Collection<(key: String, value: any SQLExpressible)>
@@ -962,7 +962,7 @@ extension Database {
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonReplace(
_ value: some SQLExpressible,
_ assignments: some Collection<(key: String, value: any SQLExpressible)>
@@ -987,7 +987,7 @@ extension Database {
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonSet(
_ value: some SQLExpressible,
_ assignments: some Collection<(key: String, value: any SQLExpressible)>
@@ -1020,7 +1020,7 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jobj>
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonObject(
_ elements: some Collection<(key: String, value: any SQLExpressible)>
) -> SQLExpression {
@@ -1039,7 +1039,7 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonPatch(
_ value: some SQLExpressible,
with patch: some SQLExpressible)
@@ -1062,7 +1062,7 @@ extension Database {
/// - Parameters:
/// - value: A JSON value.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_REMOVE", [value.sqlExpression, path.sqlExpression])
}
@@ -1081,7 +1081,7 @@ extension Database {
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonRemove(
_ value: some SQLExpressible,
atPaths paths: some Collection<some SQLExpressible>
@@ -1099,7 +1099,7 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jtype>
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonType(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_TYPE", [value.sqlExpression])
}
@@ -1118,7 +1118,7 @@ extension Database {
/// - Parameters:
/// - value: A JSON value.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonType(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSON_TYPE", [value.sqlExpression, path.sqlExpression])
}
@@ -1133,7 +1133,7 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jvalid>
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_VALID", [value.sqlExpression])
}
@@ -1151,7 +1151,7 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jquote>
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonQuote(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_QUOTE", [value.sqlExpression.jsonBuilderExpression])
}
@@ -1176,7 +1176,7 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonGroupArray(
_ value: some SQLExpressible,
filter: (any SQLSpecificExpressible)? = nil)
@@ -1217,7 +1217,7 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgroupobject>
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
public static func jsonGroupObject(
key: some SQLExpressible,
value: some SQLExpressible,
@@ -646,6 +646,7 @@ extension QueryInterfaceRequest {
// MARK: - Batch Delete and Fetch
extension QueryInterfaceRequest {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Returns a `DELETE RETURNING` prepared statement.
///
/// For example:
@@ -828,6 +829,196 @@ extension QueryInterfaceRequest {
return try RowDecoder.ID.fetchSet(statement)
}
#else
/// Returns a `DELETE RETURNING` prepared statement.
///
/// For example:
///
/// ```swift
/// // Delete all players and return their names
/// // DELETE FROM player RETURNING name
/// let request = Player.all()
/// let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")])
/// let deletedNames = try String.fetchSet(statement)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter selection: The returned columns (must not be empty).
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `selection` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchStatement(
_ db: Database,
selection: [any SQLSelectable])
throws -> Statement
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection)
}
/// Returns a `DELETE RETURNING` prepared statement.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let name = Column("name")
/// }
/// }
///
/// // Delete all players and return their names
/// // DELETE FROM player RETURNING name
/// let request = Player.all()
/// let statement = try request.deleteAndFetchStatement(db, select: { [$0.name] })
/// let deletedNames = try String.fetchSet(statement)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter select: A closure that returns the returned columns
/// (must not be empty).
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `select` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchStatement(
_ db: Database,
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try deleteAndFetchStatement(db, selection: select(RowDecoder.databaseComponents))
}
/// Returns a cursor over the records deleted by a
/// `DELETE RETURNING` statement.
///
/// For example:
///
/// ```swift
/// // Fetch all deleted players
/// // DELETE FROM player RETURNING *
/// let request = Player.all()
/// let players = try request.deleteAndFetchCursor(db)
/// while let player = try players.next() {
/// print("Player \(player) was deleted")
/// }
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A ``RecordCursor`` over the deleted records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchCursor(_ db: Database)
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
let statement = try deleteAndFetchStatement(db, selection: RowDecoder.databaseSelection)
return try RowDecoder.fetchCursor(statement)
}
/// Executes a `DELETE RETURNING` statement and returns the array of
/// deleted records.
///
/// For example:
///
/// ```swift
/// // Fetch all deleted players
/// // DELETE FROM player RETURNING *
/// let request = Player.all()
/// let deletedPlayers = try request.deleteAndFetchAll(db)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: An array of deleted records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchAll(_ db: Database)
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try Array(deleteAndFetchCursor(db))
}
/// Executes a `DELETE RETURNING` statement and returns the set of
/// deleted records.
///
/// For example:
///
/// ```swift
/// // Fetch all deleted players
/// // DELETE FROM player RETURNING *
/// let request = Player.all()
/// let deletedPlayers = try request.deleteAndFetchSet(db)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A set of deleted records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchSet(_ db: Database)
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try Set(deleteAndFetchCursor(db))
}
/// Executes a `DELETE RETURNING` statement and returns the set of
/// deleted ids.
///
/// For example:
///
/// ```swift
/// // Fetch the ids of deleted players
/// // DELETE FROM player RETURNING id
/// let request = Player.all()
/// let deletedPlayerIds = try request.deleteAndFetchIds(db)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - returns: A set of deleted ids.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func deleteAndFetchIds(_ db: Database)
throws -> Set<RowDecoder.ID>
where RowDecoder: TableRecord & Identifiable,
RowDecoder.ID: Hashable & DatabaseValueConvertible & StatementColumnConvertible
{
let primaryKey = try db.primaryKey(RowDecoder.databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Fetching id requires a single-column primary key in the table \(databaseTableName)")
let statement = try deleteAndFetchStatement(db, selection: [Column(primaryKey.columns[0])])
return try RowDecoder.ID.fetchSet(statement)
}
#endif
}
// MARK: - Batch Update
@@ -985,6 +1176,7 @@ extension QueryInterfaceRequest {
// MARK: - Batch Update and Fetch
extension QueryInterfaceRequest {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Returns an `UPDATE RETURNING` prepared statement.
///
/// For example:
@@ -1025,7 +1217,7 @@ extension QueryInterfaceRequest {
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
select: (DatabaseComponents) throws -> [any SQLSelectable]
select: (DatabaseComponents) -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
@@ -1307,6 +1499,338 @@ extension QueryInterfaceRequest {
{
try Set(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
}
#else
/// Returns an `UPDATE RETURNING` prepared statement.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// // Fetch all updated scores
/// // UPDATE player SET score = score + 10 RETURNING score
/// let request = Player.all()
/// let statement = try request.updateAndFetchStatement(db) {
/// [$0.score += 10]
/// } select: {
/// [$0.score]
/// }
/// let updatedScores = try Int.fetchAll(statement)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments (must not be empty).
/// - parameter select: A closure that returns the returned columns
/// (must not be empty).
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The results of `select` and `assignments`
/// are not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment],
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> Statement
where RowDecoder: TableRecord
{
try updateAndFetchStatement(
db,
onConflict: conflictResolution,
assignments(RowDecoder.databaseComponents),
selection: select(RowDecoder.databaseComponents))
}
/// Returns an `UPDATE RETURNING` prepared statement.
///
/// For example:
///
/// ```swift
/// // Fetch all updated scores
/// // UPDATE player SET score = score + 10 RETURNING score
/// let request = Player.all()
/// let statement = try request.updateAndFetchStatement(
/// db, [Column("score") += 10],
/// selection: [Column("score")])
/// let updatedScores = try Int.fetchAll(statement)
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments
/// (must not be empty).
/// - parameter selection: The returned columns (must not be empty).
/// - returns: A prepared statement.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `selection` and `assignments` are not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchStatement(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment],
selection: [any SQLSelectable])
throws -> Statement
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate
guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement(
db,
conflictResolution: conflictResolution,
assignments: assignments,
selection: selection)
else {
fatalError("Invalid empty assignments")
}
return updateStatement
}
/// Returns a cursor over the records updated by an
/// `UPDATE RETURNING` statement.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let players = try request.updateAndFetchCursor(db) { [$0.score += 10] }
/// while let player = try players.next() {
/// print("Player \(player) was updated")
/// }
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments.
/// - returns: A cursor over the updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchCursor(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
}
/// Returns a cursor over the records updated by an
/// `UPDATE RETURNING` statement.
///
/// For example:
///
/// ```swift
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let players = try request.updateAndFetchCursor(db, [Column("score") += 10])
/// while let player = try players.next() {
/// print("Player \(player) was updated")
/// }
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments.
/// - returns: A cursor over the updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchCursor(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> RecordCursor<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord
{
let statement = try updateAndFetchStatement(
db,
onConflict: conflictResolution,
assignments,
selection: RowDecoder.databaseSelection)
return try RowDecoder.fetchCursor(statement)
}
/// Executes an `UPDATE RETURNING` statement and returns the array of
/// updated records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let updatedPlayers = try request.updateAndFetchAll(db) { [$0.score += 10] }
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments.
/// - returns: An array of updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
}
/// Executes an `UPDATE RETURNING` statement and returns the array of
/// updated records.
///
/// For example:
///
/// ```swift
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let updatedPlayers = try request.updateAndFetchAll(db, [Column("score") += 10])
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments.
/// - returns: An array of updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchAll(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> [RowDecoder]
where RowDecoder: FetchableRecord & TableRecord
{
try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
}
/// Executes an `UPDATE RETURNING` statement and returns the set of
/// updated records.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let updatedPlayers = try request.updateAndFetchSet(db) { [$0.score += 10] }
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: A closure that returns an array of
/// column assignments.
/// - returns: A set of updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: The result of `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
) throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents))
}
/// Executes an `UPDATE RETURNING` statement and returns the set of
/// updated records.
///
/// For example:
///
/// ```swift
/// // Fetch all updated players
/// // UPDATE player SET score = score + 10 RETURNING *
/// let request = Player.all()
/// let updatedPlayers = try request.updateAndFetchSet(db, [Column("score") += 10])
/// ```
///
/// - important: Make sure you check the documentation of the `RETURNING`
/// clause, which describes important limitations and caveats:
/// <https://www.sqlite.org/lang_returning.html#limitations_and_caveats>.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution.
/// - parameter assignments: An array of column assignments.
/// - returns: A set of updated records.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
/// - precondition: `assignments` is not empty.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetchSet(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
_ assignments: [ColumnAssignment])
throws -> Set<RowDecoder>
where RowDecoder: FetchableRecord & TableRecord & Hashable
{
try Set(updateAndFetchCursor(db, onConflict: conflictResolution, assignments))
}
#endif
}
// MARK: - ColumnAssignment
+23 -6
View File
@@ -525,11 +525,11 @@ public struct SQLExpression: Sendable {
static let jsonExtractSQL = BinaryOperator("->>")
#else
/// The `->` SQL operator
@available(iOS 16, macOS 13.2, tvOS 17, *) // SQLite 3.38+
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
static let jsonExtractJSON = BinaryOperator("->", isJSONValue: true)
/// The `->>` SQL operator
@available(iOS 16, macOS 13.2, tvOS 17, *) // SQLite 3.38+
@available(iOS 16, macOS 13.2, tvOS 17, watchOS 9, *) // SQLite 3.38+
static let jsonExtractSQL = BinaryOperator("->>")
#endif
}
@@ -2021,7 +2021,7 @@ struct SQLAggregateFunctionInvocation {
var arguments: [SQLExpression]
var isDistinct = false
var ordering: SQLOrdering? // SQLite 3.44.0+
var filter: SQLExpression?
var filter: SQLExpression? // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+
/// A boolean value indicating if a function is known to return a
/// JSON value.
@@ -2139,7 +2139,7 @@ extension SQLExpression {
}
}
#else
@available(iOS 16, tvOS 17, *) // SQLite 3.38+ with exceptions for macOS
@available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS
/// Returns an expression suitable in JSON building contexts.
var jsonBuilderExpression: SQLExpression {
switch preferredJSONInterpretation {
@@ -2205,6 +2205,7 @@ extension SQLExpressible where Self == Column {
/// See also JSON functions in <doc:JSON>.
///
/// - ``abs(_:)-5l6xp``
/// - ``average(_:)``
/// - ``average(_:filter:)``
/// - ``capitalized``
/// - ``cast(_:as:)-1dmu3``
@@ -2220,13 +2221,15 @@ extension SQLExpressible where Self == Column {
/// - ``localizedUppercased``
/// - ``lowercased``
/// - ``min(_:_:_:)``
/// - ``min(_:)``
/// - ``min(_:filter:)``
/// - ``max(_:_:_:)``
/// - ``max(_:)``
/// - ``max(_:filter:)``
/// - ``sum(_:)``
/// - ``sum(_:filter:)``
/// - ``sum(_:orderBy:filter:)``
/// - ``total(_:)``
/// - ``total(_:filter:)``
/// - ``total(_:orderBy:filter:)``
/// - ``uppercased``
/// - ``SQLDateModifier``
///
@@ -2370,6 +2373,7 @@ extension SQLSpecificExpressible {
.desc(sqlExpression)
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// An ordering term for ascending order (nulls last).
public var ascNullsLast: SQLOrdering {
.ascNullsLast(sqlExpression)
@@ -2379,6 +2383,19 @@ extension SQLSpecificExpressible {
public var descNullsFirst: SQLOrdering {
.descNullsFirst(sqlExpression)
}
#else
/// An ordering term for ascending order (nulls last).
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public var ascNullsLast: SQLOrdering {
.ascNullsLast(sqlExpression)
}
/// An ordering term for descending order (nulls first).
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public var descNullsFirst: SQLOrdering {
.descNullsFirst(sqlExpression)
}
#endif
}
// MARK: - SQL Selection Support
+123 -66
View File
@@ -10,6 +10,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
.function("ABS", [value.sqlExpression])
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `AVG` SQL aggregate function.
///
/// For example:
@@ -17,19 +18,45 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
/// ```swift
/// // AVG(length)
/// average(Column("length"))
///
/// // AVG(length) FILTER (WHERE length > 0)
/// average(Column("length"), filter: Column("length") > 0)
/// ```
public func average(
_ value: some SQLSpecificExpressible,
filter: (any SQLSpecificExpressible)? = nil
) -> SQLExpression {
filter: (any SQLSpecificExpressible)? = nil)
-> SQLExpression {
.aggregateFunction("AVG", [value.sqlExpression], filter: filter?.sqlExpression)
}
#else
/// The `AVG` SQL aggregate function.
///
/// For example:
///
/// ```swift
/// // AVG(length) FILTER (WHERE length > 0)
/// average(Column("length"), filter: Column("length") > 0)
/// ```
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public func average(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
-> SQLExpression {
.aggregateFunction(
"AVG", [value.sqlExpression],
filter: filter?.sqlExpression)
filter: filter.sqlExpression)
}
/// The `AVG` SQL aggregate function.
///
/// For example:
///
/// ```swift
/// // AVG(length)
/// average(Column("length"))
/// ```
public func average(_ value: some SQLSpecificExpressible) -> SQLExpression {
.aggregateFunction("AVG", [value.sqlExpression])
}
#endif
/// The `CAST` SQL function.
///
/// For example:
@@ -136,6 +163,7 @@ public func max(
.simpleFunction("MAX", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `MAX` SQL aggregate function.
///
/// For example:
@@ -143,18 +171,42 @@ public func max(
/// ```swift
/// // MAX(score)
/// max(Column("score"))
///
/// // MAX(score) FILTER (WHERE score < 0)
/// max(Column("score"), filter: Column("score") < 0)
/// ```
public func max(
_ value: some SQLSpecificExpressible,
filter: (any SQLSpecificExpressible)? = nil
) -> SQLExpression {
.aggregateFunction(
"MAX", [value.sqlExpression],
filter: filter?.sqlExpression)
filter: (any SQLSpecificExpressible)? = nil)
-> SQLExpression {
.aggregateFunction("MAX", [value.sqlExpression], filter: filter?.sqlExpression)
}
#else
/// The `MAX` SQL aggregate function.
///
/// For example:
///
/// ```swift
/// // MAX(score) FILTER (WHERE score < 0)
/// max(Column("score"), filter: Column("score") < 0)
/// ```
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public func max(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
-> SQLExpression {
.aggregateFunction("MAX", [value.sqlExpression], filter: filter.sqlExpression)
}
/// The `MAX` SQL aggregate function.
///
/// For example:
///
/// ```swift
/// // MAX(score)
/// max(Column("score"))
/// ```
public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
.aggregateFunction("MAX", [value.sqlExpression])
}
#endif
/// The `MIN` SQL multi-argument function.
///
@@ -172,6 +224,7 @@ public func min(
.simpleFunction("MIN", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `MIN` SQL aggregate function.
///
/// For example:
@@ -179,18 +232,42 @@ public func min(
/// ```swift
/// // MIN(score)
/// min(Column("score"))
///
/// // MIN(score) FILTER (WHERE score > 0)
/// min(Column("score"), filter: Column("score") > 0)
/// ```
public func min(
_ value: some SQLSpecificExpressible,
filter: (any SQLSpecificExpressible)? = nil
) -> SQLExpression {
.aggregateFunction(
"MIN", [value.sqlExpression],
filter: filter?.sqlExpression)
filter: (any SQLSpecificExpressible)? = nil)
-> SQLExpression {
.aggregateFunction("MIN", [value.sqlExpression], filter: filter?.sqlExpression)
}
#else
/// The `MIN` SQL aggregate function.
///
/// For example:
///
/// ```swift
/// // MIN(score) FILTER (WHERE score > 0)
/// min(Column("score"), filter: Column("score") > 0)
/// ```
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public func min(
_ value: some SQLSpecificExpressible,
filter: some SQLSpecificExpressible)
-> SQLExpression {
.aggregateFunction("MIN", [value.sqlExpression], filter: filter.sqlExpression)
}
/// The `MIN` SQL aggregate function.
///
/// For example:
///
/// ```swift
/// // MIN(score)
/// min(Column("score"))
/// ```
public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
.aggregateFunction("MIN", [value.sqlExpression])
}
#endif
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// The `SUM` SQL aggregate function.
@@ -202,7 +279,7 @@ public func min(
/// sum(Column("amount"))
/// ```
///
/// See also ``total(_:orderBy:filter:)``.
/// See also ``total(_:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func sum(
@@ -217,28 +294,26 @@ public func sum(
filter: filter?.sqlExpression)
}
#else
/// The `SUM` SQL aggregate function, with an ordering.
/// The `SUM` SQL aggregate function.
///
/// For example:
///
/// ```swift
/// // SUM(amount ORDER BY date)
/// sum(Column("amount"), orderBy: Column("date"))
/// // SUM(amount) FILTER (WHERE amount > 0)
/// sum(Column("amount"), filter: Column("amount") > 0)
/// ```
///
/// See also ``total(_:orderBy:filter:)``.
/// See also ``total(_:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
@available(anyAppleOS 26, *) // SQLite 3.44.0+
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public func sum(
_ value: some SQLSpecificExpressible,
orderBy ordering: any SQLOrderingTerm,
filter: (any SQLSpecificExpressible)? = nil
) -> SQLExpression {
filter: some SQLSpecificExpressible)
-> SQLExpression {
.aggregateFunction(
"SUM", [value.sqlExpression],
ordering: ordering.sqlOrdering,
filter: filter?.sqlExpression)
filter: filter.sqlExpression)
}
/// The `SUM` SQL aggregate function.
@@ -248,21 +323,13 @@ public func sum(
/// ```swift
/// // SUM(amount)
/// sum(Column("amount"))
///
/// // SUM(amount) FILTER (WHERE amount > 0)
/// sum(Column("amount"), filter: Column("amount") > 0)
/// ```
///
/// See also ``total(_:filter:)``.
/// See also ``total(_:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func sum(
_ value: some SQLSpecificExpressible,
filter: (any SQLSpecificExpressible)? = nil
) -> SQLExpression {
.aggregateFunction(
"SUM", [value.sqlExpression],
filter: filter?.sqlExpression)
public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
.aggregateFunction("SUM", [value.sqlExpression])
}
#endif
@@ -276,7 +343,7 @@ public func sum(
/// total(Column("amount"))
/// ```
///
/// See also ``sum(_:orderBy:filter:)``.
/// See also ``sum(_:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func total(
@@ -291,28 +358,26 @@ public func total(
filter: filter?.sqlExpression)
}
#else
/// The `TOTAL` SQL aggregate function, with an ordering.
/// The `TOTAL` SQL aggregate function.
///
/// For example:
///
/// ```swift
/// // TOTAL(amount ORDER BY date)
/// total(Column("amount"), orderBy: Column("date"))
/// // TOTAL(amount) FILTER (WHERE amount > 0)
/// total(Column("amount"), filter: Column("amount") > 0)
/// ```
///
/// See also ``sum(_:orderBy:filter:)``.
/// See also ``sum(_:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
@available(anyAppleOS 26, *) // SQLite 3.44.0+
@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+
public func total(
_ value: some SQLSpecificExpressible,
orderBy ordering: any SQLOrderingTerm,
filter: (any SQLSpecificExpressible)? = nil
) -> SQLExpression {
filter: some SQLSpecificExpressible)
-> SQLExpression {
.aggregateFunction(
"TOTAL", [value.sqlExpression],
ordering: ordering.sqlOrdering,
filter: filter?.sqlExpression)
filter: filter.sqlExpression)
}
/// The `TOTAL` SQL aggregate function.
@@ -322,21 +387,13 @@ public func total(
/// ```swift
/// // TOTAL(amount)
/// total(Column("amount"))
///
/// // TOTAL(amount) FILTER (WHERE amount > 0)
/// total(Column("amount"), filter: Column("amount") > 0)
/// ```
///
/// See also ``sum(_:filter:)``.
/// See also ``sum(_:)``.
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
public func total(
_ value: some SQLSpecificExpressible,
filter: (any SQLSpecificExpressible)? = nil
) -> SQLExpression {
.aggregateFunction(
"TOTAL", [value.sqlExpression],
filter: filter?.sqlExpression)
public func total(_ value: some SQLSpecificExpressible) -> SQLExpression {
.aggregateFunction("TOTAL", [value.sqlExpression])
}
#endif
+4 -8
View File
@@ -21,24 +21,20 @@ public struct SQLOrdering: Sendable {
/// ORDER BY score
case expression(SQLExpression)
/// An ascending expression with NULLS first
/// An ascending expression
///
/// ORDER BY score ASC
case asc(SQLExpression)
/// A descending expression with NULLS last
/// A descending expression
///
/// ORDER BY score DESC
case desc(SQLExpression)
/// An ascending expression with NULLS last
///
/// ORDER BY score ASC NULLS LAST
/// Only available from SQLite 3.30.0
case ascNullsLast(SQLExpression)
/// A descending expression with NULLS first
///
/// ORDER BY score DESC NULLS FIRST
/// Only available from SQLite 3.30.0
case descNullsFirst(SQLExpression)
/// A literal SQL ordering
@@ -125,7 +125,7 @@ struct SQLTableGenerator {
tableOptions.append("STRICT")
}
#else
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, *) { // SQLite 3.37+
if #available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) { // SQLite 3.37+
if options.contains(.strict) {
tableOptions.append("STRICT")
}
@@ -350,6 +350,7 @@ public final class ColumnDefinition {
return self
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Defines the column as a generated column.
///
/// For example:
@@ -478,6 +479,138 @@ public final class ColumnDefinition {
qualification: qualification)
return self
}
#else
/// Defines the column as a generated column.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// // score INTEGER NOT NULL,
/// // bonus INTEGER NOT NULL,
/// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL
/// // )
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("score", .integer).notNull()
/// t.column("bonus", .integer).notNull()
/// t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
/// // No property for `totalScore`
/// var id: Int64
/// var score: Int
/// var bonus: Int
/// }
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
/// - sql: An SQL expression.
/// - qualification: The generated column's qualification, which
/// defaults to ``GeneratedColumnQualification/virtual``.
/// - returns: `self` so that you can further refine the column definition.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ (3.31 actually)
@discardableResult
public func generatedAs(
sql: String,
_ qualification: GeneratedColumnQualification = .virtual)
-> Self
{
let expression = SQL(sql: sql).sqlExpression
generatedColumnConstraint = GeneratedColumnConstraint(
expression: expression,
qualification: qualification)
return self
}
/// Defines the column as a generated column.
///
/// For example:
///
/// ```swift
/// // CREATE TABLE player(
/// // id INTEGER PRIMARY KEY AUTOINCREMENT,
/// // score INTEGER NOT NULL,
/// // bonus INTEGER NOT NULL,
/// // totalScore INTEGER GENERATED ALWAYS AS (score + bonus) VIRTUAL
/// // )
/// try db.create(table: "player") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("score", .integer).notNull()
/// t.column("bonus", .integer).notNull()
/// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"))
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
/// // No property for `totalScore`
/// var id: Int64
/// var score: Int
/// var bonus: Int
/// }
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
/// - expression: The generated expression.
/// - qualification: The generated column's qualification, which
/// defaults to ``GeneratedColumnQualification/virtual``.
/// - returns: `self` so that you can further refine the column definition.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ (3.31 actually)
@discardableResult
public func generatedAs(
_ expression: some SQLExpressible,
_ qualification: GeneratedColumnQualification = .virtual)
-> Self
{
generatedColumnConstraint = GeneratedColumnConstraint(
expression: expression.sqlExpression,
qualification: qualification)
return self
}
#endif
/// Adds a foreign key constraint.
///
@@ -79,6 +79,42 @@ public final class TableAlteration {
alterations.append(.addColumnLiteral(literal))
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Renames a column.
///
/// For example:
///
/// ```swift
/// try db.alter(table: "player") { t in
/// t.rename(column: "url", to: "homeURL")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - parameter name: the old name of the column.
/// - parameter newName: the new name of the column.
public func rename(column name: String, to newName: String) {
_rename(column: name, to: newName)
}
/// Drops a column.
///
/// For example:
///
/// ```swift
/// try db.alter(table: "player") { t in
/// t.drop(column: "age")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - Parameter name: the name of the column to drop.
public func drop(column name: String) {
_drop(column: name)
}
#else
/// Renames a column.
///
/// For example:
@@ -132,9 +168,11 @@ public final class TableAlteration {
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
///
/// - Parameter name: the name of the column to drop.
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func drop(column name: String) {
_drop(column: name)
}
#endif
private func _rename(column name: String, to newName: String) {
alterations.append(.rename(old: name, new: newName))
@@ -20,7 +20,7 @@ public struct TableOptions: OptionSet, Sendable {
public static let strict = TableOptions(rawValue: 1 << 3)
#else
/// Creates a [STRICT](https://www.sqlite.org/stricttables.html) table.
@available(iOS 15.4, macOS 12.4, tvOS 15.4, *) // SQLite 3.37+
@available(iOS 15.4, macOS 12.4, tvOS 15.4, watchOS 8.5, *) // SQLite 3.37+
public static let strict = TableOptions(rawValue: 1 << 3)
#endif
}
+1 -1
View File
@@ -39,7 +39,7 @@ import Foundation // For JSONEncoder
/// - ``databaseChanges(from:)``
/// - ``databaseChanges(modify:)``
/// - ``databaseEquals(_:)``
public protocol EncodableRecord: SendableMetatype {
public protocol EncodableRecord: GRDBSendableMetatype {
/// Encodes the record into the provided persistence container.
///
/// In your implementation of this method, store in the `container` argument
@@ -1,17 +1,17 @@
// MARK: - Delete Callbacks
extension MutablePersistableRecord {
@inline(always)
@inline(__always)
@inlinable
public func willDelete(_ db: Database) throws { }
@inline(always)
@inline(__always)
@inlinable
public func aroundDelete(_ db: Database, delete: () throws -> Bool) throws {
_ = try delete()
}
@inline(always)
@inline(__always)
@inlinable
public func didDelete(deleted: Bool) { }
}
@@ -1,17 +1,17 @@
// MARK: - Insert Callbacks
extension MutablePersistableRecord {
@inline(always)
@inline(__always)
@inlinable
public mutating func willInsert(_ db: Database) throws { }
@inline(always)
@inline(__always)
@inlinable
public func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws {
_ = try insert()
}
@inline(always)
@inline(__always)
@inlinable
public mutating func didInsert(_ inserted: InsertionSuccess) { }
}
@@ -90,6 +90,7 @@ extension MutablePersistableRecord {
// MARK: - Insert and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -331,6 +332,255 @@ extension MutablePersistableRecord {
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> T
where Self: TableRecord
{
try insertAndFetch(db, onConflict: conflictResolution, selection: select(Self.databaseComponents), fetch: fetch)
}
#else
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
/// This method is equivalent to ``insertAndFetch(_:onConflict:as:)``,
/// with `Self` as the `returnedType` argument:
///
/// ```swift
/// // Equivalent
/// let insertedPlayer = try player.insertAndFetch(db)
/// let insertedPlayer = try player.insertAndFetch(db, as: Player.self)
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The inserted record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func insertAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self
where Self: FetchableRecord
{
var result = self
return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
/// This method helps deal with default column values and
/// generated columns.
///
/// For example:
///
/// ```swift
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: MutablePersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // A full player, with all database information
/// struct Player: TableRecord, FetchableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// // Insert a partial player, get a full one
/// try dbQueue.write { db in
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// let player = try partialPlayer.insertAndFetch(db, as: Player.self)
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T
{
let record = self
return try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
}
}
/// Executes an `INSERT RETURNING` statement, and returns the selected
/// columns from the inserted row.
///
/// This method helps deal with default column values and
/// generated columns.
///
/// For example:
///
/// ```swift
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: MutablePersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // Insert a partial player, get the inserted score
/// try dbQueue.write { db in
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
/// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in
/// try Int.fetchOne(statement)
/// }
/// print(score) // The inserted score
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A closure that executes its ``Statement`` argument.
/// If the conflict policy is `IGNORE`, the statement may return no row.
/// - returns: The result of the `fetch` function.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func insertAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var success: (inserted: InsertionSuccess, returned: T)?
try aroundSave(db) {
success = try insertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return PersistenceSuccess(success!.inserted)
}
guard let success else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(PersistenceSuccess(success.inserted))
return success.returned
}
/// Executes an `INSERT RETURNING` statement, and returns the selected
/// columns from the inserted row.
///
/// This method helps deal with default column values and
/// generated columns.
///
/// For example:
///
/// ```swift
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: MutablePersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
///
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// // Insert a partial player, get the inserted score
/// try dbQueue.write { db in
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
/// let score = try partialPlayer.insertAndFetch(db) { statement in
/// try Int.fetchOne(statement)
/// } select: {
/// [$0.score]
/// }
/// print(score) // The inserted score
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter fetch: A closure that executes its ``Statement`` argument.
/// If the conflict policy is `IGNORE`, the statement may return no row.
/// - parameter select: A closure that returns the returned columns
/// (must not be empty).
/// - returns: The result of the `fetch` function.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// - precondition: The result of `select` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func insertAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
fetch: (Statement) throws -> T,
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> T
where Self: TableRecord
{
try insertAndFetch(
db,
@@ -338,6 +588,7 @@ extension MutablePersistableRecord {
selection: select(Self.databaseComponents),
fetch: fetch)
}
#endif
}
// MARK: - Internals
+136 -3
View File
@@ -1,17 +1,17 @@
// MARK: - Save Callbacks
extension MutablePersistableRecord {
@inline(always)
@inline(__always)
@inlinable
public func willSave(_ db: Database) throws { }
@inline(always)
@inline(__always)
@inlinable
public func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws {
_ = try save()
}
@inline(always)
@inline(__always)
@inlinable
public func didSave(_ saved: PersistenceSuccess) { }
}
@@ -86,6 +86,7 @@ extension MutablePersistableRecord {
// MARK: - Save and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -213,6 +214,138 @@ extension MutablePersistableRecord {
didSave(success.saved)
return success.returned
}
#else
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// This method helps deal with default column values and
/// generated columns.
///
/// For example:
///
/// let player: Player = ...
/// let savedPlayer = try player.saveAndFetch(db)
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The saved record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func saveAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self
where Self: FetchableRecord
{
var result = self
return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T
{
try willSave(db)
var success: (saved: PersistenceSuccess, returned: T)?
try aroundSave(db) {
let record = self
success = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
})
return success!.saved
}
guard let success else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(success.saved)
return success.returned
}
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns the selected columns from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes its ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func saveAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var success: (saved: PersistenceSuccess, returned: T)?
try aroundSave(db) {
success = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return success!.saved
}
guard let success else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(success.saved)
return success.returned
}
#endif
}
// MARK: - Internal
@@ -1,17 +1,17 @@
// MARK: - Update Callbacks
extension MutablePersistableRecord {
@inline(always)
@inline(__always)
@inlinable
public func willUpdate(_ db: Database, columns: Set<String>) throws { }
@inline(always)
@inline(__always)
@inlinable
public func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws {
_ = try update()
}
@inline(always)
@inline(__always)
@inlinable
public func didUpdate(_ updated: PersistenceSuccess) { }
}
@@ -213,6 +213,7 @@ extension MutablePersistableRecord {
// MARK: - Update and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
@@ -494,7 +495,7 @@ extension MutablePersistableRecord {
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes its ``Statement`` argument.
/// - parameter modify: A closure that modifies the record.
/// - returns: The result of the `fetch` function, or nil if the record
/// - returns: The result of the `fetch` function, or nil if the record
/// has no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
@@ -518,11 +519,327 @@ extension MutablePersistableRecord {
selection: selection,
fetch: fetch)
}
#else
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The updated record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self
where Self: FetchableRecord
{
try updateAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
/// Executes an `UPDATE RETURNING` statement on all columns, and returns a
/// new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T
{
try updateAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
}
}
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
/// new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter modify: A closure that modifies the record.
/// - returns: An updated record, or nil if the record has no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func updateChangesAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
modify: (inout Self) throws -> Void)
throws -> Self?
where Self: FetchableRecord
{
try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify)
}
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
/// new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - parameter modify: A closure that modifies the record.
/// - returns: A record of type `returnedType`, or nil if the record has
/// no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the update fails due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func updateChangesAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type,
modify: (inout Self) throws -> Void)
throws -> T?
{
let record = self
return try updateChangesAndFetch(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
if let result = try T.fetchOne($0) {
return result
}
throw record.recordNotFound(db)
},
modify: modify)
}
/// Executes an `UPDATE RETURNING` statement on the provided columns, and
/// returns the selected columns from the updated row.
///
/// For example:
///
/// ```swift
/// try dbQueue.write { db in
/// // UPDATE player SET score = ... RETURNING totalScore
/// let totalScore = try player.updateAndFetch(
/// db, columns: ["score"],
/// selection: [Column("totalScore")],
/// fetch: { statement in
/// try Int.fetchOne(statement)
/// })
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter columns: The columns to update.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes its ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
columns: some Collection<String>,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T
) throws -> T {
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var success: (updated: PersistenceSuccess, returned: T)?
try aroundSave(db) {
success = try updateAndFetchWithCallbacks(
db, onConflict: conflictResolution,
columns: Set(columns),
selection: selection,
fetch: fetch)
return success!.updated
}
guard let success else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(success.updated)
return success.returned
}
/// Executes an `UPDATE RETURNING` statement on the provided columns, and
/// returns the selected columns from the updated row.
///
/// For example:
///
/// ```swift
/// try dbQueue.write { db in
/// // UPDATE player SET score = ... RETURNING totalScore
/// let totalScore = try player.updateAndFetch(
/// db, columns: [Column("score")],
/// selection: [Column("totalScore")],
/// fetch: { statement in
/// try Int.fetchOne(statement)
/// })
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter columns: The columns to update.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes its ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
columns: some Collection<some ColumnExpression>,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T
) throws -> T {
try updateAndFetch(
db, onConflict: conflictResolution,
columns: columns.map(\.name),
selection: selection,
fetch: fetch)
}
/// Executes an `UPDATE RETURNING` statement on all columns, and returns the
/// selected columns from the updated row.
///
/// For example:
///
/// ```swift
/// try dbQueue.write { db in
/// // UPDATE player SET ... RETURNING totalScore
/// let totalScore = try player.updateAndFetch(db, selection: [Column("totalScore")]) { statement in
/// try Int.fetchOne(statement)
/// }
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes its ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func updateAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
let databaseTableName = type(of: self).databaseTableName
let columns = try db.columns(in: databaseTableName).map(\.name)
return try updateAndFetch(
db, onConflict: conflictResolution,
columns: columns,
selection: selection,
fetch: fetch)
}
/// Modifies the record according to the provided `modify` closure, and
/// executes an `UPDATE RETURNING` statement that updates the modified
/// columns, if and only if the record was modified. The method returns a
/// new record built from the updated row.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes its ``Statement`` argument.
/// - parameter modify: A closure that modifies the record.
/// - returns: The result of the `fetch` function, or nil if the record
/// has no change.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type,
/// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the
/// primary key does not match any row in the database.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func updateChangesAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T,
modify: (inout Self) throws -> Void)
throws -> T?
{
let container = try PersistenceContainer(db, self)
try modify(&self)
return try updateChangesAndFetch(
db, onConflict: conflictResolution,
from: container,
selection: selection,
fetch: fetch)
}
#endif
}
// MARK: - Internals
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
@inlinable // allow specialization so that empty callbacks are removed
func updateChangesAndFetch<T>(
_ db: Database,
@@ -543,6 +860,29 @@ extension MutablePersistableRecord {
selection: selection,
fetch: fetch)
}
#else
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
func updateChangesAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
from container: PersistenceContainer,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T?
{
let changes = try PersistenceContainer(db, self).changesIterator(from: container)
let changedColumns: Set<String> = changes.reduce(into: []) { $0.insert($1.0) }
if changedColumns.isEmpty {
return nil
}
return try updateAndFetch(
db, onConflict: conflictResolution,
columns: changedColumns,
selection: selection,
fetch: fetch)
}
#endif
/// Executes an `UPDATE` statement, and runs update callbacks.
@inlinable // allow specialization so that empty callbacks are removed
@@ -1,6 +1,7 @@
// MARK: - Upsert
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT ON CONFLICT DO UPDATE` statement.
///
/// The upsert behavior is triggered by a violation of any uniqueness
@@ -46,6 +47,7 @@ extension MutablePersistableRecord {
didSave(saved)
}
// TODO: Make it possible to build assignments from $0.columnName
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
/// returns the upserted record.
///
@@ -184,6 +186,194 @@ extension MutablePersistableRecord {
didSave(PersistenceSuccess(success.inserted))
return success.returned
}
#else
/// Executes an `INSERT ON CONFLICT DO UPDATE` statement.
///
/// The upsert behavior is triggered by a violation of any uniqueness
/// constraint on the table (primary key or unique index). In case of
/// violation, all columns but the primary key are overwritten with the
/// inserted values.
///
/// For example:
///
/// ```swift
/// struct Player: Encodable, MutablePersistableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// // INSERT INTO player (id, name, score)
/// // VALUES (1, 'Arthur', 1000)
/// // ON CONFLICT DO UPDATE SET
/// // name = excluded.name,
/// // score = excluded.score
/// var player = Player(id: 1, name: "Arthur", score: 1000)
/// try player.upsert(db)
/// ```
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func upsert(_ db: Database) throws {
try willSave(db)
var saved: PersistenceSuccess?
try aroundSave(db) {
let inserted = try upsertWithCallbacks(db)
saved = PersistenceSuccess(inserted)
return saved!
}
guard let saved else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(saved)
}
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
/// returns the upserted record.
///
/// With default parameters (`upsertAndFetch(db)`), the upsert behavior is
/// triggered by a violation of any uniqueness constraint on the table
/// (primary key or unique index). In case of violation, all columns but the
/// primary key are overwritten with the inserted values:
///
/// ```swift
/// struct Player: Encodable, MutablePersistableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// // INSERT INTO player (id, name, score)
/// // VALUES (1, 'Arthur', 1000)
/// // ON CONFLICT DO UPDATE SET
/// // name = excluded.name,
/// // score = excluded.score
/// // RETURNING *
/// var player = Player(id: 1, name: "Arthur", score: 1000)
/// let upsertedPlayer = try player.upsertAndFetch(db)
/// ```
///
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
/// you can further control the upsert behavior. Make sure you check
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
///
/// The conflict target consists of the columns of the uniqueness constraint
/// (primary key or unique index) that triggers the upsert. If empty, all
/// uniqueness constraints are considered.
///
/// The strategy controls which columns are updated in case of
/// uniqueness constraint violation: all columns unless specified (the
/// default), or only the specified columns.
///
/// For example, compare:
///
/// ```swift
/// // In case of conflict, updates all columns, including columns added
/// // in a future migration.
/// let upserted = try player.upsertAndFetch(db)
///
/// // In case of conflict, updates all columns, including future ones,
/// // but 'score'.
/// let upserted = try player.upsertAndFetch(db) { _ in
/// [Column("score").noOverwrite]
/// }
///
/// // In case of conflict, do not update any column.
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
///
/// // In case of conflict, only update 'name'.
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
/// [Column("name").set(to: excluded[Column("name")])]
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictTarget: The conflict target.
/// - parameter strategy: The default strategy, `.allColumns`, updates
/// all columns in case of conflict, unless specified otherwise in the
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
/// update the columns assigned in the `assignments` parameter.
/// - parameter assignments: An optional function that returns an array of
/// ``ColumnAssignment``. In case of violation of a uniqueness
/// constraint, these assignments are performed, and remaining columns
/// are overwritten by inserted values, or not, depending on the
/// chosen `strategy`. To use the value that would have been inserted
/// had the constraint not failed, use the `excluded` parameter.
/// - returns: The upserted record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func upsertAndFetch(
_ db: Database,
onConflict conflictTarget: [String] = [],
updating strategy: UpsertUpdateStrategy = .allColumns,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> Self
where Self: FetchableRecord
{
try upsertAndFetch(
db, as: Self.self, onConflict: conflictTarget,
updating: strategy, doUpdate: assignments)
}
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
/// returns the upserted record.
///
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
/// information about the `conflictTarget`, `strategy`, and
/// `assignments` parameters.
///
/// - parameter db: A database connection.
/// - parameter returnedType: The type of the returned record.
/// - parameter conflictTarget: The conflict target.
/// - parameter strategy: The default strategy, `.allColumns`, updates
/// all columns in case of conflict, unless specified otherwise in the
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
/// update the columns assigned in the `assignments` parameter.
/// - parameter assignments: An optional function that returns an array of
/// ``ColumnAssignment``. In case of violation of a uniqueness
/// constraint, these assignments are performed, and remaining columns
/// are overwritten by inserted values, or not, depending on the
/// chosen `strategy`. To use the value that would have been inserted
/// had the constraint not failed, use the `excluded` parameter.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public mutating func upsertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
as returnedType: T.Type,
onConflict conflictTarget: [String] = [],
updating strategy: UpsertUpdateStrategy = .allColumns,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> T
{
try willSave(db)
var success: (inserted: InsertionSuccess, returned: T)?
try aroundSave(db) {
success = try upsertAndFetchWithCallbacks(
db, onConflict: conflictTarget,
updating: strategy, doUpdate: assignments,
selection: T.databaseSelection,
decode: { try T(row: $0) })
return PersistenceSuccess(success!.inserted)
}
guard let success else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(PersistenceSuccess(success.inserted))
return success.returned
}
#endif
}
// MARK: - Internal
+219 -2
View File
@@ -1,11 +1,11 @@
// MARK: - Insert Callbacks
extension PersistableRecord {
@inline(always)
@inline(__always)
@inlinable
public func willInsert(_ db: Database) throws { }
@inline(always)
@inline(__always)
@inlinable
public func didInsert(_ inserted: InsertionSuccess) { }
}
@@ -55,6 +55,7 @@ extension PersistableRecord {
// MARK: - Insert and Fetch
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
@@ -263,6 +264,221 @@ extension PersistableRecord {
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> T
where Self: TableRecord
{
try insertAndFetch(db, onConflict: conflictResolution, selection: select(Self.databaseComponents), fetch: fetch)
}
#else
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
/// This method helps deal with default column values and
/// generated columns.
///
/// For example:
///
/// ```swift
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: PersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // A full player, with all database information
/// struct Player: TableRecord, FetchableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// // Insert a partial player, get a full one
/// try dbQueue.write { db in
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// let player = try partialPlayer.insertAndFetch(db, as: Player.self)
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the insertion failed due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
}
}
/// Executes an `INSERT RETURNING` statement, and returns the selected
/// columns from the inserted row.
///
/// This method helps deal with default column values and
/// generated columns.
///
/// For example:
///
/// ```swift
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: PersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // Insert a partial player, get the inserted score
/// try dbQueue.write { db in
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
/// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in
/// try Int.fetchOne(statement)
/// }
/// print(score) // The inserted score
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A closure that executes its ``Statement`` argument.
/// If the conflict policy is `IGNORE`, the statement may return no row.
/// - returns: The result of the `fetch` function.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func insertAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var success: (inserted: InsertionSuccess, returned: T)?
try aroundSave(db) {
success = try insertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return PersistenceSuccess(success!.inserted)
}
guard let success else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(PersistenceSuccess(success.inserted))
return success.returned
}
/// Executes an `INSERT RETURNING` statement, and returns the selected
/// columns from the inserted row.
///
/// This method helps deal with default column values and
/// generated columns.
///
/// For example:
///
/// ```swift
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: PersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
///
/// enum Columns {
/// static let score = Column("score")
/// }
/// }
///
/// // Insert a partial player, get the inserted score
/// try dbQueue.write { db in
/// let partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
/// let score = try partialPlayer.insertAndFetch(db) { statement in
/// try Int.fetchOne(statement)
/// } select: {
/// [$0.score]
/// }
/// print(score) // The inserted score
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter fetch: A closure that executes its ``Statement`` argument.
/// If the conflict policy is `IGNORE`, the statement may return no row.
/// - parameter select: A closure that returns the returned columns
/// (must not be empty).
/// - returns: The result of the `fetch` function.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// - precondition: The result of `select` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func insertAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
fetch: (Statement) throws -> T,
select: (DatabaseComponents) throws -> [any SQLSelectable]
) throws -> T
where Self: TableRecord
{
try insertAndFetch(
db,
@@ -270,6 +486,7 @@ extension PersistableRecord {
selection: select(Self.databaseComponents),
fetch: fetch)
}
#endif
}
// MARK: - Internals
+96
View File
@@ -38,6 +38,7 @@ extension PersistableRecord {
// MARK: - Save and Fetch
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
@@ -129,6 +130,101 @@ extension PersistableRecord {
didSave(success.saved)
return success.returned
}
#else
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns a new record built from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// ``RecordError/recordNotFound(databaseTableName:key:)`` can be
/// thrown if the database changes fail due to the IGNORE conflict policy.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func saveAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T
{
try willSave(db)
var success: (saved: PersistenceSuccess, returned: T)?
try aroundSave(db) {
success = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: T.databaseSelection,
fetch: {
if let result = try T.fetchOne($0) {
return result
}
throw recordNotFound(db)
})
return success!.saved
}
guard let success else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(success.saved)
return success.returned
}
/// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and
/// returns the selected columns from the saved row.
///
/// If the receiver has a non-nil primary key and a matching row in the
/// database, this method performs an update. Otherwise, it performs
/// an insert.
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A function that executes its ``Statement`` argument.
/// - returns: The result of the `fetch` function.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func saveAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var success: (saved: PersistenceSuccess, returned: T)?
try aroundSave(db) {
success = try updateOrInsertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return success!.saved
}
guard let success else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(success.saved)
return success.returned
}
#endif
}
// MARK: - Internal
+190
View File
@@ -1,6 +1,7 @@
// MARK: - Upsert
extension PersistableRecord {
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
/// Executes an `INSERT ON CONFLICT DO UPDATE` statement.
///
/// The upsert behavior is triggered by a violation of any uniqueness
@@ -46,6 +47,7 @@ extension PersistableRecord {
didSave(saved)
}
// TODO: Make it possible to build assignments from $0.columnName
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
/// returns the upserted record.
///
@@ -184,6 +186,194 @@ extension PersistableRecord {
didSave(PersistenceSuccess(success.inserted))
return success.returned
}
#else
/// Executes an `INSERT ON CONFLICT DO UPDATE` statement.
///
/// The upsert behavior is triggered by a violation of any uniqueness
/// constraint on the table (primary key or unique index). In case of
/// violation, all columns but the primary key are overwritten with the
/// inserted values.
///
/// For example:
///
/// ```swift
/// struct Player: Encodable, PersistableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// // INSERT INTO player (id, name, score)
/// // VALUES (1, 'Arthur', 1000)
/// // ON CONFLICT DO UPDATE SET
/// // name = excluded.name,
/// // score = excluded.score
/// let player = Player(id: 1, name: "Arthur", score: 1000)
/// try player.upsert(db)
/// ```
///
/// - parameter db: A database connection.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func upsert(_ db: Database) throws {
try willSave(db)
var saved: PersistenceSuccess?
try aroundSave(db) {
let inserted = try upsertWithCallbacks(db)
saved = PersistenceSuccess(inserted)
return saved!
}
guard let saved else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(saved)
}
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
/// returns the upserted record.
///
/// With default parameters (`upsertAndFetch(db)`), the upsert behavior is
/// triggered by a violation of any uniqueness constraint on the table
/// (primary key or unique index). In case of violation, all columns but the
/// primary key are overwritten with the inserted values:
///
/// ```swift
/// struct Player: Encodable, PersistableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// // INSERT INTO player (id, name, score)
/// // VALUES (1, 'Arthur', 1000)
/// // ON CONFLICT DO UPDATE SET
/// // name = excluded.name,
/// // score = excluded.score
/// // RETURNING *
/// let player = Player(id: 1, name: "Arthur", score: 1000)
/// let upsertedPlayer = try player.upsertAndFetch(db)
/// ```
///
/// With the `conflictTarget`, `strategy`, and `assignments` arguments,
/// you can further control the upsert behavior. Make sure you check
/// <https://www.sqlite.org/lang_UPSERT.html> for detailed information.
///
/// The conflict target consists of the columns of the uniqueness constraint
/// (primary key or unique index) that triggers the upsert. If empty, all
/// uniqueness constraints are considered.
///
/// The strategy controls which columns are updated in case of
/// uniqueness constraint violation: all columns unless specified (the
/// default), or only the specified columns.
///
/// For example, compare:
///
/// ```swift
/// // In case of conflict, updates all columns, including columns added
/// // in a future migration.
/// let upserted = try player.upsertAndFetch(db)
///
/// // In case of conflict, updates all columns, including future ones,
/// // but 'score'.
/// let upserted = try player.upsertAndFetch(db) { _ in
/// [Column("score").noOverwrite]
/// }
///
/// // In case of conflict, do not update any column.
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified)
///
/// // In case of conflict, only update 'name'.
/// let upserted = try player.upsertAndFetch(db, updating: .noColumnUnlessSpecified) { excluded in
/// [Column("name").set(to: excluded[Column("name")])]
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictTarget: The conflict target.
/// - parameter strategy: The default strategy, `.allColumns`, updates
/// all columns in case of conflict, unless specified otherwise in the
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
/// update the columns assigned in the `assignments` parameter.
/// - parameter assignments: An optional function that returns an array of
/// ``ColumnAssignment``. In case of violation of a uniqueness
/// constraint, these assignments are performed, and remaining columns
/// are overwritten by inserted values, or not, depending on the
/// chosen `strategy`. To use the value that would have been inserted
/// had the constraint not failed, use the `excluded` parameter.
/// - returns: The upserted record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func upsertAndFetch(
_ db: Database,
onConflict conflictTarget: [String] = [],
updating strategy: UpsertUpdateStrategy = .allColumns,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> Self
where Self: FetchableRecord
{
try upsertAndFetch(
db, as: Self.self, onConflict: conflictTarget,
updating: strategy, doUpdate: assignments)
}
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
/// returns the upserted record.
///
/// See ``upsertAndFetch(_:onConflict:updating:doUpdate:)`` for more
/// information about the `conflictTarget`, `strategy`, and
/// `assignments` parameters.
///
/// - parameter db: A database connection.
/// - parameter returnedType: The type of the returned record.
/// - parameter conflictTarget: The conflict target.
/// - parameter strategy: The default strategy, `.allColumns`, updates
/// all columns in case of conflict, unless specified otherwise in the
/// `assignments` parameter. Use `.noColumnUnlessSpecified` to only
/// update the columns assigned in the `assignments` parameter.
/// - parameter assignments: An optional function that returns an array of
/// ``ColumnAssignment``. In case of violation of a uniqueness
/// constraint, these assignments are performed, and remaining columns
/// are overwritten by inserted values, or not, depending on the
/// chosen `strategy`. To use the value that would have been inserted
/// had the constraint not failed, use the `excluded` parameter.
/// - returns: A record of type `returnedType`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
public func upsertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
as returnedType: T.Type,
onConflict conflictTarget: [String] = [],
updating strategy: UpsertUpdateStrategy = .allColumns,
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
throws -> T
{
try willSave(db)
var success: (inserted: InsertionSuccess, returned: T)?
try aroundSave(db) {
success = try upsertAndFetchWithCallbacks(
db, onConflict: conflictTarget,
updating: strategy, doUpdate: assignments,
selection: T.databaseSelection,
decode: { try T(row: $0) })
return PersistenceSuccess(success!.inserted)
}
guard let success else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(PersistenceSuccess(success.inserted))
return success.returned
}
#endif
}
// MARK: - Internal
+1 -1
View File
@@ -134,7 +134,7 @@ import Foundation
/// - ``select(_:as:)-tjh0``
/// - ``updateAll(_:onConflict:_:)-7vv9x``
/// - ``updateAll(_:onConflict:_:)-7atfw``
public protocol TableRecord: SendableMetatype {
public protocol TableRecord: GRDBSendableMetatype {
/// A type that defines columns.
///
/// For example:
+2 -2
View File
@@ -27,7 +27,7 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
self.attemptToFulfill = attemptToFulfill
}
func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
func receive<S>(subscriber: S) where S: Subscriber & GRDBSendableMetatype, Failure == S.Failure, Output == S.Input {
let subscription = OnDemandFutureSubscription(
attemptToFulfill: attemptToFulfill,
downstream: subscriber)
@@ -36,7 +36,7 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
}
private class OnDemandFutureSubscription<Downstream>: Subscription, @unchecked Sendable
where Downstream: Subscriber & SendableMetatype
where Downstream: Subscriber & GRDBSendableMetatype
{
// @unchecked because `state` is protected with `lock`.
typealias Promise = @Sendable (Result<Downstream.Input, Downstream.Failure>) -> Void
+11 -1
View File
@@ -23,10 +23,20 @@ public func databaseQuestionMarks(count: Int) -> String {
repeatElement("?", count: count).joined(separator: ",")
}
#if compiler(>=6.2)
/// A synonym for the standard `SendableMetatype` protocol in Swift 6.2,
/// and `Any` in previous compiler versions.
public typealias GRDBSendableMetatype = SendableMetatype
#else
/// A synonym for the standard `SendableMetatype` protocol in Swift 6.2,
/// and `Any` in previous compiler versions.
public typealias GRDBSendableMetatype = Any
#endif
// MARK: - Internal
/// Reserved for GRDB: do not use.
@inline(always)
@inline(__always)
@inlinable
func GRDBPrecondition(
_ condition: @autoclosure() -> Bool,
@@ -11,7 +11,7 @@
// which is its `Fetcher`.
/// Implementation details of `ValueReducer`.
public protocol _ValueReducer: SendableMetatype {
public protocol _ValueReducer: GRDBSendableMetatype {
/// The Sendable type that fetches database values
associatedtype Fetcher: _ValueReducerFetcher
+3 -14
View File
@@ -429,20 +429,9 @@ public struct AsyncValueObservation<Element: Sendable>: AsyncSequence, Sendable
var iterator: AsyncThrowingStream<Element, Error>.AsyncIterator
let cancellable: AnyDatabaseCancellable
// @concurrent in order to avoid a compiler error:
// > Sending 'self.iterator' risks causing data races
// On systems where `AsyncThrowingStream.Iterator.next(isolation:)`
// is available, `next(isolation:)` below is used instead.
@concurrent public mutating func next() async throws -> Element? {
public mutating func next() async throws -> Element? {
try await iterator.next()
}
@available(iOS 18, macOS 15, tvOS 18, watchOS 11, visionOS 2, *)
public mutating func next(
isolation actor: isolated (any Actor)?
) async throws(any Error) -> Element? {
try await iterator.next(isolation: actor)
}
}
}
@@ -523,7 +512,7 @@ extension DatabasePublishers {
}
public func receive<S>(subscriber: S)
where S: Subscriber & SendableMetatype,
where S: Subscriber & GRDBSendableMetatype,
Failure == S.Failure,
Output == S.Input
{
@@ -536,7 +525,7 @@ extension DatabasePublishers {
private class ValueSubscription<Downstream>:
Subscription, @unchecked Sendable
where Downstream: Subscriber & SendableMetatype,
where Downstream: Subscriber & GRDBSendableMetatype,
Downstream.Failure == Error
{
// @unchecked Sendable because `cancellable` and `state` are
+2 -6
View File
@@ -8,7 +8,7 @@
/* Begin PBXBuildFile section */
56781B08243F7B5300650A83 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; };
56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Public, ); }; };
56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
EED476F21CFD17270026A4EC /* GRDBCustomSQLite-USER.h in Headers */ = {isa = PBXBuildFile; fileRef = EED476F11CFD16FF0026A4EC /* GRDBCustomSQLite-USER.h */; settings = {ATTRIBUTES = (Public, ); }; };
F3BA80931CFB2F13003DC1BA /* GRDB.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF11CFB23D3003DC1BA /* GRDB.h */; settings = {ATTRIBUTES = (Public, ); }; };
F3BA80951CFB2F18003DC1BA /* sqlite3.h in Headers */ = {isa = PBXBuildFile; fileRef = F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */; settings = {ATTRIBUTES = (Public, ); }; };
@@ -259,7 +259,7 @@
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0730;
LastUpgradeCheck = 2720;
LastUpgradeCheck = 2600;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
F3BA80591CFB2BB2003DC1BA = {
@@ -428,7 +428,6 @@
DEAD_CODE_STRIPPING = YES;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
@@ -487,7 +486,6 @@
DEAD_CODE_STRIPPING = YES;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
@@ -524,7 +522,6 @@
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_NO_COMMON_BLOCKS = YES;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -560,7 +557,6 @@
DYLIB_CURRENT_VERSION = 1;
DYLIB_INSTALL_NAME_BASE = "@rpath";
ENABLE_MODULE_VERIFIER = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_NO_COMMON_BLOCKS = YES;
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
LD_RUNPATH_SEARCH_PATHS = (
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "2720"
LastUpgradeVersion = "2600"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
+30 -2
View File
@@ -8,7 +8,7 @@
# make distclean - Restore repository to a pristine state
default: test
smokeTest: test_framework_GRDBiOS_maxTarget test_framework_GRDBiOS_minTarget test_framework_SQLCipher4Encrypted test_framework_GRDBCustomSQLiteiOS_maxTarget test_SPM
smokeTest: test_framework_GRDBiOS_maxTarget test_framework_GRDBiOS_minTarget test_framework_SQLCipher3 test_framework_SQLCipher4Encrypted test_framework_GRDBCustomSQLiteiOS_maxTarget test_SPM
# =====
# Tools
@@ -77,7 +77,7 @@ test_framework: test_framework_darwin
test_framework_darwin: test_framework_GRDB test_framework_GRDBCustom test_framework_SQLCipher test_SPM
test_framework_GRDB: test_framework_GRDBOSX test_framework_GRDBiOS test_framework_GRDBtvOS
test_framework_GRDBCustom: test_framework_GRDBCustomSQLiteOSX test_framework_GRDBCustomSQLiteiOS
test_framework_SQLCipher: test_framework_SQLCipher4 test_framework_SQLCipher4Encrypted
test_framework_SQLCipher: test_framework_SQLCipher3 test_framework_SQLCipher3Encrypted test_framework_SQLCipher4 test_framework_SQLCipher4Encrypted
test_archive: test_universal_xcframework
test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods
test_CocoaPodsLint: test_CocoaPodsLint_GRDB
@@ -159,6 +159,34 @@ test_framework_GRDBCustomSQLiteiOS_minTarget: SQLiteCustom
$(TEST_ACTIONS) \
$(XCPRETTY)
test_framework_SQLCipher3:
ifdef POD
cd Tests/CocoaPods/SQLCipher3 && \
$(POD) install && \
$(XCODEBUILD) \
-workspace GRDBTests.xcworkspace \
-scheme GRDBTests \
build-for-testing test-without-building \
$(XCPRETTY)
else
@echo CocoaPods must be installed for test_framework_SQLCipher3
@exit 1
endif
test_framework_SQLCipher3Encrypted:
ifdef POD
cd Tests/CocoaPods/SQLCipher3 && \
$(POD) install && \
$(XCODEBUILD) \
-workspace GRDBTests.xcworkspace \
-scheme GRDBEncryptedTests \
build-for-testing test-without-building \
$(XCPRETTY)
else
@echo CocoaPods must be installed for test_framework_SQLCipher3Encrypted
@exit 1
endif
test_framework_SQLCipher4:
ifdef POD
cd Tests/CocoaPods/SQLCipher4 && \
+7 -8
View File
@@ -1,4 +1,4 @@
// swift-tools-version:6.4
// swift-tools-version:6.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import Foundation
@@ -48,10 +48,10 @@ let package = Package(
name: "GRDB",
defaultLocalization: "en", // for tests
platforms: [
.iOS(.v15),
.macOS(.v12),
.tvOS(.v15),
.watchOS(.v9),
.iOS(.v13),
.macOS(.v10_15),
.tvOS(.v13),
.watchOS(.v7),
],
products: [
// GRDB+SQLCipher: Delete the GRDBSQLite library
@@ -84,8 +84,6 @@ let package = Package(
cSettings: cSettings,
swiftSettings: swiftSettings + [
.enableUpcomingFeature("MemberImportVisibility"),
.enableUpcomingFeature("NonisolatedNonsendingByDefault"),
.enableUpcomingFeature("InferIsolatedConformances"),
]),
.testTarget(
name: "GRDBTests",
@@ -117,5 +115,6 @@ let package = Package(
.enableUpcomingFeature("InferSendableFromCaptures"),
.enableUpcomingFeature("GlobalActorIsolatedTypesUsability"),
])
]
],
swiftLanguageModes: [.v6]
)
+13 -4
View File
@@ -10,14 +10,14 @@
</p>
<p align="center">
<a href="https://developer.apple.com/swift/"><img alt="Swift 6.4" src="https://img.shields.io/badge/swift-6.4-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>
**Latest release**: November 30, 2026 • [version 7.12.1](https://github.com/groue/GRDB.swift/tree/v7.12.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Requirements**: iOS 15.0+ / macOS 12.0+ / tvOS 15.0+ / watchOS 9.0+ &bull; SQLite 3.36.0+ &bull; Swift 6.4+ / Xcode 27.0+
**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**:
@@ -2181,6 +2181,8 @@ For more information about batch updates, see [Update Requests](#update-requests
[UPSERT](https://www.sqlite.org/lang_UPSERT.html) is an SQLite feature that causes an INSERT to behave as an UPDATE or a no-op if the INSERT would violate a uniqueness constraint (primary key or unique index).
> **Note**: Upsert apis are available from SQLite 3.35.0+: iOS 15.0+, macOS 12.0+, tvOS 15.0+, watchOS 8.0+, or with a [custom SQLite build] or [SQLCipher](#encryption).
>
> **Note**: With regard to [persistence callbacks](#available-callbacks), an upsert behaves exactly like an insert. In particular: the `aroundInsert(_:)` and `didInsert(_:)` callbacks report the rowid of the inserted or updated row; `willUpdate`, `aroundUpdate`, `didUpdate` are not called.
[PersistableRecord] provides three upsert methods:
@@ -2273,6 +2275,8 @@ For more information about batch updates, see [Update Requests](#update-requests
SQLite is able to return values from an inserted, updated, or deleted row, with the [`RETURNING` clause](https://www.sqlite.org/lang_returning.html).
> **Note**: Support for the `RETURNING` clause is available from SQLite 3.35.0+: iOS 15.0+, macOS 12.0+, tvOS 15.0+, watchOS 8.0+, or with a [custom SQLite build] or [SQLCipher](#encryption).
The `RETURNING` clause helps deal with database features such as auto-incremented ids, default values, and [generated columns](https://sqlite.org/gencol.html). You can, for example, insert a few columns and fetch the default or generated ones in one step.
GRDB uses the `RETURNING` clause in all persistence methods that contain `AndFetch` in their name.
@@ -4582,15 +4586,20 @@ try Player.customRequest().fetchAll(db) // [Player]
Encryption
==========
**GRDB can encrypt your database with [SQLCipher](http://sqlcipher.net) v4.5+.**
**GRDB can encrypt your database with [SQLCipher](http://sqlcipher.net) v3.4+.**
To use SQLCipher with the [Swift Package Manager](https://swift.org/package-manager/), you must fork GRDB, and modify `Package.swift`. Instructions are in the file itself, in comments that contain "GRDB+SQLCipher".
To use SQLCipher with [CocoaPods](http://cocoapods.org/), specify in your `Podfile`:
```ruby
# GRDB with SQLCipher 4
pod 'GRDB.swift/SQLCipher'
pod 'SQLCipher', '~> 4.5'
pod 'SQLCipher', '~> 4.0'
# GRDB with SQLCipher 3
pod 'GRDB.swift/SQLCipher'
pod 'SQLCipher', '~> 3.4'
```
Make sure you remove any existing `pod 'GRDB.swift'` from your Podfile. `GRDB.swift/SQLCipher` must be the only active GRDB pod in your whole project, or you will face linker or runtime errors, due to the conflicts between SQLCipher and the system SQLite.
-2
View File
@@ -14,5 +14,3 @@ 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.1
SWIFT_UPCOMING_FEATURE_NONISOLATED_NONSENDING_BY_DEFAULT = YES
SWIFT_UPCOMING_FEATURE_INFER_ISOLATED_CONFORMANCES = YES
+1 -1
View File
@@ -1,4 +1,4 @@
IPHONEOS_DEPLOYMENT_TARGET = 15.0
MACOSX_DEPLOYMENT_TARGET = 12.0
TVOS_DEPLOYMENT_TARGET = 15.0
WATCHOS_DEPLOYMENT_TARGET = 9.0
WATCHOS_DEPLOYMENT_TARGET = 8.0
+5
View File
@@ -9,6 +9,7 @@ static inline void _registerErrorLogCallback(_errorLogCallback callback) {
sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
}
#if SQLITE_VERSION_NUMBER >= 3029000
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
/// be used from Swift.
static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) {
@@ -22,4 +23,8 @@ static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) {
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0);
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0);
}
#else
static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { }
static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { }
#endif
#endif /* grdb_config_h */
+1 -1
View File
@@ -59,7 +59,7 @@ opt_in_rules:
- pattern_matching_keywords
- prohibited_super_call
- reduce_into
- redundant_self
- redundant_self_in_closure
- redundant_type_annotation
- shorthand_optional_binding
- sorted_first_last
@@ -11,6 +11,7 @@ static inline void _registerErrorLogCallback(_errorLogCallback callback) {
sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
}
#if SQLITE_VERSION_NUMBER >= 3029000
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
/// be used from Swift.
static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) {
@@ -24,4 +25,8 @@ static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) {
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0);
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0);
}
#else
static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { }
static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { }
#endif
#endif /* grdb_config_h */
+5
View File
@@ -8,6 +8,7 @@ static inline void _registerErrorLogCallback(_errorLogCallback callback) {
sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
}
#if SQLITE_VERSION_NUMBER >= 3029000
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
/// be used from Swift.
static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) {
@@ -21,6 +22,10 @@ static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) {
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0);
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0);
}
#else
static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { }
static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { }
#endif
// Expose APIs that are missing from system <sqlite3.h>
#ifdef GRDB_SQLITE_ENABLE_PREUPDATE_HOOK
-2
View File
@@ -4,9 +4,7 @@ PRODUCT_NAME = GRDB
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.$(PRODUCT_NAME:rfc1034identifier)
MODULEMAP_FILE = $(SRCROOT)/Support/module.modulemap
SWIFT_VERSION = 6.1
SWIFT_UPCOMING_FEATURE_NONISOLATED_NONSENDING_BY_DEFAULT = YES
OTHER_SWIFT_FLAGS = $(inherited) -D GRDBFRAMEWORK
SWIFT_UPCOMING_FEATURE_INFER_ISOLATED_CONFORMANCES = YES
// Slow compilation hunt:
// OTHER_SWIFT_FLAGS = $(inherited) -Xfrontend -warn-long-expression-type-checking=100 -Xfrontend -warn-long-function-bodies=100
+1 -1
View File
@@ -1,7 +1,7 @@
IPHONEOS_DEPLOYMENT_TARGET = 15.0
MACOSX_DEPLOYMENT_TARGET = 12.0
TVOS_DEPLOYMENT_TARGET = 15.0
WATCHOS_DEPLOYMENT_TARGET = 9.0
WATCHOS_DEPLOYMENT_TARGET = 8.0
OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_SNAPSHOT
//// Compile with all opt-in APIs
+5
View File
@@ -11,6 +11,7 @@ static inline void _registerErrorLogCallback(_errorLogCallback callback) {
sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
}
#if SQLITE_VERSION_NUMBER >= 3029000
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
/// be used from Swift.
static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) {
@@ -24,4 +25,8 @@ static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) {
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0);
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0);
}
#else
static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { }
static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { }
#endif
#endif /* grdb_config_h */
+5
View File
@@ -11,6 +11,7 @@ static inline void _registerErrorLogCallback(_errorLogCallback callback) {
sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
}
#if SQLITE_VERSION_NUMBER >= 3029000
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
/// be used from Swift.
static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) {
@@ -24,6 +25,10 @@ static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) {
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0);
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0);
}
#else
static inline void _disableDoubleQuotedStringLiterals(sqlite3 *db) { }
static inline void _enableDoubleQuotedStringLiterals(sqlite3 *db) { }
#endif
// Expose APIs that are missing from system <sqlite3.h>
#ifdef GRDB_SQLITE_ENABLE_PREUPDATE_HOOK
+1 -1
View File
@@ -6,7 +6,7 @@ pod 'GRDB.swift', :path => '../../..'
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
# Workaround for Xcode 27
# Workaround for Xcode Xcode 27
# https://github.com/CocoaPods/CocoaPods/issues/11839
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '15.0'
end
+1 -1
View File
@@ -5,7 +5,7 @@ pod 'GRDB.swift', :path => '../../..'
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
# Workaround for Xcode 27
# Workaround for Xcode Xcode 27
# https://github.com/CocoaPods/CocoaPods/issues/11839
config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '15.0'
end
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:SQLCipher4.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1340"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "564A2095226B8E18001F64F1"
BuildableName = "GRDBTestsEncrypted.xctest"
BlueprintName = "GRDBTestsEncrypted"
ReferencedContainer = "container:GRDBTests.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "564A2095226B8E18001F64F1"
BuildableName = "GRDBTestsEncrypted.xctest"
BlueprintName = "GRDBTestsEncrypted"
ReferencedContainer = "container:GRDBTests.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1100"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "NO"
buildForProfiling = "NO"
buildForArchiving = "NO"
buildForAnalyzing = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "564A1F1C226B876D001F64F1"
BuildableName = "GRDBTests.xctest"
BlueprintName = "GRDBTests"
ReferencedContainer = "container:GRDBTests.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "564A1F1C226B876D001F64F1"
BuildableName = "GRDBTests.xctest"
BlueprintName = "GRDBTests"
ReferencedContainer = "container:GRDBTests.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "564A1F1C226B876D001F64F1"
BuildableName = "GRDBTests.xctest"
BlueprintName = "GRDBTests"
ReferencedContainer = "container:GRDBTests.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:GRDBTests.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
+24
View File
@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>LSApplicationCategoryType</key>
<string></string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>BNDL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
+43
View File
@@ -0,0 +1,43 @@
platform :macos, '12.0'
use_frameworks!
def common
pod 'GRDB.swift/SQLCipher', path: '../../..'
pod 'SQLCipher', '~> 3.0', inhibit_warnings: true
end
target 'GRDBTests' do
common
end
target 'GRDBTestsEncrypted' do
common
end
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
# Workaround for Xcode 14.3+/Xcode 27
# https://github.com/CocoaPods/CocoaPods/issues/11839
config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '12.0'
config.build_settings['GCC_OPTIMIZATION_LEVEL'] = '3'
end
end
# TODO: remove when https://github.com/CocoaPods/CocoaPods/pull/12009 is merged.
# https://github.com/CocoaPods/CocoaPods/issues/12012#issuecomment-1655191516
installer.aggregate_targets.each do |target|
target.xcconfigs.each do |variant, xcconfig|
xcconfig_path = target.client_root + target.xcconfig_relative_path(variant)
IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
end
end
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
if config.base_configuration_reference.is_a? Xcodeproj::Project::Object::PBXFileReference
xcconfig_path = config.base_configuration_reference.real_path
IO.write(xcconfig_path, IO.read(xcconfig_path).gsub("DT_TOOLCHAIN_DIR", "TOOLCHAIN_DIR"))
end
end
end
end
+1 -1
View File
@@ -3,7 +3,7 @@ use_frameworks!
def common
pod 'GRDB.swift/SQLCipher', path: '../../..'
pod 'SQLCipher', '~> 4.5', inhibit_warnings: true
pod 'SQLCipher', '~> 4.0', inhibit_warnings: true
end
target 'GRDBTests' do
@@ -135,10 +135,14 @@ class DatabaseConfigurationTests: GRDBTestCase {
// Test SQLITE_DBCONFIG_DQS_DML
do {
_ = try dbQueue.inDatabase { db in
let foo = try dbQueue.inDatabase { db in
try String.fetchOne(db, sql: "SELECT \"foo\" FROM player")
}
XCTFail("Expected error")
if Database.sqliteLibVersionNumber >= 3029000 {
XCTFail("Expected error")
} else {
XCTAssertEqual(foo, "foo")
}
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.sql, "SELECT \"foo\" FROM player")
@@ -149,7 +153,9 @@ class DatabaseConfigurationTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE INDEX i ON player(\"foo\")")
}
XCTFail("Expected error")
if Database.sqliteLibVersionNumber >= 3029000 {
XCTFail("Expected error")
}
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.sql, "CREATE INDEX i ON player(\"foo\")")
@@ -197,6 +197,14 @@ class DatabaseWriterTests : GRDBTestCase {
}
func testVacuumInto() throws {
guard #available(iOS 14, macOS 10.16, tvOS 14, *) else {
throw XCTSkip("VACUUM INTO is not available")
}
// Prevent SQLCipher failures
guard Database.sqliteLibVersionNumber >= 3027000 else {
throw XCTSkip("VACUUM INTO is not available")
}
func testVacuumInto(writer: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("init") { db in
@@ -355,7 +363,13 @@ class DatabaseWriterTests : GRDBTestCase {
try await test(setup(makeDatabasePool()))
}
@available(iOS 14, macOS 10.16, tvOS 14, *) // async + vacuum into
func testAsyncAwait_vacuumInto() async throws {
// Prevent SQLCipher failures
guard Database.sqliteLibVersionNumber >= 3027000 else {
throw XCTSkip("VACUUM INTO is not available")
}
func setup<T: DatabaseWriter>(_ dbWriter: T) throws -> T {
try dbWriter.write { db in
try db.execute(sql: "CREATE TABLE t (id INTEGER PRIMARY KEY)")
@@ -86,7 +86,11 @@ class FTS3TableBuilderTests: GRDBTestCase {
}
}
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
func testUnicode61TokenizerDiacriticsRemove() throws {
guard Database.sqliteLibVersionNumber >= 3027000 else {
throw XCTSkip("remove_diacritics=2 is not available")
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
@@ -95,7 +99,21 @@ class FTS3TableBuilderTests: GRDBTestCase {
assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts3(tokenize=unicode61 \"remove_diacritics=2\")")
}
}
#else
func testUnicode61TokenizerDiacriticsRemove() throws {
guard #available(iOS 14, macOS 10.16, tvOS 14, *) else {
throw XCTSkip("remove_diacritics=2 is not available")
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", using: FTS3()) { t in
t.tokenizer = .unicode61(diacritics: .remove)
}
assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts3(tokenize=unicode61 \"remove_diacritics=2\")")
}
}
#endif
func testUnicode61TokenizerSeparators() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more