mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-04 05:08:44 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b44628b9cd |
No files matched your search
@@ -18,11 +18,12 @@ Please fill out this template when filing an issue.
|
||||
|
||||
### Environment
|
||||
|
||||
**GRDB flavor(s):** (GRDB, SQLCipher, Custom SQLite build?)
|
||||
**GRDB version:**
|
||||
**Enabled SwiftPM traits:**
|
||||
**Installation method:** (CocoaPods, SPM, manual?)
|
||||
**Xcode version:**
|
||||
**Swift version:**
|
||||
**Platform(s) running GRDB:**
|
||||
**Platform(s) running GRDB:** (iOS, macOS, watchOS?)
|
||||
**macOS version running Xcode:**
|
||||
|
||||
### Demo Project
|
||||
|
||||
+59
-42
@@ -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-14-Readme.md
|
||||
|
||||
name: "GRDB CI"
|
||||
|
||||
@@ -8,7 +8,7 @@ on:
|
||||
- master
|
||||
- development
|
||||
paths:
|
||||
- 'Sources/**'
|
||||
- 'GRDB/**'
|
||||
- 'Tests/**'
|
||||
- '.github/workflows/**'
|
||||
- 'Makefile'
|
||||
@@ -16,7 +16,7 @@ on:
|
||||
- 'SQLiteCustom/src'
|
||||
pull_request:
|
||||
paths:
|
||||
- 'Sources/**'
|
||||
- 'GRDB/**'
|
||||
- 'Tests/**'
|
||||
- '.github/workflows/**'
|
||||
- 'Makefile'
|
||||
@@ -40,20 +40,20 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_27.2.app"
|
||||
runsOn: xcode-27
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_27.2.app"
|
||||
runsOn: xcode-27
|
||||
destination: "OS=27.2,name=iPhone 17"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.1,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.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.1,name=Apple TV"
|
||||
name: "tvOS"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
|
||||
SPM:
|
||||
@@ -66,13 +66,30 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_27.2.app"
|
||||
runsOn: xcode-27
|
||||
name: "Xcode 27.2"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
- 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.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher3Encrypted
|
||||
SQLCipher4:
|
||||
name: SQLCipher4
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
@@ -83,30 +100,30 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_27.2.app"
|
||||
runsOn: xcode-27
|
||||
name: "Xcode 27.2"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_SPM_SQLCipherEncrypted
|
||||
# CustomSQLite:
|
||||
# name: CustomSQLite
|
||||
# runs-on: ${{ matrix.runsOn }}
|
||||
# env:
|
||||
# DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
# timeout-minutes: 60
|
||||
# strategy:
|
||||
# fail-fast: false
|
||||
# matrix:
|
||||
# include:
|
||||
# - xcode: "Xcode_27.2.app"
|
||||
# runsOn: xcode-27
|
||||
# name: "Xcode 27.2"
|
||||
# steps:
|
||||
# - uses: actions/checkout@v5
|
||||
# - name: ${{ matrix.name }}
|
||||
# run: make test_framework_GRDBCustomSQLiteOSX
|
||||
run: make test_framework_SQLCipher4Encrypted
|
||||
CustomSQLite:
|
||||
name: CustomSQLite
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
env:
|
||||
DEVELOPER_DIR: "/Applications/${{ matrix.xcode }}/Contents/Developer"
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBCustomSQLiteOSX
|
||||
XCFramework:
|
||||
name: XCFramework
|
||||
runs-on: ${{ matrix.runsOn }}
|
||||
@@ -117,11 +134,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_27.2.app"
|
||||
runsOn: xcode-27
|
||||
name: "Xcode 27.2"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_universal_xcframework
|
||||
|
||||
+6
-1
@@ -71,7 +71,6 @@ Session.vim
|
||||
# Build generated
|
||||
build/
|
||||
DerivedData
|
||||
/Package.resolved
|
||||
|
||||
# Various settings
|
||||
*.pbxuser
|
||||
@@ -101,6 +100,10 @@ xcuserdata
|
||||
SQLiteCustom/GRDBCustomSQLite-USER.h
|
||||
SQLiteCustom/GRDBCustomSQLite-USER.xcconfig
|
||||
|
||||
# CocoaPods test
|
||||
Pods
|
||||
Podfile.lock
|
||||
|
||||
# SPM
|
||||
.build
|
||||
GRDB.xcworkspace/xcshareddata/swiftpm
|
||||
@@ -110,3 +113,5 @@ Tests/SPM/Packages
|
||||
# Ruby
|
||||
.ruby-version
|
||||
|
||||
# Test products
|
||||
Tests/products
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
[submodule "SQLiteCustom/src"]
|
||||
path = SQLiteCustom/src
|
||||
url = https://github.com/groue/SQLiteLib
|
||||
url = https://github.com/swiftlyfalling/SQLiteLib.git
|
||||
@@ -2,4 +2,4 @@ version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [GRDB]
|
||||
swift_version: 6.1
|
||||
swift_version: 6.0
|
||||
+161
@@ -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
|
||||
Vendored
-7
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"editor.formatOnSave": false,
|
||||
"editor.insertSpaces": true,
|
||||
"editor.tabSize": 4,
|
||||
"editor.detectIndentation": false,
|
||||
"editor.trimAutoWhitespace": false
|
||||
}
|
||||
+1
-119
@@ -7,12 +7,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 7.x Releases
|
||||
|
||||
- `7.12.x` Releases - [7.12.0](#7120) - [7.12.1](#7121)
|
||||
- `7.11.x` Releases - [7.11.0](#7110) - [7.11.1](#7111)
|
||||
- `7.10.x` Releases - [7.10.0](#7100)
|
||||
- `7.9.x` Releases - [7.9.0](#790)
|
||||
- `7.8.x` Releases - [7.8.0](#780)
|
||||
- `7.7.x` Releases - [7.7.0](#770) - [7.7.1](#771)
|
||||
- `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761)
|
||||
- `7.5.x` Releases - [7.5.0](#750)
|
||||
- `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741)
|
||||
@@ -144,118 +138,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## Unreleased
|
||||
|
||||
[Migrating From GRDB 7 to GRDB 8](Documentation/GRDB8MigrationGuide.md) describes how to bump the GRDB version in your application.
|
||||
|
||||
- **New**: Xcode 27 compatibility
|
||||
- **New**: Bump custom SQLite build to version 3.54.1
|
||||
- **New**: SQLCipher package trait by [@GeorgeElsham](https://github.com/GeorgeElsham) and [@groue](https://github.com/groue) in [#1902](https://github.com/groue/GRDB.swift/pull/1902)
|
||||
- **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.
|
||||
- **New**: Async database accesses accept `sending` closures and return `sending` results, instead of requiring `Sendable`.
|
||||
- **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
|
||||
- **Breaking Change**: Drop CocoaPods support
|
||||
- **Breaking Change**: `FetchableRecord.databaseDecodingUserInfo` and `EncodableRecord.databaseEncodingUserInfo` are now declared as `[CodingUserInfoKey: any Sendable]`, as `JSONDecoder.userInfo` and `JSONEncoder.userInfo` are.
|
||||
- **Breaking Change**: Remove deprecated APIs
|
||||
|
||||
## 7.12.1
|
||||
|
||||
Released November 30, 2026
|
||||
|
||||
- **New**: Optimize database read reentrancy checks by [@groue](https://github.com/groue) and [@renchris](https://github.com/renchris) in [#1897](https://github.com/groue/GRDB.swift/pull/1897)
|
||||
- **Fixed**: Ignore interruptions when entering the read-only mode by [@uveshm003](https://github.com/uveshm003) in [#1900](https://github.com/groue/GRDB.swift/pull/1900)
|
||||
|
||||
## 7.12.0
|
||||
|
||||
Released November 1, 2026
|
||||
|
||||
- **New**: Add support for Strings that contain the NUL character by [@groue](https://github.com/groue) and [@nesevis](https://github.com/nesevis) in [#1885](https://github.com/groue/GRDB.swift/pull/1885)
|
||||
- **New**: Keep SQLite's error message when a database fails to open by [@builtbysharath](https://github.com/builtbysharath) in [#1889](https://github.com/groue/GRDB.swift/pull/1889)
|
||||
- **Fixed**: Fix doubled word in doc comment by [@latent-9](https://github.com/latent-9) in [#1876](https://github.com/groue/GRDB.swift/pull/1876)
|
||||
- **Fixed**: Fix an accidentally quadratic behavior in SQLite statement compilation by [@groue](https://github.com/groue) and [@guidedways](https://github.com/guidedways) in [#1881](https://github.com/groue/GRDB.swift/pull/1881)
|
||||
- **Fixed**: Work around an SQLite bug in WAL snapshot ordering by [@groue](https://github.com/groue) and [@vburojevic](https://github.com/vburojevic) in [#1884](https://github.com/groue/GRDB.swift/pull/1884)
|
||||
- **Fixed**: Fix upsert for WITHOUT ROWID tables with an INTEGER primary key by [@nesevis](https://github.com/nesevis) in [#1879](https://github.com/groue/GRDB.swift/pull/1879)
|
||||
- **Fixed**: Support for statement recompilation after the columns are modified in the database schema by [@groue](https://github.com/groue) in [#1893](https://github.com/groue/GRDB.swift/pull/1893)
|
||||
- **Fixed**: Fix SharedValueObservation deadlock, ordering, and cancellation by [@groue](https://github.com/groue) in [#1894](https://github.com/groue/GRDB.swift/pull/1894)
|
||||
|
||||
## 7.11.1
|
||||
|
||||
Released June 18, 2026
|
||||
|
||||
- **New**: Make migration registration an O(1) operation [@MarkusSintonen](https://github.com/MarkusSintonen) in [#1869](https://github.com/groue/GRDB.swift/pull/1869)
|
||||
|
||||
## 7.11.0
|
||||
|
||||
Released June 1, 2026
|
||||
|
||||
- **New**: Add option to disable database change filtering in `TransactionObserver` by [@simolus3](https://github.com/simolus3) in [#1864](https://github.com/groue/GRDB.swift/pull/1864)
|
||||
- **Fixed**: Fix upsert for WITHOUT ROWID tables by [@groue](https://github.com/groue) in [#1858](https://github.com/groue/GRDB.swift/pull/1858)
|
||||
|
||||
## 7.10.0
|
||||
|
||||
Released February 15, 2026
|
||||
|
||||
- **Documentation fixes** by [@bellebethcooper](https://github.com/bellebethcooper), [@Cykelero](https://github.com/Cykelero), and [@leejungyeob](https://github.com/leejungyeob) in [#1842](https://github.com/groue/GRDB.swift/pull/1842), [#1846](https://github.com/groue/GRDB.swift/pull/1846), [#1848](https://github.com/groue/GRDB.swift/pull/1848)
|
||||
- **New**: Linux adjustments by [@thinkpractice](https://github.com/thinkpractice) in [#1825](https://github.com/groue/GRDB.swift/pull/1825)
|
||||
- **New**: SQLCipher adjustments by [@R4N](https://github.com/R4N) in [#1845](https://github.com/groue/GRDB.swift/pull/1845)
|
||||
- **New**: Android and Windows adjustments by [@marcprux](https://github.com/marcprux) in [#1849](https://github.com/groue/GRDB.swift/pull/1849), [#1850](https://github.com/groue/GRDB.swift/pull/1850)
|
||||
- **New**: Configure whether UPSERT should update all columns, or no column by [@groue](https://github.com/groue) in [#1852](https://github.com/groue/GRDB.swift/pull/1852)
|
||||
|
||||
## 7.9.0
|
||||
|
||||
Released December 13, 2025
|
||||
|
||||
- **Breaking Change**: Simplify the compiler checks for the availability of SQLite snapshots by [@groue](https://github.com/groue) in [#1826](https://github.com/groue/GRDB.swift/pull/1826)
|
||||
|
||||
This change aims at easing Linux and Android compatibility.
|
||||
|
||||
**The library requirements are raised to Swift 6.1+, Xcode 16.3+.**
|
||||
|
||||
- **Breaking Change**: Accept multiple SQLCipher libraries by [@groue](https://github.com/groue) in [#1819](https://github.com/groue/GRDB.swift/pull/1819)
|
||||
|
||||
This change aims at easing building GRDB against various SQLCipher flavors.
|
||||
|
||||
**The compiler flag that enables new GRDB APIs for SQLCipher is now `SQLITE_HAS_CODEC`.**
|
||||
|
||||
- **Fixed**: Fix cancellation of async tasks that use the FTS5 full-text engine by [@groue](https://github.com/groue) in [#1839](https://github.com/groue/GRDB.swift/pull/1839)
|
||||
|
||||
This workarounds an [SQLite bug](https://sqlite.org/forum/forumpost/95413eb410) that would trigger a GRDB crash, and improves the robustness of the library regarding database accesses cancellation and database interruption.
|
||||
|
||||
- **New**: Improve the ergonomics of `DatabaseMigrator.registerMigration(_:foreignKeyChecks:merging:migrate)`, introduced in [#1818](https://github.com/groue/GRDB.swift/pull/1818), by accepting that the name of the merged migration is included in the set of merged migrations:
|
||||
|
||||
```swift
|
||||
// Used to fail, now OK:
|
||||
migrator.registerMigration("v3", merging: ["v1", "v2", "v3"]) { ... }
|
||||
// ~~~~ ~~~~
|
||||
|
||||
// The above code is equivalent to:
|
||||
migrator.registerMigration("v3", merging: ["v1", "v2"]) { ... }
|
||||
```
|
||||
|
||||
## 7.8.0
|
||||
|
||||
Released October 2, 2025
|
||||
|
||||
- **New**: Merged Migrations by [@groue](https://github.com/groue) in [#1818](https://github.com/groue/GRDB.swift/pull/1818)
|
||||
|
||||
## 7.7.1
|
||||
|
||||
Released September 29, 2025
|
||||
|
||||
- **Fixed**: Fix the save() method for record types with attached triggers by [@groue](https://github.com/groue) in [#1822](https://github.com/groue/GRDB.swift/pull/1822)
|
||||
|
||||
## 7.7.0
|
||||
|
||||
Released September 23, 2025
|
||||
|
||||
- **New**: Update GRDB7MigrationGuide.md reference by [@emmanuel-ferdman](https://github.com/emmanuel-ferdman) in [#1807](https://github.com/groue/GRDB.swift/pull/1807)
|
||||
- **New**: Persistable Database Views by [@groue](https://github.com/groue) in [#1810](https://github.com/groue/GRDB.swift/pull/1810)
|
||||
- **New**: Support for Xcode 26 by [@groue](https://github.com/groue) in [#1813](https://github.com/groue/GRDB.swift/pull/1813)
|
||||
- **Fixed**: Fix another race condition regarding Task cancellation, completing [#1797](https://github.com/groue/GRDB.swift/pull/1797)
|
||||
|
||||
## 7.6.1
|
||||
|
||||
Released July 23, 2025
|
||||
@@ -4465,7 +4347,7 @@ Released April 3, 2017
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- SQLite C API is now available right from the GRDB module: you don't need any longer to import `SQLiteiPhoneOS` module et al (see documentation for [Raw SQLite Pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers)).
|
||||
- SQLite C API is now available right from the GRBD module: you don't need any longer to import `SQLiteiPhoneOS` module et al (see documentation for [Raw SQLite Pointers](https://github.com/groue/GRDB.swift#raw-sqlite-pointers)).
|
||||
- The [manual installation procedure for WatchOS extensions](https://github.com/groue/GRDB.swift#installation) has changed.
|
||||
- [Carthage](https://github.com/Carthage/Carthage) is no longer supported. At the present time it is unable to support the various frameworks built by GRDB (system SQLite, SQLCipher, custom SQLite builds, etc.)
|
||||
|
||||
|
||||
+6
-4
@@ -11,6 +11,7 @@ How you can Contribute
|
||||
|
||||
- For running tests:
|
||||
- Ruby
|
||||
- [CocoaPods](https://cocoapods.org) (gem)
|
||||
- [xcpretty](https://github.com/xcpretty/xcpretty) (gem)
|
||||
- For contributing code:
|
||||
- [Swiftlint](https://github.com/realm/SwiftLint) (present in the `$PATH` or in `/opt/homebrew/bin/`)
|
||||
@@ -27,7 +28,8 @@ How you can Contribute
|
||||
- `GRDB`: GRDB sources
|
||||
- `Tests`: GRDB tests
|
||||
- `GRDBCustom.xcodeproj`: the project which builds GRDB with a custom SQLite build.
|
||||
- `GRDBDemo.xcodeproj`: the demo app.
|
||||
- `GRDBProfiling.xcodeproj`: a project which helps profiling GRDB with Instruments. No code here is really precious.
|
||||
- `GRDBDemoiOS.xcodeproj`, `GRDBCombineDemo.xcodeproj`, `GRDBAsyncDemo.xcodeproj`: the demo apps.
|
||||
|
||||
To work with `GRDBCustom.xcodeproj`:
|
||||
|
||||
@@ -69,11 +71,11 @@ How you can Contribute
|
||||
|
||||
Please keep the reference and the guides up-to-date. To control the quality of your DocC reference documentation, close the workspace, open `Package.swift` in Xcode, and use Product > Build Documentation.
|
||||
|
||||
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what the purpose of your contribution is, how to use it, and what its caveats and corner cases are. When the documentation is hard to write, or reveals too many caveats, it is a sign that the api needs to be fixed.
|
||||
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed.
|
||||
|
||||
8. **Open a pull request with your changes (targeting the `development` branch)!**
|
||||
|
||||
9. **If you are granted push access to the repository**, check [ReleaseProcess.md](Documentation/ReleaseProcess.md) in order to publish a new GRDB version.
|
||||
9. **If you are granted a push access to the repository**, check [ReleaseProcess.md](Documentation/ReleaseProcess.md) in order to publish a new GRDB version.
|
||||
|
||||
|
||||
## Answer issues and contribute to discussions
|
||||
@@ -83,7 +85,7 @@ Answering [issues](https://github.com/groue/GRDB.swift/issues), participating in
|
||||
|
||||
## Financial support and sponsoring
|
||||
|
||||
GRDB is free, and openly developed by its contributors, in their free time, according to their will, needs, and availability. It is not controlled by any company.
|
||||
GRDB is free, and openly developed by its contributors, on their free time, according to their will, needs, and availability. It is not controlled by any company.
|
||||
|
||||
Support is free as well, as long as it happens publicly, and is available to everyone as well as internet search engines. This excludes the private channels of social networks, closed environments such as Slack, etc.
|
||||
|
||||
|
||||
@@ -141,7 +141,7 @@ let request = Book.including(optional: Book.author)
|
||||
let bookInfos = BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
Before we dive in, please remember that associations cannot generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just fine, because your SQL skills are welcome. The [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:)) method can help you consume the rows fetched from joined queries, as in `SELECT book.*, author.* FROM ...`.
|
||||
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome. The [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:)) method can help you consume the rows fetched from joined queries, as in `SELECT book.*, author.* FROM ...`.
|
||||
|
||||
|
||||
## Required Protocols
|
||||
@@ -211,7 +211,7 @@ GRDB handles several types of associations:
|
||||
- **HasOneThrough**
|
||||
- **Associations to common table expressions**
|
||||
|
||||
An association generally declares a link from one record type to another, as in "one book **belongs to** its author". It instructs GRDB to use the foreign keys declared in the database as support for Swift methods.
|
||||
An association generally declares a link from a record type to another, as in "one book **belongs to** its author". It instructs GRDB to use the foreign keys declared in the database as support for Swift methods.
|
||||
|
||||
Each one of these associations is appropriate for a particular database situation.
|
||||
|
||||
@@ -228,7 +228,7 @@ Associations to [common table expressions] are specific enough and are documente
|
||||
|
||||
## BelongsTo
|
||||
|
||||
The **BelongsTo** association sets up a one-to-one connection from a record type to another record type, such that each instance of the declaring record "belongs to" an instance of the other record.
|
||||
The **BelongsTo** association sets up a one-to-one connection from a record type to another record type, such as each instance of the declaring record "belongs to" an instance of the other record.
|
||||
|
||||
For example, if your application includes authors and books, and each book is assigned its author, you'd declare the `Book.author` association as below:
|
||||
|
||||
@@ -243,7 +243,7 @@ struct Author: TableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
The **BelongsTo** association between a book and its author requires that the database table for books has a column that points to the table for authors:
|
||||
The **BelongsTo** association between a book and its author needs that the database table for books has a column that points to the table for authors:
|
||||
|
||||

|
||||
|
||||
@@ -252,7 +252,7 @@ See [Convention for the BelongsTo Association] for some sample code that defines
|
||||
|
||||
## HasMany
|
||||
|
||||
The **HasMany** association indicates a one-to-many connection between two record types, such that each instance of the declaring record "has many" instances of the other record. You'll often find this association on the other side of a **BelongsTo** association.
|
||||
The **HasMany** association indicates a one-to-many connection between two record types, such as each instance of the declaring record "has many" instances of the other record. You'll often find this association on the other side of a **BelongsTo** association.
|
||||
|
||||
For example, if your application includes authors and books, and each author is assigned zero or more books, you'd declare the `Author.books` association as below:
|
||||
|
||||
@@ -266,7 +266,7 @@ struct Book: TableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
The **HasMany** association between an author and its books requires that the database table for books has a column that points to the table for authors:
|
||||
The **HasMany** association between an author and its books needs that the database table for books has a column that points to the table for authors:
|
||||
|
||||

|
||||
|
||||
@@ -290,7 +290,7 @@ struct Demographics: TableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
The **HasOne** association between a country and its demographics requires that the database table for demographics has a column that points to the table for countries:
|
||||
The **HasOne** association between a country and its demographics needs that the database table for demographics has a column that points to the table for countries:
|
||||
|
||||

|
||||
|
||||
@@ -444,7 +444,7 @@ migrator.registerMigration("Employees") { db in
|
||||
}
|
||||
```
|
||||
|
||||
Note that the associations on both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consume this association. For example:
|
||||
Note that the associations on both sides of the self-join use a customized **[association key](#the-structure-of-a-joined-request)**. This helps consuming this association. For example:
|
||||
|
||||
```swift
|
||||
struct EmployeeInfo: FetchableRecord, Decodable {
|
||||
@@ -468,7 +468,7 @@ Associations and the Database Schema
|
||||
|
||||
**Associations are grounded in the database schema, the way database tables are defined.**
|
||||
|
||||
For example, a **[BelongsTo]** association between a book and its author requires that the database table for books has a column that points to the table for authors.
|
||||
For example, a **[BelongsTo]** association between a book and its author needs that the database table for books has a column that points to the table for authors.
|
||||
|
||||
GRDB also comes with several *conventions* for defining your database schema.
|
||||
|
||||
@@ -490,7 +490,7 @@ Make them look like Swift identifiers: `book`, `author`, `postalAddress`.
|
||||
If the database schema does not follow this convention, and has, for example, database tables which are named with underscores (`postal_address`), you can still use associations. But you need to help row consumption by naming your associations with a customized key:
|
||||
|
||||
```swift
|
||||
// Setup for table names that do not follow the expected convention
|
||||
// Setup for table names that does not follow the expected convention
|
||||
|
||||
struct PostalAddress: TableRecord {
|
||||
// Customized table name
|
||||
@@ -507,7 +507,7 @@ GRDB will automatically **pluralize** or **singularize** names in order to help
|
||||
|
||||
For example, the Book and Author records will automatically feed properties named `books`, `author`, or `bookCount` in your decoded records, without any explicit configuration, as long as the names of the backing database tables are "book" and "author".
|
||||
|
||||
The GRDB pluralization mechanisms are very powerful, being capable of pluralizing and singularizing both regular and irregular words (it's directly inspired by the battle-tested [Ruby on Rails inflections](https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-pluralize)).
|
||||
The GRDB pluralization mechanisms are very powerful, being capable of pluralizing and singularizing both regular and irregular words (it's directly inspired from the battle-tested [Ruby on Rails inflections](https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-pluralize)).
|
||||
|
||||
When using class names composed of two or more words, the table name should use the camelCase singular form:
|
||||
|
||||
@@ -665,7 +665,7 @@ migrator.registerMigration("Countries") { db in
|
||||
1. The `country` table has a primary key.
|
||||
2. The `demographics.countryCode` column is used to link a demographic profile to the country it belongs to. This column is indexed in order to ease the selection of the demographics of a country. A foreign key is defined from `demographics.countryCode` column to `country.code`, so that SQLite guarantees that no profile refers to a missing country. The `onDelete: .cascade` option has SQLite automatically delete a profile when its country is deleted. See [Foreign Key Actions] for more information.
|
||||
3. Make the `demographics.countryCode` column not null if you want SQLite to guarantee that all profiles are linked to a country.
|
||||
4. Create a unique index on the `demographics.countryCode` column in order to guarantee the uniqueness of any country's profile.
|
||||
4. Create a unique index on the `demographics.countryCode` column in order to guarantee the unicity of any country's profile.
|
||||
|
||||
The example above uses a string primary key for the "country" table. But generally speaking, all primary keys are supported, including composite primary keys that span several columns.
|
||||
|
||||
@@ -711,9 +711,9 @@ struct Author: TableRecord {
|
||||
|
||||
> **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns.
|
||||
>
|
||||
> **Warning**: SQLite voids foreign key constraints when one or more foreign key columns are NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either.
|
||||
> **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either.
|
||||
|
||||
Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from one table to another.
|
||||
Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another.
|
||||
|
||||

|
||||
|
||||
@@ -777,7 +777,7 @@ struct Book: TableRecord {
|
||||
Building Requests from Associations
|
||||
===================================
|
||||
|
||||
**Once you have defined associations, you can define fetch requests that involve several record types.**
|
||||
**Once you have defined associations, you can define fetch request that involve several record types.**
|
||||
|
||||
Fetch requests do not visit the database until you fetch values from them. This will be covered in [Fetching Values from Associations]. But before you can fetch anything, you have to describe what you want to fetch. This is the topic of this chapter.
|
||||
|
||||
@@ -801,7 +801,7 @@ For example, given a `Book.author` **[BelongsTo]** association, you can build a
|
||||
|
||||
```swift
|
||||
struct Book: TableRecord, EncodableRecord {
|
||||
/// The association from a book to its author
|
||||
/// The association from a book to is author
|
||||
static let author = belongsTo(Author.self)
|
||||
|
||||
/// The request for the author of a book
|
||||
@@ -939,14 +939,14 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select(\.country))
|
||||
.annotated(withRequired: Book.author.select(\.country)
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
### `including(optional:)`
|
||||
|
||||
For example, fetch books along with their optional author:
|
||||
For example, fetch books along with their eventual author:
|
||||
|
||||
```swift
|
||||
// SELECT book.*, author.*
|
||||
@@ -960,7 +960,7 @@ This method accepts any association. It has the base record fetched along with o
|
||||
**To fetch results from such a request**, you define a dedicated record type:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with their optional author
|
||||
// Fetch all books along with their eventual author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book // The base record
|
||||
var author: Author? // The optional associated record
|
||||
@@ -976,7 +976,7 @@ let bookInfos = try Book
|
||||
**When you only need a few columns of the associated record**, you can define a partial type with one property per selected column of the associated record:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with the name and country of their optional author
|
||||
// Fetch all books along with the name and country of their eventual author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
struct PartialAuthor: Decodable {
|
||||
var name: String
|
||||
@@ -994,7 +994,7 @@ let bookInfos = try Book
|
||||
But if you'd rather avoid this extra partial type, prefer [`annotated(withOptional:)`]:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with the country of their optional author
|
||||
// Fetch all books along with the country of their eventual author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var country: String?
|
||||
@@ -1133,7 +1133,7 @@ let bookInfos = try Book
|
||||
|
||||
### `annotated(withOptional:)`
|
||||
|
||||
For example, fetch books along with the name and country of their optional author:
|
||||
For example, fetch books along with the name and country of their eventual author:
|
||||
|
||||
```swift
|
||||
// SELECT book.*, author.name, author.country
|
||||
@@ -1147,7 +1147,7 @@ This method accepts any association. The base record is annotated with the selec
|
||||
**To fetch results from such a request**, you define a dedicated record type:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with the name of their optional author
|
||||
// Fetch all books along with the name of their eventual author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book // The base record
|
||||
var name: String? // A column of the optional associated record
|
||||
@@ -1162,7 +1162,7 @@ let bookInfos = try Book
|
||||
If the name of a column of the associated record is also the name of a column of the base record, rename the associated column with the column `forKey(_:)` method, and accordingly rename the property of the decoded record type:
|
||||
|
||||
```swift
|
||||
// Fetch all books along with the name of their optional author
|
||||
// Fetch all books along with the name of their eventual author
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var authorName: String?
|
||||
@@ -1207,16 +1207,16 @@ let request = Book.joining(optional: Book.author)
|
||||
|
||||
This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. The associated record can be missing: it is "optional".
|
||||
|
||||
This method has no observable effect unless the associated record is used in one way or another. We'll see examples later in this documentation.
|
||||
This method has no observable effect unless the associated record is used in a way or another. We'll see examples later in this documentation.
|
||||
|
||||
|
||||
### Choosing a Joining Method Given the Shape of the Decoded Type
|
||||
|
||||
In the description of the [joining methods] above, we have seen that you need to define dedicated record types in order to prefetch associated records. Each joining method needs a dedicated record type that has a specific shape.
|
||||
|
||||
In this chapter, we take the reverse perspective. We list various shapes of decoded record types. When you find the type you want, you'll know the joining method you need.
|
||||
In this chapter, we take the reversed perspective. We list various shapes of decoded record types. When you find the type you want, you'll know the joining method you need.
|
||||
|
||||
> **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level APIs described in [Decoding a Joined Request with FetchableRecord].
|
||||
> **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level apis described in [Decoding a Joined Request with FetchableRecord].
|
||||
|
||||
- [`including(required:)`]
|
||||
|
||||
@@ -1270,7 +1270,7 @@ In this chapter, we take the reverse perspective. We list various shapes of deco
|
||||
```swift
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book // The base record
|
||||
var author: Author? // The optional associated record
|
||||
var author: Author? // The eventual associated record
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
@@ -1286,7 +1286,7 @@ In this chapter, we take the reverse perspective. We list various shapes of deco
|
||||
var country: String
|
||||
}
|
||||
var book: Book // The base record
|
||||
var author: PartialAuthor? // The optional partial associated record
|
||||
var author: PartialAuthor? // The eventual partial associated record
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
@@ -1300,8 +1300,8 @@ In this chapter, we take the reverse perspective. We list various shapes of deco
|
||||
```swift
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
var book: Book // The base record
|
||||
var authorName: String? // A column of the optional associated record
|
||||
var country: String? // A column of the optional associated record
|
||||
var authorName: String? // A column of the eventual associated record
|
||||
var country: String? // A column of the eventual associated record
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
@@ -1381,9 +1381,9 @@ struct BookInfo: FetchableRecord, Decodable {
|
||||
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
The request above fetches all books, along with their author and optional translator.
|
||||
The request above fetches all books, along with their author and eventual translator.
|
||||
|
||||
You can chain associations in order to jump from one record to another:
|
||||
You can chain associations in order to jump from a record to another:
|
||||
|
||||
```swift
|
||||
// SELECT book.*, person.*, country.*
|
||||
@@ -1441,7 +1441,7 @@ struct BookInfo: FetchableRecord, Decodable {
|
||||
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
> **Warning**: you cannot currently chain a required association behind an optional association:
|
||||
> **Warning**: you can not currently chain a required association behind an optional association:
|
||||
>
|
||||
> ```swift
|
||||
> // Not implemented
|
||||
@@ -1496,7 +1496,7 @@ let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
**There are more filtering options:**
|
||||
|
||||
- Filtering on conditions that involve several tables.
|
||||
- Filtering in the WHERE clause instead of the ON clause (can be useful when you are skilled enough in SQL to tell the difference).
|
||||
- Filtering in the WHERE clause instead of the ON clause (can be useful when you are skilled enough in SQL to make the difference).
|
||||
|
||||
Those extra filtering options require **[Table Aliases]**, introduced below.
|
||||
|
||||
@@ -1735,7 +1735,7 @@ Associations support more refinements:
|
||||
|
||||
- [Common Table Expressions]
|
||||
|
||||
Associations can use their own CTEs:
|
||||
Association can use their own CTEs:
|
||||
|
||||
```swift
|
||||
struct AuthorInfo: FetchableRecord, Decodable {
|
||||
@@ -1762,7 +1762,7 @@ Associations support more refinements:
|
||||
|
||||
In all examples we have seen so far, all associated records are joined, included, filtered, and sorted independently. We could not filter them on conditions that involve several records, for example.
|
||||
|
||||
Let's say we look for posthumous books, published after their author has died. We need to compare a book publication date with an author's possible death date.
|
||||
Let's say we look for posthumous books, published after their author has died. We need to compare a book publication date with an author eventual death date.
|
||||
|
||||
Let's first see a wrong way to do it:
|
||||
|
||||
@@ -1779,7 +1779,7 @@ let request = Book
|
||||
|
||||
When executed, we'll get a DatabaseError of code 1, "no such column: book.deathDate".
|
||||
|
||||
That is because the "deathDate" column has been used for filtering books, whereas it is defined on the person database table.
|
||||
That is because the "deathDate" column has been used for filtering books, when it is defined on the person database table.
|
||||
|
||||
To fix this error, we need a **table alias**:
|
||||
|
||||
@@ -1811,7 +1811,7 @@ let request = Book
|
||||
.filter { $0.publishDate >= authorAlias[Author.Columns.deathDate] }
|
||||
```
|
||||
|
||||
Note that Swift 6.1 is required for the short syntax `alias.column`. From now on, we will only give examples in Swift 6.1.
|
||||
Note that Swift 6.1 is required for the short syntac `alias.column`. From now on, we will only give examples in Swift 6.1.
|
||||
|
||||
**Table aliases** can also improve control over the ordering of request results. In the example below, we override the [default ordering](#sorting-associations) of associated records by sorting on author names first:
|
||||
|
||||
@@ -1844,7 +1844,7 @@ let request = Book.aliased(bookAlias)
|
||||
> **Note**: avoid reusing table aliases between several tables or requests, because you will get a fatal error:
|
||||
>
|
||||
> ```swift
|
||||
> // Fatal error: A TableAlias must not be used to refer to multiple tables
|
||||
> // Fatal error: A TableAlias most not be used to refer to multiple tables
|
||||
> let alias = TableAlias()
|
||||
> let books = Book.aliased(alias)...
|
||||
> let people = Person.aliased(alias)...
|
||||
@@ -1931,7 +1931,7 @@ extension DerivableRequest<Book> {
|
||||
joining(required: Book.author.filter(country: country))
|
||||
}
|
||||
|
||||
/// Order books by author name and then book year
|
||||
/// Order books by author name and then book title
|
||||
func orderedByAuthorNameAndYear() -> Self {
|
||||
let authorAlias = TableAlias<Author>()
|
||||
return self
|
||||
@@ -1990,7 +1990,7 @@ Each association included in the request can feed a property of the decoded reco
|
||||
let employeeInfos: [EmployeeInfo] = try EmployeeInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
- `including(required:)` feeds a non-optional property:
|
||||
- `including(required:)` feeds an non-optional property:
|
||||
|
||||
```swift
|
||||
let request = Book.including(required: Book.author)
|
||||
@@ -2024,7 +2024,7 @@ Each association included in the request can feed a property of the decoded reco
|
||||
|
||||
## The Structure of a Joined Request
|
||||
|
||||
**A joined request defines a tree of associated records identified by "association keys".**
|
||||
**Joined request defines a tree of associated records identified by "association keys".**
|
||||
|
||||
Below, author and cover image are both associated to book, and country is associated to author:
|
||||
|
||||
@@ -2052,7 +2052,7 @@ struct BookInfo: FetchableRecord, Decodable {
|
||||
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
By default, **association keys** are the names of the database tables of associated records. Keys are automatically [singularized or pluralized](#convention-for-database-table-names), depending on the cardinality of the included association:
|
||||
By default, **association keys** are the names of the database tables of associated records. Keys are automatically [singularized or pluralized](#convention-for-database-table-names), depending of the cardinality of the included association:
|
||||
|
||||
```swift
|
||||
extension Author {
|
||||
@@ -2108,7 +2108,7 @@ let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
|
||||
We see that a hierarchical tree has been flattened in the `BookInfo` record.
|
||||
|
||||
But sometimes your decoded records will better reflect the hierarchical structure of the request:
|
||||
But sometimes your decoded records will have better reflect the hierarchical structure of the request:
|
||||
|
||||
|
||||
### Decoding a Hierarchical Decodable Record
|
||||
@@ -2124,9 +2124,9 @@ let request = Book
|
||||
.including(optional: Person.country))
|
||||
```
|
||||
|
||||
This requests all books, with their cover images, and their authors and translators. Those people are themselves decorated with their respective nationalities.
|
||||
This requests for all books, with their cover images, and their authors and translators. Those people are themselves decorated with their respective nationalities.
|
||||
|
||||
We plan to decode this request into the following nested record:
|
||||
We plan to decode this request into is the following nested record:
|
||||
|
||||
```swift
|
||||
struct BookInfo: FetchableRecord, Decodable {
|
||||
@@ -2143,7 +2143,7 @@ struct BookInfo: FetchableRecord, Decodable {
|
||||
|
||||
This request needs a little preparation: we need **association keys** that match the **coding keys** for the authorInfo and translatorInfo properties.
|
||||
|
||||
And who is best able to know those coding keys? BookInfo itself, thanks to its `CodingKeys` enum that was automatically generated by the Swift compiler. We thus define the `BookInfo.all()` method that builds our request:
|
||||
And who is the most able to know those coding keys? BookInfo itself, thanks to its `CodingKeys` enum that was automatically generated by the Swift compiler. We thus define the `BookInfo.all()` method that builds our request:
|
||||
|
||||
```swift
|
||||
extension BookInfo {
|
||||
@@ -2168,9 +2168,9 @@ let bookInfos = try BookInfo.all().fetchAll(db, request) // [BookInfo]
|
||||
|
||||
## Decoding a Joined Request with FetchableRecord
|
||||
|
||||
While [Decodable](#decoding-a-joined-request-with-a-decodable-record) records provide convenient decoding of joined rows, you may want a little more control over row decoding.
|
||||
When [Decodable](#decoding-a-joined-request-with-a-decodable-record) records provides convenient decoding of joined rows, you may want a little more control over row decoding.
|
||||
|
||||
The `init(row:)` initializer of the [FetchableRecord] protocol is what you look for:
|
||||
The `init(row:)` initializer of the [FetchableRecord] protocol is what you look after:
|
||||
|
||||
```swift
|
||||
let request = Book
|
||||
@@ -2209,7 +2209,7 @@ let country = try row.decodeIfPresent(Country.self, forKey: "country")
|
||||
|
||||
You can also perform custom navigation in the tree by using *row scopes*. See [Row Adapters] for more information.
|
||||
|
||||
When you use the `including(all:)` method, you can decode an Array or a Set of records:
|
||||
When you use the `include(all:)` method, you can decode an Array or a Set of records:
|
||||
|
||||
```swift
|
||||
let request = Author.including(all: Author.books)
|
||||
@@ -2230,7 +2230,7 @@ let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
|
||||
## Debugging Request Decoding
|
||||
|
||||
When you have difficulties building a Decodable record that successfully decodes a joined request, we advise you to temporarily decode raw database rows, and inspect them.
|
||||
When you have difficulties building a Decodable record that successfully decodes a joined request, we advise to temporarily decode raw database rows, and inspect them.
|
||||
|
||||
```swift
|
||||
let request = Book
|
||||
@@ -2250,9 +2250,9 @@ print(rows[0].debugDescription)
|
||||
// + prizes: 3 rows
|
||||
```
|
||||
|
||||
In the row debugging description, watch for:
|
||||
Watch in the row debugging description:
|
||||
|
||||
- the **association keys**: "author", "country", "coverImage" and "prizes" in our example
|
||||
- the **association keys**: "person", "country", "coverImage" and "prizes" in our example
|
||||
- associated rows that contain only null values ("coverImage", above).
|
||||
|
||||
The associated rows that contain only null values are easy to deal with: null rows loaded from optional associated records should be decoded into Swift optionals:
|
||||
@@ -2308,7 +2308,7 @@ let request = author.books.select { max($0.year) }
|
||||
let maxBookYear = try Int.fetchOne(db, request) // Int?
|
||||
```
|
||||
|
||||
When you need to compute aggregates **from several records**, in a single shot, you'll use an **association aggregate**. Those are the topic of this chapter.
|
||||
When you need to compute aggregates **from several record**, in a single shot, you'll use an **association aggregate**. Those are the topic of this chapter.
|
||||
|
||||
For example, you'll use the `isEmpty` aggregate when you want, say, to fetch all authors who wrote no book at all, or some books:
|
||||
|
||||
@@ -2354,7 +2354,7 @@ for info in authorInfos {
|
||||
|
||||
### Annotating a Request with Aggregates
|
||||
|
||||
The `annotated(with:)` method appends aggregated values to the selected columns of a request. You can append as many aggregate values as needed, from one or several associations.
|
||||
The `annotated(with:)` method appends aggregated values to the selected columns of a request. You can append as many aggregates values as needed, from one or several associations.
|
||||
|
||||
In order to access those values, you fetch records that have matching properties.
|
||||
|
||||
@@ -2392,8 +2392,8 @@ The default name is built from the aggregating method, the **[association key](#
|
||||
|
||||
| Method | Association Key | Aggregated Column | Aggregate name |
|
||||
| ------ | --------------- | ----------------- | -------------- |
|
||||
| `Author.books.isEmpty` | `books` | - | `hasNoBook` |
|
||||
| `Author.books.count` | `books` | - | `bookCount` |
|
||||
| `Author.books.isEmpty`. | `books` | - | `hasNoBook` |
|
||||
| `Author.books.count`. | `books` | - | `bookCount` |
|
||||
| `Author.books.min(\.year)` | `books` | `year` | `minBookYear` |
|
||||
| `Author.books.max(\.year)` | `books` | `year` | `maxBookYear` |
|
||||
| `Author.books.average(\.price)` | `books` | `price` | `averageBookPrice` |
|
||||
@@ -2440,7 +2440,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var numberOfBooks: Int
|
||||
|
||||
static func all() -> QueryInterfaceRequest<AuthorInfo> {
|
||||
let numberOfBooks = Author.books.count.forKey(CodingKeys.numberOfBooks) // <--
|
||||
let numberOfBooks = Author.books.count.forKey(CodingKey.numberOfBooks) // <--
|
||||
return Author
|
||||
.annotated(with: numberOfBooks)
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
@@ -2653,7 +2653,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let workCount = Author.books.count + Author.paintings.count
|
||||
let workCount = Author.books.count + Author.paintings.count)
|
||||
let request = Author.annotated(with: workCount.forKey("workCount"))
|
||||
```
|
||||
|
||||
@@ -2697,7 +2697,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
|
||||
When you compute multiple aggregates, make sure they use as many distinct **[association keys](#the-structure-of-a-joined-request)** as there are distinct populations of associated records.
|
||||
|
||||
In the example below, we compute two aggregates from the same association `Author.books`. Both aggregates are computed on the same population of associated records, and so we want them to share the same association key:
|
||||
In the example below, we use compute two aggregates from the same association `Author.books`. Both aggregates are computed on the same population of associated records, and so we want them to share the same association key:
|
||||
|
||||
- Authors with the publishing year of their first and last book:
|
||||
|
||||
@@ -2707,7 +2707,7 @@ In the example below, we compute two aggregates from the same association `Autho
|
||||
```sql
|
||||
SELECT author.*,
|
||||
MIN(book.year) AS minBookYear,
|
||||
MAX(book.year) AS maxBookYear
|
||||
MAX(book.year) AS maxBookYea
|
||||
FROM author
|
||||
LEFT JOIN book ON book.authorId = author.id
|
||||
GROUP BY author.id
|
||||
@@ -2732,7 +2732,7 @@ In the example below, we compute two aggregates from the same association `Autho
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
In this other example, the `Author.books` and `Author.paintings` have the distinct `books` and `paintings` keys. They don't interfere, and provide the expected results:
|
||||
In this other example, the `Author.books` and `Author.paintings` have the distinct `book` and `painting` keys. They don't interfere, and provide the expected results:
|
||||
|
||||
- Authors with their number of books and paintings:
|
||||
|
||||
@@ -2843,7 +2843,7 @@ But in the following example, we use the same association `Author.books` twice,
|
||||
|
||||
## DerivableRequest Protocol
|
||||
|
||||
The `DerivableRequest` protocol is adopted by both [query interface requests] such as `Author.all()` and associations such as `Book.author`. It is intended for you to use as a customization point when you want to extend the built-in GRDB APIs.
|
||||
The `DerivableRequest` protocol is adopted by both [query interface requests] such as `Author.all()` and associations such as `Book.author`. It is intended for you to use as a customization point when you want to extend the built-in GRDB apis.
|
||||
|
||||
For example, we may want to define `orderedByName()` and `filter(country:)` request methods that make our requests easier to read:
|
||||
|
||||
@@ -2905,7 +2905,7 @@ See [Recommended Practices for Designing Record Types] for more information.
|
||||
.filter { $0.publishDate >= authorAlias.deathDate })
|
||||
```
|
||||
|
||||
- **You can't use the `including(all:)` method with a [HasMany] and a [HasManyThrough] association that share the same base association in the same request**:
|
||||
- **You can't use the `including(all:)` method with a [HasMany] and a [HasManyThrough] associations that share the same base association in the same request**:
|
||||
|
||||
```swift
|
||||
// NOT IMPLEMENTED
|
||||
@@ -2927,7 +2927,7 @@ See [Recommended Practices for Designing Record Types] for more information.
|
||||
|
||||
---
|
||||
|
||||
This documentation owes a lot to the [Active Record Associations](http://guides.rubyonrails.org/association_basics.html) guide, which is an immensely well-written introduction to database relations. Many thanks to the Rails team and contributors.
|
||||
This documentation owns a lot to the [Active Record Associations](http://guides.rubyonrails.org/association_basics.html) guide, which is an immensely well-written introduction to database relations. Many thanks to the Rails team and contributors.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -113,7 +113,7 @@ let cancellable = publisher.sink(
|
||||
|
||||
# Asynchronous Database Access
|
||||
|
||||
GRDB provides publishers that perform asynchronous database accesses:
|
||||
GRDB provide publishers that perform asynchronous database accesses:
|
||||
|
||||
- [`readPublisher(receiveOn:value:)`]
|
||||
- [`writePublisher(receiveOn:updates:)`]
|
||||
@@ -123,7 +123,7 @@ GRDB provides publishers that perform asynchronous database accesses:
|
||||
|
||||
#### `DatabaseReader.readPublisher(receiveOn:value:)`
|
||||
|
||||
This method returns a publisher that completes after database values have been asynchronously fetched.
|
||||
This methods returns a publisher that completes after database values have been asynchronously fetched.
|
||||
|
||||
```swift
|
||||
// DatabasePublishers.Read<[Player]>
|
||||
@@ -134,7 +134,7 @@ let players = dbQueue.readPublisher { db in
|
||||
|
||||
Any attempt at modifying the database completes subscriptions with an error.
|
||||
|
||||
When you use a [database queue] or a [database snapshot], the read has to wait for any concurrent database access performed by this queue or snapshot to complete.
|
||||
When you use a [database queue] or a [database snapshot], the read has to wait for any eventual concurrent database access performed by this queue or snapshot to complete.
|
||||
|
||||
When you use a [database pool], reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured].
|
||||
|
||||
@@ -174,8 +174,9 @@ This method returns a publisher that completes after database updates have been
|
||||
```swift
|
||||
// DatabasePublishers.Write<Int>
|
||||
let newPlayerCount = dbQueue.writePublisher(
|
||||
updates: { db in try Player(...).insert(db) },
|
||||
updates: { db in try Player(...).insert(db) }
|
||||
thenRead: { db, _ in try Player.fetchCount(db) })
|
||||
}
|
||||
```
|
||||
|
||||
It publishes exactly the same values as [`writePublisher(receiveOn:updates:)`]:
|
||||
@@ -188,7 +189,7 @@ let newPlayerCount = dbQueue.writePublisher { db -> Int in
|
||||
}
|
||||
```
|
||||
|
||||
The difference is that the last fetches are performed in the `thenRead` function. This function accepts two arguments: a readonly database connection, and the result of the `updates` function. This allows you to pass information from one function to the other (it is ignored in the sample code above).
|
||||
The difference is that the last fetches are performed in the `thenRead` function. This function accepts two arguments: a readonly database connection, and the result of the `updates` function. This allows you to pass information from a function to the other (it is ignored in the sample code above).
|
||||
|
||||
When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention.
|
||||
|
||||
@@ -223,11 +224,11 @@ let publisher = observation.publisher(in: dbQueue)
|
||||
|
||||
This publisher has the same behavior as ValueObservation:
|
||||
|
||||
- It notifies an initial value before subsequent changes.
|
||||
- It notifies an initial value before the eventual changes.
|
||||
- It may coalesce subsequent changes into a single notification.
|
||||
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
|
||||
- It only completes when it is cancelled.
|
||||
- By default, it notifies the initial value, as well as subsequent changes and errors, on the main thread, asynchronously.
|
||||
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
|
||||
|
||||
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservationscheduler).
|
||||
|
||||
@@ -310,7 +311,7 @@ When you compose database publishers together with Combine operators such as `co
|
||||
|
||||
This is because each database publisher is isolated from others: each one of them sees its own state of the database. Whenever some database change is interleaved between publisher operations, publishers will process or publish values that may not fit well together.
|
||||
|
||||
In other words, whenever you need to perform some database access or observation that depends on some database invariant, make sure you define one and only one database publisher instead of combining several publishers. This is how you will prevent concurrent database writes from messing with your app, and introducing bugs.
|
||||
In other words, whenever you need to perform some database access or observation that depends on some database invariant, make sure you define one and only one database publisher instead of combining several publishers. This is how you will prevent eventual concurrent database writes from messing with your app, and introduce bugs.
|
||||
|
||||
To this end, remember that *all database publishers can perform several requests*.
|
||||
|
||||
|
||||
@@ -126,13 +126,13 @@ let request = Player
|
||||
.filter { $0.name == playerNameCTE.all() }
|
||||
```
|
||||
|
||||
> **Note**: the `with(_:)` method can be called as many times as there are common table expressions in your request.
|
||||
> **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
|
||||
>
|
||||
> **Note**: the `with(_:)` method can be called at any time, like all request methods: `Player.with(...).filter(...).with(...)`.
|
||||
> **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`.
|
||||
>
|
||||
> **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it.
|
||||
>
|
||||
> **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be confused with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
|
||||
> **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
|
||||
>
|
||||
> ```swift
|
||||
> cte.all().select(...).filter(...).group(...).order(...)
|
||||
@@ -270,7 +270,7 @@ LeftRecord
|
||||
|
||||
### CTE Association Example: a Chat App
|
||||
|
||||
As an example, let's build the classic main screen of a chat application: a list of all latest messages from all conversations.
|
||||
As an example, let's build the classical main screen of a chat application: a list of all latest messages from all conversations.
|
||||
|
||||
The database schema of the chat app contains a `chat` and a `message` table. The application defines the following records:
|
||||
|
||||
@@ -368,7 +368,7 @@ And we can fetch the data that feeds our application screen:
|
||||
|
||||
```swift
|
||||
|
||||
let chatInfos: [ChatInfo] = try dbQueue.read { db in
|
||||
let chatInfos: [ChatInfos] = try dbQueue.read { db in
|
||||
try request.fetchAll(db)
|
||||
}
|
||||
```
|
||||
@@ -395,8 +395,8 @@ let chatInfos: [ChatInfo] = try dbQueue.read { db in
|
||||
> // JOIN far ON ...
|
||||
> let request = BaseRecord
|
||||
> .with(cte1).with(cte2)
|
||||
> .joining(required: assoc1 // OK
|
||||
> .joining(required: assoc2 // OK
|
||||
> .joining(required: assoc1. // OK
|
||||
> .joining(required: assoc2. // OK
|
||||
> .joining(required: assoc3))) // OK
|
||||
>
|
||||
> // Compiler error
|
||||
|
||||
@@ -3,13 +3,13 @@ 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).
|
||||
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](../../../#full-text-search), 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).
|
||||
> Warning: The technique described here is not compatible with the Swift Package Manager (SPM). It will create [build issues](https://github.com/groue/GRDB.swift/issues/1709) with SPM companion librairies such as [GRDBQuery](https://github.com/groue/GRDBQuery) or [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting).
|
||||
|
||||
**To install GRDB with a custom SQLite build:**
|
||||
|
||||
@@ -109,7 +109,7 @@ GRDB builds SQLite with [groue/SQLiteLib](https://github.com/groue/SQLiteLib), w
|
||||
echo "Finished syncing"
|
||||
```
|
||||
|
||||
Modify the top of the `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
|
||||
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
|
||||
|
||||
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
|
||||
|
||||
|
||||
@@ -158,7 +158,7 @@
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 2600;
|
||||
LastUpgradeCheck = 1600;
|
||||
TargetAttributes = {
|
||||
56CFC6432C9F1DC9000B5023 = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
@@ -287,13 +287,12 @@
|
||||
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;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
@@ -346,12 +345,11 @@
|
||||
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;
|
||||
SDKROOT = iphoneos;
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
@@ -381,9 +379,8 @@
|
||||
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;
|
||||
SWIFT_VERSION = 6.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -411,9 +408,8 @@
|
||||
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;
|
||||
SWIFT_VERSION = 6.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Release;
|
||||
@@ -428,9 +424,8 @@
|
||||
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;
|
||||
SWIFT_VERSION = 6.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
|
||||
};
|
||||
@@ -446,9 +441,8 @@
|
||||
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;
|
||||
SWIFT_VERSION = 6.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
|
||||
};
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2720"
|
||||
LastUpgradeVersion = "1600"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -18,7 +18,7 @@ struct AppDatabase: Sendable {
|
||||
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections>
|
||||
private let dbWriter: any DatabaseWriter
|
||||
|
||||
/// Creates an `AppDatabase`, and makes sure the database schema
|
||||
/// Creates a `AppDatabase`, and makes sure the database schema
|
||||
/// is ready.
|
||||
///
|
||||
/// - important: Create the `DatabaseWriter` with a configuration
|
||||
@@ -62,7 +62,7 @@ struct AppDatabase: Sendable {
|
||||
// MARK: - Database Configuration
|
||||
|
||||
extension AppDatabase {
|
||||
// Uncomment to enable SQL logging
|
||||
// Uncomment for enabling SQL logging
|
||||
// private static let sqlLogger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
|
||||
|
||||
/// Returns a database configuration suited for `AppDatabase`.
|
||||
@@ -76,7 +76,7 @@ extension AppDatabase {
|
||||
// db.add(function: ...)
|
||||
// }
|
||||
//
|
||||
// Uncomment to enable SQL logging if the `SQL_TRACE` environment variable is set.
|
||||
// Uncomment for enabling SQL logging if the `SQL_TRACE` environment variable is set.
|
||||
// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/trace(options:_:)>
|
||||
// if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
|
||||
// config.prepareDatabase { db in
|
||||
@@ -114,25 +114,25 @@ extension AppDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes the specified players
|
||||
/// Delete the specified players
|
||||
func deletePlayers(ids: [Int64]) throws {
|
||||
try dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db, keys: ids)
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes all players
|
||||
/// Delete all players
|
||||
func deleteAllPlayers() throws {
|
||||
try dbWriter.write { db in
|
||||
_ = try Player.deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Refreshes all players (by performing some random changes, for demo purposes).
|
||||
/// Refresh all players (by performing some random changes, for demo purpose).
|
||||
func refreshPlayers() async throws {
|
||||
try await dbWriter.write { db in
|
||||
if try Player.all().isEmpty(db) {
|
||||
// When the database is empty, insert new random players
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
} else {
|
||||
// Insert a player
|
||||
@@ -141,8 +141,8 @@ extension AppDatabase {
|
||||
}
|
||||
|
||||
// Delete a random player
|
||||
if Bool.random(), let player = try Player.order(sql: "RANDOM()").fetchOne(db) {
|
||||
try player.delete(db)
|
||||
if Bool.random() {
|
||||
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
|
||||
}
|
||||
|
||||
// Update some players
|
||||
@@ -155,7 +155,7 @@ extension AppDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates random players if the database is empty.
|
||||
/// Create random players if the database is empty.
|
||||
func createRandomPlayersIfEmpty() throws {
|
||||
try dbWriter.write { db in
|
||||
if try Player.all().isEmpty(db) {
|
||||
@@ -175,11 +175,11 @@ extension AppDatabase {
|
||||
// MARK: - Database Access: Reads
|
||||
|
||||
// This demo app does not provide any specific reading method, and instead
|
||||
// gives unrestricted read-only access to the rest of the application.
|
||||
// gives an unrestricted read-only access to the rest of the application.
|
||||
// In your app, you are free to choose another path, and define focused
|
||||
// reading methods.
|
||||
extension AppDatabase {
|
||||
/// Provides read-only access to the database.
|
||||
/// Provides a read-only access to the database.
|
||||
var reader: any GRDB.DatabaseReader {
|
||||
dbWriter
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ struct Player: Equatable {
|
||||
/// The player id.
|
||||
///
|
||||
/// Int64 is the recommended type for auto-incremented database ids.
|
||||
/// Use nil for players that are not inserted in the database yet.
|
||||
/// Use nil for players that are not inserted yet in the database.
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
@@ -26,7 +26,7 @@ extension AppDatabase {
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
|
||||
// Populate the database if it is empty, for a better demo.
|
||||
// Populate the database if it is empty, for better demo purpose.
|
||||
try appDatabase.createRandomPlayersIfEmpty()
|
||||
|
||||
return appDatabase
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
"zero" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "No Players"
|
||||
"value" : "No Player"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@
|
||||
"zero" : {
|
||||
"stringUnit" : {
|
||||
"state" : "translated",
|
||||
"value" : "0 points"
|
||||
"value" : "0 point"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
+8
-5
@@ -1,6 +1,7 @@
|
||||
import SwiftUI
|
||||
|
||||
struct PlayerEditView: View {
|
||||
struct PlayerEditionView: 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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +36,6 @@ struct PlayerEditView: View {
|
||||
|
||||
#Preview {
|
||||
NavigationStack {
|
||||
PlayerEditView(player: .makeRandom())
|
||||
PlayerEditionView(player: .makeRandom())
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,7 @@ import GRDB
|
||||
|
||||
// Start observing the database.
|
||||
// Previous observation, if any, is cancelled.
|
||||
cancellable = observation.start(in: appDatabase.reader, scheduling: .immediate) { error in
|
||||
cancellable = observation.start(in: appDatabase.reader) { error in
|
||||
// Handle error
|
||||
} onChange: { [unowned self] players in
|
||||
self.players = players
|
||||
@@ -65,7 +65,7 @@ import GRDB
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
/// Delete players at the specified indexes in `self.players`.
|
||||
/// Delete players at specified indexes in `self.players`.
|
||||
func deletePlayers(at offsets: IndexSet) throws {
|
||||
let playerIds = offsets.compactMap { players[$0].id }
|
||||
try appDatabase.deletePlayers(ids: playerIds)
|
||||
@@ -76,12 +76,12 @@ import GRDB
|
||||
try appDatabase.deleteAllPlayers()
|
||||
}
|
||||
|
||||
/// Refresh all players (by performing some random changes, for demo purposes).
|
||||
/// Refresh all players (by performing some random changes, for demo purpose).
|
||||
func refreshPlayers() async throws {
|
||||
try await appDatabase.refreshPlayers()
|
||||
}
|
||||
|
||||
/// Perform 50 refreshes in parallel, for demo purposes.
|
||||
/// Perform 50 refreshes in parallel, for demo purpose.
|
||||
func refreshPlayersManyTimes() async throws {
|
||||
try await withThrowingTaskGroup(of: Void.self) { group in
|
||||
for _ in 0..<50 {
|
||||
|
||||
@@ -8,7 +8,7 @@ struct PlayerListView: View {
|
||||
List {
|
||||
ForEach(model.players, id: \.id) { player in
|
||||
NavigationLink {
|
||||
PlayerEditView(player: player)
|
||||
PlayerEditionView(player: player)
|
||||
} label: {
|
||||
PlayerRow(player: player)
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ private struct ContentView: View {
|
||||
.buttonStyle(.borderedProminent)
|
||||
}
|
||||
// Hide the title, but set a string anyway in order to avoid
|
||||
// an odd relayout when the player list becomes empty during
|
||||
// an odd relayout when player list becomes empty during
|
||||
// the tornado.
|
||||
.navigationTitle("")
|
||||
}
|
||||
|
||||
@@ -5,11 +5,11 @@ GRDBDemo Application
|
||||
|
||||
**GRDBDemo demonstrates how GRDB can fuel a SwiftUI application.**
|
||||
|
||||
> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as inspiration.
|
||||
> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
|
||||
|
||||
The topics covered in this demo are:
|
||||
|
||||
- How to set up a database in an iOS app.
|
||||
- How to setup a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation).
|
||||
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
|
||||
@@ -23,21 +23,21 @@ The topics covered in this demo are:
|
||||
|
||||
- [AppDatabase.swift](GRDBDemo/Database/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator) in order to set up the database schema, and provides methods that read and write.
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and provides methods that read and write.
|
||||
|
||||
`AppDatabase` is [tested](GRDBDemoTests/AppDatabaseTests.swift).
|
||||
|
||||
- [Persistence.swift](GRDBDemo/Database/Persistence.swift)
|
||||
|
||||
This file instantiates `AppDatabase` instances for the various needs of the project: one database on disk for the application, and in-memory databases for SwiftUI previews.
|
||||
This file instantiates various `AppDatabase` for the various projects needs: one database on disk for the application, and in-memory databases for SwiftUI previews.
|
||||
|
||||
- [Player.swift](GRDBDemo/Database/Models/Player.swift)
|
||||
|
||||
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all the advantages of [Codable Records](../../../README.md#codable-records).
|
||||
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records).
|
||||
|
||||
- [PlayerListModel.swift](GRDBDemo/Views/PlayerListModel.swift)
|
||||
|
||||
`PlayerListModel` is an `@Observable` object that observes the database, always displays fresh values on screen, and performs actions.
|
||||
`PlayerListModel` is an `@Observable` object that observes the database, displays always fresh values on screen, and performs actions.
|
||||
|
||||
`PlayerListModel` is [tested](GRDBDemoTests/PlayerListModelTests.swift).
|
||||
|
||||
|
||||
@@ -29,13 +29,13 @@ GRDB lets you define your own custom FTS5 tokenizers, and extend SQLite built-in
|
||||
|
||||
**A Tokenizer splits text into tokens**. For example, a tokenizer can split "SQLite is a database engine" into the five tokens "SQLite", "is", "a", "database", and "engine".
|
||||
|
||||
FTS5 uses tokenizers to tokenize both indexed documents and search patterns. **A match between a document and a search pattern happens when both produce *identical* tokens.**
|
||||
FTS5 use tokenizers to tokenize both indexed documents and search patterns. **A match between a document and a search pattern happens when both produce *identical* tokens.**
|
||||
|
||||
All SQLite [built-in tokenizers](https://www.sqlite.org/fts5.html#tokenizers) tokenize both "SQLite" and "sqlite" into the common lowercase token "sqlite". This is why they are case-insensitive. Generally speaking, different tokenizers achieve different matching by applying different transformations to the input text.
|
||||
|
||||
- The [ascii](https://www.sqlite.org/fts5.html#ascii_tokenizer) tokenizer turns all ASCII characters to lowercase. "SQLite is a database engine" gives "sqlite", "is", "a", "database", and "engine". The query "SQLITE DATABASE" will match, because its tokens "sqlite" and "database" are found in the document.
|
||||
|
||||
- The [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer removes diacritics from latin characters. Unlike the ascii tokenizer, it will match "Jérôme" with "Jerome", as both produce the same "jerome" token.
|
||||
- The [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer remove diacritics from latin characters. Unlike the ascii tokenizer, it will match "Jérôme" with "Jerome", as both produce the same "jerome" token.
|
||||
|
||||
- The [porter](https://www.sqlite.org/fts5.html#porter_tokenizer) tokenizer turns English words into their root: "database engine" gives the "databas" and "engin" tokens. The query "database engines" will match, because it produces the same tokens.
|
||||
|
||||
@@ -43,7 +43,7 @@ However, built-in tokenizers don't match "first" with "1st", because they produc
|
||||
|
||||
Nor do they match "Grossmann" with "Großmann", because they produce the different "grossmann" and "großmann" tokens.
|
||||
|
||||
Custom tokenizers help deal with these situations. We'll see how to match "Grossmann" and "Großmann" by tokenizing them into "grossmann" (see [latin script](#example-latin-script)). We'll also see how to have "first" and "1st" emit *synonym tokens*, so that they can match too (see [synonyms](#example-synonyms)).
|
||||
Custom tokenizers help dealing with these situations. We'll see how to match "Grossmann" and "Großmann" by tokenizing them into "grossmann" (see [latin script](#example-latin-script)). We'll also see how to have "first" and "1st" emit *synonym tokens*, so that they can match too (see [synonyms](#example-synonyms)).
|
||||
|
||||
|
||||
## The Tokenizer Protocols
|
||||
@@ -54,7 +54,7 @@ GRDB lets you use and define FTS5 tokenizers through three protocols:
|
||||
|
||||
- [FTS5CustomTokenizer](#fts5customtokenizer): the low-level protocol that lets custom tokenizers use the raw [FTS5 C API](https://www.sqlite.org/fts5.html#custom_tokenizers).
|
||||
|
||||
- [FTS5WrapperTokenizer](#fts5wrappertokenizer): the high-level protocol for custom tokenizers that post-process the tokens produced by another FTS5Tokenizer.
|
||||
- [FTS5WrapperTokenizer](#fts5wrappertokenizer): the high-level protocol for custom tokenizers that post-processes the tokens produced by another FTS5Tokenizer.
|
||||
|
||||
|
||||
## Using a Custom Tokenizer
|
||||
@@ -73,7 +73,7 @@ config.prepareDatabase { db in
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
```
|
||||
|
||||
**Create [full-text tables](FullTextSearch.md#create-fts5-virtual-tables) that use the custom tokenizer:**
|
||||
**Create [full-text tables](../../../#create-fts5-virtual-tables) that use the custom tokenizer:**
|
||||
|
||||
```swift
|
||||
try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
@@ -82,7 +82,7 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
}
|
||||
```
|
||||
|
||||
The full-text table can be fed and queried in [a regular way](FullTextSearch.md):
|
||||
The full-text table can be fed and queried in [a regular way](../../../#full-text-search):
|
||||
|
||||
```swift
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["..."])
|
||||
@@ -161,7 +161,7 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
|
||||
FTS5CustomTokenizer inherits from [FTS5Tokenizer](#fts5tokenizer), and performs tokenization with its `tokenize(context:tokenization:pText:nText:tokenCallback:)` method. This low-level method matches the `xTokenize` C function documented at https://www.sqlite.org/fts5.html#custom_tokenizers.
|
||||
|
||||
This method's arguments are:
|
||||
This method arguments are:
|
||||
|
||||
- `context`: An opaque pointer that is the first argument to the `tokenCallback` function
|
||||
- `tokenization`: The reason why FTS5 is requesting tokenization.
|
||||
@@ -175,14 +175,14 @@ This method's arguments are:
|
||||
- `iStart`: Byte offset of token within input text
|
||||
- `iEnd`: Byte offset of end of token within input text
|
||||
|
||||
Since tokenization is hard, and pointers to byte buffers difficult to deal with, you may enjoy the [FTS5WrapperTokenizer](#fts5wrappertokenizer) protocol.
|
||||
Since tokenization is hard, and pointers to byte buffers uneasy to deal with, you may enjoy the [FTS5WrapperTokenizer](#fts5wrappertokenizer) protocol.
|
||||
|
||||
|
||||
## FTS5WrapperTokenizer
|
||||
|
||||
**FTS5WrapperTokenizer** is the high-level protocol for your custom tokenizers. It provides a default implementation for the low-level `tokenize(context:tokenization:pText:nText:tokenCallback:)` method, so that the adopting type does not have to deal with raw byte buffers of the raw [FTS5 C API](https://www.sqlite.org/fts5.html#custom_tokenizers).
|
||||
|
||||
An FTS5WrapperTokenizer leaves the hard tokenization job to another tokenizer, the "wrapped tokenizer", and post-processes the tokens produced by this wrapped tokenizer.
|
||||
A FTS5WrapperTokenizer lets the hard tokenization job to another tokenizer, the "wrapped tokenizer", and post-processes the tokens produced by this wrapped tokenizer.
|
||||
|
||||
```swift
|
||||
protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
|
||||
@@ -195,7 +195,7 @@ protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
|
||||
}
|
||||
```
|
||||
|
||||
Like all custom tokenizers, wrapper tokenizers must have a name:
|
||||
As all custom tokenizers, wrapper tokenizers must have a name:
|
||||
|
||||
```swift
|
||||
final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
@@ -236,11 +236,11 @@ final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
|
||||
The token argument is a token produced by the wrapped tokenizer, ready to be ignored, modified, or multiplied into several [synonyms](#example-synonyms).
|
||||
|
||||
The tokenization parameter tells the reason why tokens are produced: whether FTS5 is tokenizing a document, or a search pattern. Some tokenizers may produce different tokens depending on this parameter.
|
||||
The tokenization parameter tells the reason why tokens are produced, if FTS5 is tokenizing a document, or a search pattern. Some tokenizers may produce different tokens depending on this parameter.
|
||||
|
||||
Finally, the tokenCallback is a function you call to output a custom token.
|
||||
|
||||
There are two rules to observe when implementing the accept method:
|
||||
There are a two rules to observe when implementing the accept method:
|
||||
|
||||
1. Errors thrown by the tokenCallback function must not be caught (they notify that FTS5 requires the tokenization process to stop immediately).
|
||||
2. The flags parameter should be given unmodified to the tokenCallback function along with the custom token, unless you union it with the `.colocated` flag when the tokenizer produces [synonyms](#example-synonyms).
|
||||
@@ -300,9 +300,9 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
|
||||
|
||||
The topic of synonyms is documented at https://www.sqlite.org/fts5.html#synonym_support, which describes several methods. You should carefully read this documentation, and pick the method you prefer.
|
||||
|
||||
In the example below, we'll pick method (3), and implement a tokenizer that adds multiple synonyms for a single term to the FTS index. Using this method, when tokenizing document text, the tokenizer provides multiple synonyms for each token. So when a document such as "I won first place" is tokenized, entries are added to the FTS index for "i", "won", "first", "1st" and "place".
|
||||
In the example below, we'll pick method (3), and implement a tokenizer that adds multiple synonyms for a single term to the FTS index. Using this method, when tokenizing document text, the tokenizer provides multiple synonyms for each token. So that when a document such as "I won first place" is tokenized, entries are added to the FTS index for "i", "won", "first", "1st" and "place".
|
||||
|
||||
We'll also follow the SQLite advice:
|
||||
We'll also take care of the SQLite advice:
|
||||
|
||||
> When using methods (2) or (3), it is important that the tokenizer only provide synonyms when tokenizing document text or query text, not both. Doing so will not cause any errors, but is inefficient.
|
||||
|
||||
@@ -350,11 +350,11 @@ Languages that use the [latin script](https://en.wikipedia.org/wiki/Latin_script
|
||||
|
||||
Full-text search in such a corpus often needs input tolerance, so that "encyclopaedia" can match "Encyclopædia", "Grossmann", "Großmann", and "Jerome", "Jérôme".
|
||||
|
||||
German has something specific in that both "Mueller" and "Muller" should match "Müller", while "Bauer" should not match "Baur" (only "ü" accepts both "u" and "ue"). A pull request that adds a chapter about German will be welcome.
|
||||
German has something specific in that both "Mueller" and "Muller" should match "Müller", when "Bauer" should not match "Baur" (only "ü" accepts both "u" and "ue"). A pull request that adds a chapter about German will be welcome.
|
||||
|
||||
A custom FTS5 tokenizer lets you provide fuzzy latin matching: after "Grossmann", "Großmann", and "GROSSMANN" have all been turned into "grossmann", they will all match together.
|
||||
|
||||
We'll wrap the built-in [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer (the one that knows how to split text on spaces and punctuation), and transform its tokens into their bare lowercase ascii form.
|
||||
We'll wrap the built-in [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer (the one that knows how to split text on spaces and punctuations), and transform its tokens into their bare lowercase ascii form.
|
||||
|
||||
The tokenizer wrapping is provided by the [FTS5WrapperTokenizer](#fts5wrappertokenizer) protocol. The string transformation is provided by the [String.applyingTransform](https://developer.apple.com/reference/swift/string/1643133-applyingtransform) method:
|
||||
|
||||
|
||||
@@ -78,7 +78,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
|
||||
|
||||
For a full feature list, read the SQLite documentation. Some missing features can be achieved with extra application code.
|
||||
|
||||
- **The speed versus disk space constraints.** Roughly speaking, FTS4 and FTS5 are faster than FTS3, but use more space. Only FTS4 supports content compression.
|
||||
- **The speed versus disk space constraints.** Roughly speaking, FTS4 and FTS5 are faster than FTS3, but use more space. FTS4 only supports content compression.
|
||||
|
||||
- **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables.
|
||||
|
||||
@@ -148,7 +148,7 @@ try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
}
|
||||
```
|
||||
|
||||
The `content` option is involved in "contentless" and "external content" full-text tables. GRDB can help you define full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
The `content` option is involved in "contentless" and "external content" full-text tables. GRDB can help you defining full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
|
||||
|
||||
See [SQLite documentation](https://www.sqlite.org/fts3.html) for more information.
|
||||
@@ -254,7 +254,7 @@ FTS3.tokenize("Gustave Doré", withTokenizer: .unicode61()) // ["gustave", "dore
|
||||
|
||||
**Not all search patterns are valid**: they must follow the [Full-Text Index Queries Grammar](https://www.sqlite.org/fts3.html#full_text_index_queries).
|
||||
|
||||
The FTS3Pattern type helps you validate patterns, and build valid patterns from untrusted strings (such as strings typed by users):
|
||||
The FTS3Pattern type helps you validating patterns, and building valid patterns from untrusted strings (such as strings typed by users):
|
||||
|
||||
```swift
|
||||
struct FTS3Pattern {
|
||||
@@ -301,7 +301,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS3Pattern instances are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -377,7 +377,7 @@ try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
}
|
||||
```
|
||||
|
||||
The `content` and `contentRowID` options are involved in "contentless" and "external content" full-text tables. GRDB can help you define full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
The `content` and `contentRowID` options are involved in "contentless" and "external content" full-text tables. GRDB can help you defining full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
|
||||
|
||||
See [SQLite documentation](https://www.sqlite.org/fts5.html) for more information.
|
||||
|
||||
@@ -493,7 +493,7 @@ See the `FTS5_TOKEN_*` flags in https://www.sqlite.org/fts5.html#custom_tokenize
|
||||
|
||||
**Not all search patterns are valid**: they must follow the [Full-Text Query Syntax](https://www.sqlite.org/fts5.html#full_text_query_syntax).
|
||||
|
||||
The FTS5Pattern type helps you validate patterns, and build valid patterns from untrusted strings (such as strings typed by users):
|
||||
The FTS5Pattern type helps you validating patterns, and building valid patterns from untrusted strings (such as strings typed by users):
|
||||
|
||||
```swift
|
||||
extension Database {
|
||||
@@ -550,7 +550,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
|
||||
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
|
||||
```
|
||||
|
||||
FTS5Pattern instances are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -583,7 +583,7 @@ let documents = try Document.fetchAll(db,
|
||||
let documents = try Document.matching(pattern).order(Column.rank).fetchAll(db)
|
||||
```
|
||||
|
||||
For more information about the ranking algorithm, as well as extra options, read [Sorting by Auxiliary Function Results](https://www.sqlite.org/fts5.html#sorting_by_auxiliary_function_results).
|
||||
For more information about the ranking algorithm, as well as extra options, read [Sorting by Auxiliary Function Results](https://www.sqlite.org/fts5.html#sorting_by_auxiliary_function_results)
|
||||
|
||||
GRDB does not provide any ranking for FTS3 and FTS4. See SQLite's [Search Application Tips](https://www.sqlite.org/fts3.html#appendix_a) if you really need it.
|
||||
|
||||
@@ -592,7 +592,7 @@ GRDB does not provide any ranking for FTS3 and FTS4. See SQLite's [Search Applic
|
||||
|
||||
**An external content table does not store the indexed text.** Instead, it indexes the text stored in another table.
|
||||
|
||||
This is very handy when you want to index a table that cannot be declared as a full-text table (because it contains non-textual values, for example). You just have to define an external content full-text table that refers to the regular table.
|
||||
This is very handy when you want to index a table that can not be declared as a full-text table (because it contains non-textual values, for example). You just have to define an external content full-text table that refers to the regular table.
|
||||
|
||||
The two tables must be kept up-to-date, so that the full-text index matches the content of the regular table. This synchronization happens automatically if you use the `synchronize(withTable:)` method in your full-text table definition:
|
||||
|
||||
@@ -614,7 +614,7 @@ try db.create(virtualTable: "book_ft", using: FTS4()) { t in // or FTS5()
|
||||
}
|
||||
```
|
||||
|
||||
Any content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.
|
||||
The eventual content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.
|
||||
|
||||
For more information, see the SQLite documentation about external content tables: [FTS4](https://www.sqlite.org/fts3.html#_external_content_fts4_tables_), [FTS5](https://sqlite.org/fts5.html#external_content_tables).
|
||||
|
||||
@@ -623,11 +623,11 @@ See also [WWDC Companion](https://github.com/groue/WWDCCompanion), a sample app
|
||||
|
||||
### Deleting Synchronized Full-Text Tables
|
||||
|
||||
Synchronization of full-text tables with their content table happens by means of SQL triggers.
|
||||
Synchronization of full-text tables with their content table happens by the mean of SQL triggers.
|
||||
|
||||
SQLite automatically deletes those triggers when the content (not full-text) table is dropped.
|
||||
|
||||
However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertions, updates, and deletions in the content table, and the creation of a new full-text table.
|
||||
However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertion, updates, and deletions in the content table, and the creation of a new full-text table.
|
||||
|
||||
To drop those triggers, use the `dropFTS4SynchronizationTriggers` or `dropFTS5SynchronizationTriggers` methods:
|
||||
|
||||
@@ -661,7 +661,7 @@ try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
|
||||
|
||||
When you need to perform a full-text search, and the external content table contains all the data you need, you can simply query the full-text table.
|
||||
|
||||
But if you need to load columns from the regular table, and also perform a full-text search, then you will need to query both tables at the same time.
|
||||
But if you need to load columns from the regular table, and in the same time perform a full-text search, then you will need to query both tables at the same time.
|
||||
|
||||
That is because SQLite will throw an error when you try to perform a full-text search on a regular table:
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Migrating From GRDB 4 to GRDB 5
|
||||
===============================
|
||||
|
||||
**This guide aims at helping you upgrade your applications from GRDB 4 to GRDB 5.**
|
||||
**This guide aims at helping you upgrading your applications from GRDB 4 to GRDB 5.**
|
||||
|
||||
- [Preparing the Migration to GRDB 5](#preparing-the-migration-to-grdb-5)
|
||||
- [New requirements](#new-requirements)
|
||||
@@ -63,9 +63,9 @@ let dbQueue = try DatabaseQueue(dbPath, configuration: config)
|
||||
|
||||
## ValueObservation
|
||||
|
||||
[ValueObservation] is the database observation tool that tracks changes in database values. It has changed quite a bit in GRDB 5.
|
||||
[ValueObservation] is the database observation tool that tracks changes in database values. It has quite changed in GRDB 5.
|
||||
|
||||
Those changes make the vanilla GRDB, its [Combine publishers], and [RxGRDB] offer a common API, and a common behavior. This greatly helps choose or switch your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
|
||||
Those changes have the vanilla GRDB, its [Combine publishers], and [RxGRDB] offer a common API, and a common behavior. This greatly helps choosing or switching your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
|
||||
|
||||
In the end, this migration step might require some work. But it's for the benefit of all!
|
||||
|
||||
@@ -111,7 +111,7 @@ let observation = ValueObservation.tracking(someFetchFunction)
|
||||
let observation = ValueObservation.tracking { db in ... }
|
||||
```
|
||||
|
||||
Finally, ValueObservation used to let applications define custom "reducers" based on a protocol named ValueReducer, which was removed in GRDB 5. See the [#731](https://github.com/groue/GRDB.swift/pull/731) conversation for a solution towards a replacement.
|
||||
Finally, ValueObservation used to let application define custom "reducers" based on a protocol name ValueReducer, which was removed in GRDB 5. See the [#731](https://github.com/groue/GRDB.swift/pull/731) conversation for a solution towards a replacement.
|
||||
|
||||
<details>
|
||||
<summary>RxGRDB impact</summary>
|
||||
@@ -181,13 +181,13 @@ let cancellable = observation.start(
|
||||
|
||||
**The behavior of ValueObservation has changed**.
|
||||
|
||||
The changes can have quite an impact on your application. We'll describe them below, as well as the strategies to restore the previous behavior when needed.
|
||||
The changes can quite impact your application. We'll describe them below, as well as the strategies to restore the previous behavior when needed.
|
||||
|
||||
1. ValueObservation used to notify its initial value *immediately* when the observation starts. Now, it notifies fresh values on the main thread, *asynchronously*, by default.
|
||||
|
||||
This means that the parts of your application that rely on this immediate value to, say, set up their user interface, have to be modified. Otherwise, they may suffer from a brief flash of missing data, during the short amount of time between the beginning of the observation, and the asynchronous delivery of the initial value.
|
||||
|
||||
To get an immediate, synchronous, delivery of the initial value, insert a `scheduling: .immediate` argument in the `start` method:
|
||||
To be granted with an immediate, synchronous, delivery of the initial value, insert a `scheduling: .immediate` argument in the `start` method:
|
||||
|
||||
```swift
|
||||
let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
@@ -273,7 +273,7 @@ The changes can have quite an impact on your application. We'll describe them be
|
||||
observation.start(in: dbQueue, scheduling: .async(onQueue: queue), onError: ..., onChange: ...)
|
||||
```
|
||||
|
||||
The GRDB 4 `startImmediately` parameter is no longer supported: ValueObservation now always emits an initial value, without waiting for changes. It is up to your application to ignore this initial value if it wants to.
|
||||
The GRDB 4 `startImmediately` parameter is no longer supported: ValueObservation now always emits an initial value, without waiting for eventual changes. It is up to your application to ignore this initial value if it wants to.
|
||||
|
||||
|
||||
### Removed ValueObservation Methods
|
||||
@@ -319,7 +319,7 @@ The changes can have quite an impact on your application. We'll describe them be
|
||||
}
|
||||
```
|
||||
|
||||
As in previous versions of GRDB, do not use the `combineLatest` operators of Combine or RxSwift in order to combine several ValueObservation instances. You would lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
|
||||
As is previous versions of GRDB, do not use the `combineLatest` operators of Combine or RxSwift in order to combine several ValueObservation. You would lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
|
||||
|
||||
|
||||
## Combine Integration
|
||||
@@ -344,7 +344,7 @@ let publisher = observation
|
||||
|
||||
## Other Changes
|
||||
|
||||
1. The `Configuration.trace` property has been removed. You now use the `Database.trace(options:_:)` method instead:
|
||||
1. The `Configuration.trace` property has been removed. You know use the `Database.trace(options:_:)` method instead:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -360,7 +360,7 @@ let publisher = observation
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
```
|
||||
|
||||
2. [Batch updates] used to rely on the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
|
||||
2. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -372,7 +372,7 @@ let publisher = observation
|
||||
|
||||
> :question: This change avoids conflicts with other libraries that define the same operator.
|
||||
|
||||
3. [SQL Interpolation] no longer wraps subqueries in parentheses:
|
||||
3. [SQL Interpolation] does no longer wrap subqueries in parenthesis:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -382,12 +382,12 @@ let publisher = observation
|
||||
// NEW: GRDB 5
|
||||
let maximumScore: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
let bestPlayers: SQLRequest<Player> = "SELECT * FROM player WHERE score = (\(maximumScore))"
|
||||
// extra parentheses required: ^ ^
|
||||
// extra parenthesis required: ^ ^
|
||||
```
|
||||
|
||||
> :question: This change makes it possible to concatenate subqueries with the UNION operator.
|
||||
|
||||
4. In order to extract the raw SQL string from an [SQL literal], you now need a database connection:
|
||||
4. In order to extract raw SQL string from an [SQL literal], you now need a database connection:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -404,7 +404,7 @@ let publisher = observation
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
```
|
||||
|
||||
5. In order to extract the raw SQL string from a request ([SQLRequest] or [QueryInterfaceRequest]), you now need to call the `makePreparedRequest()` method:
|
||||
5. In order to extract raw SQL string from a request ([SQLRequest] or [QueryInterfaceRequest]), you now need to call the `makePreparedRequest()` method:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -460,7 +460,7 @@ let publisher = observation
|
||||
import GRDB
|
||||
```
|
||||
|
||||
10. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You no longer need to import the underlying SQLite library:
|
||||
10. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
Migrating From GRDB 5 to GRDB 6
|
||||
===============================
|
||||
|
||||
**This guide aims at helping you upgrade your applications from GRDB 5 to GRDB 6.**
|
||||
**This guide aims at helping you upgrading your applications from GRDB 5 to GRDB 6.**
|
||||
|
||||
- [Preparing the Migration to GRDB 6](#preparing-the-migration-to-grdb-6)
|
||||
- [New requirements](#new-requirements)
|
||||
@@ -24,7 +24,7 @@ GRDB requirements have been bumped:
|
||||
- **Xcode 14.0+** (was Xcode 12.0+)
|
||||
- iOS 11.0+ (unchanged)
|
||||
- **macOS 10.13+** (was macOS 10.10+)
|
||||
- **tvOS 11.0+** (was tvOS 9.0+)
|
||||
- **tvOS 11.0+** (was tvOS 11.0+)
|
||||
- **watchOS 4.0+** (was watchOS 2.0+)
|
||||
- **SQLite 3.19.3+** (was SQLite 3.8.5+)
|
||||
|
||||
@@ -154,7 +154,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
}
|
||||
```
|
||||
|
||||
If you subclass the `Record` class, you have to call `super` at some point in your implementation:
|
||||
If you subclass the `Record` class, you have to call `super` at some point of your implementation:
|
||||
|
||||
```diff
|
||||
class Player: Record {
|
||||
@@ -242,7 +242,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
try link.upsert(db) // Calls the willSave callback
|
||||
```
|
||||
|
||||
If you subclass the `Record` class, you have to call `super` at some point in your implementation:
|
||||
If you subclass the `Record` class, you have to call `super` at some point of your implementation:
|
||||
|
||||
```swift
|
||||
// GRDB 6
|
||||
@@ -283,7 +283,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
// How to detect failed `INSERT OR IGNORE`:
|
||||
// INSERT OR IGNORE INTO player ... RETURNING *
|
||||
if let insertedPlayer = try player.insertAndFetch(db) {
|
||||
// Successful insertion
|
||||
// Succesful insertion
|
||||
} else {
|
||||
// Ignored failure
|
||||
}
|
||||
@@ -317,7 +317,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
|
||||
- The `Record.copy()` method was removed, without replacement.
|
||||
|
||||
- The `DerivableRequest.limit(_:offset:)` method was removed, without replacement.
|
||||
- The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement.
|
||||
|
||||
You can still limit `QueryInterfaceRequest`, but associations can no longer be limited:
|
||||
|
||||
@@ -371,7 +371,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
```diff
|
||||
-db.afterNextTransactionCommit { db in
|
||||
+db.afterNextTransaction { db in
|
||||
print("Successful commit")
|
||||
print("Succesful commit")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ Before upgrading, ensure you are using the [latest GRDB 6 release](https://githu
|
||||
|
||||
GRDB 7 requires Xcode 16+ and a Swift 6 compiler.
|
||||
|
||||
Depending on the language mode and level of concurrency checking used by your application, you may see warnings or errors. See [Migrating to Swift 6] on swift.org for more information about Swift 6. See [Swift Concurrency and GRDB] for GRDB-focused advice.
|
||||
Depending of the language mode and level of concurrency checkings used by your application, you may see warnings or errors. See [Migrating to Swift 6] on swift.org for more information about Swift 6. See [Swift Concurrency and GRDB] for GRDB-focused advice.
|
||||
|
||||
## New requirements
|
||||
|
||||
@@ -79,7 +79,7 @@ In GRDB 6, asynchronous database accesses such as `try await read { ... }` or `t
|
||||
|
||||
In GRDB 7, asynchronous database accesses respect Task cancellation. If a Task is cancelled, reads and writes throw a `CancellationError`, pending transactions are rolled back, and the database is not modified. The only SQL statement that can execute in a cancelled database access is `ROLLBACK`.
|
||||
|
||||
The effect of this change on your application depends on how it uses tasks. For example, take care of database jobs initiated from the [`task`](https://developer.apple.com/documentation/swiftui/view/task(priority:_:)) SwiftUI modifier.
|
||||
The effect of this change on your application depends on how it uses tasks. For example, take care of database jobs initiated frop the [`task`](https://developer.apple.com/documentation/swiftui/view/task(priority:_:)) SwiftUI modifier.
|
||||
|
||||
If you want an asynchronous database access to always complete, regardless of Task cancellation, wrap it in an unstructured Task:
|
||||
|
||||
@@ -95,7 +95,7 @@ let task = Task {
|
||||
try await task.value
|
||||
```
|
||||
|
||||
Other asynchronous database accesses, such as methods accepting a completion block (`asyncRead`, etc.), Combine publishers, RxSwift observables, do not handle cancellation and will proceed to completion by default.
|
||||
Other asynchronous database accesses, such as methods accepting a completion blocks (`asyncRead`, etc.), Combine publishers, RxSwift observables, do not handle cancellation and will proceed to completion by default.
|
||||
|
||||
## Associations to record types named Bias, Focus, Gas, and Lens
|
||||
|
||||
@@ -160,9 +160,9 @@ You can still specify a transaction kind explicitly when necessary. See [Transac
|
||||
|
||||
## ValueObservation and the Main Actor
|
||||
|
||||
In GRDB 7, `ValueObservation` favors the main actor, because it is frequently used to automatically update database values on screen.
|
||||
In GRDB 7, `ValueObservation` fosters the main actor, because it is frequently used to automatically update database values on screen.
|
||||
|
||||
By default, its [`start`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be called on the main actor, and its notification callbacks run on the main actor as well.
|
||||
By default, its [`start`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be started on the main actor, and its notification callbacks run on the main actor as well.
|
||||
|
||||
It is not necessary to call `MainActor.assumeIsolated` in `ValueObservation` callbacks:
|
||||
|
||||
@@ -235,9 +235,9 @@ In GRDB 7, you may need an additional import, depending on how GRDB is integrate
|
||||
|
||||
Subclassing the [Record] class is **discouraged** in GRDB 7. Present in GRDB 1.0, in 2017, it has served its purpose.
|
||||
|
||||
It is not recommended to define any new type that subclasses `Record`.
|
||||
It is not recommended to define any new type that subclass `Record`.
|
||||
|
||||
It is recommended to refactor `Record` subclasses into Swift structs, before you enable the strict concurrency checking or the Swift 6 language mode. See [Migrating to Swift 6] for more information about Swift 6 language modes.
|
||||
It is recommended to refactor `Record` subclasses into Swift structs, before you enable the strict concurrency checkings or the Swift 6 language mode. See [Migrating to Swift 6] for more information about Swift 6 language modes.
|
||||
|
||||
For example:
|
||||
|
||||
@@ -273,7 +273,7 @@ Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non
|
||||
|
||||
- The `PersistenceContainer` subscript no longer guarantees that the value returned is the same as what was previously set. It only guarantees that both values are encoded identically in the database.
|
||||
|
||||
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
|
||||
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/GRDB.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
|
||||
|
||||
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide
|
||||
[Sharing a Database]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
Migrating From GRDB 7 to GRDB 8
|
||||
===============================
|
||||
|
||||
**This guide helps you upgrade your applications from GRDB 7 to GRDB 8.**
|
||||
|
||||
- [Preparing the Migration to GRDB 8](#preparing-the-migration-to-grdb-8)
|
||||
- [New requirements](#new-requirements)
|
||||
- [CocoaPods is no Longer Supported](#cocoapods-is-no-longer-supported)
|
||||
- [SQLCipher](#sqlcipher)
|
||||
- [Cached Statements](#cached-statements)
|
||||
- [JSON User Info](#json-user-info)
|
||||
|
||||
## Preparing the Migration to GRDB 8
|
||||
|
||||
Before upgrading, ensure you are using the [latest GRDB 7 release](https://github.com/groue/GRDB.swift/tags) and address any deprecation warnings. Once this is done, proceed with upgrading to GRDB 8. Due to breaking changes, your application may no longer compile. Follow the fix-it suggestions, and review the specific modifications described below.
|
||||
|
||||
## New requirements
|
||||
|
||||
GRDB requirements have been bumped:
|
||||
|
||||
- **Swift Compiler 6.4+** (was Swift 6.1+)
|
||||
- **Xcode 27.0+** (was Xcode 16.3+)
|
||||
- **iOS 15.0+** (was iOS 13.0+)
|
||||
- **macOS 12.0+** (was macOS 10.15+)
|
||||
- **tvOS 15.0+** (was tvOS 13.0+)
|
||||
- **watchOS 9.0+** (was watchOS 7.0+)
|
||||
- **SQLite 3.36.0+** (was SQLite 3.20.0+)
|
||||
- **SQLCipher 4.5+** (was SQLCipher 3.4+)
|
||||
|
||||
## CocoaPods is no Longer Supported
|
||||
|
||||
GRDB 8 is no longer distributed with CocoaPods. Install it with the Swift Package Manager, or manually. See [Installation](../README.md#installation).
|
||||
|
||||
## SQLCipher
|
||||
|
||||
To use GRDB with SQLCipher, enable the `SQLCipher` trait of the GRDB package. There is no longer any need to fork GRDB. See [Encryption](../README.md#encryption).
|
||||
|
||||
When GRDB uses SQLCipher, access SQLite C functions with `import SQLCipher` only. Importing `SQLite3` or `GRDBSQLite` can link the system SQLite next to SQLCipher, which creates undefined behavior.
|
||||
|
||||
## Cached Statements
|
||||
|
||||
The statements returned by `Database.cachedStatement(sql:)` and `Database.cachedStatement(literal:)` no longer preserve their arguments between two calls. You must set the arguments of a cached statement each time you load it from the cache:
|
||||
|
||||
```swift
|
||||
// GRDB 7: relies on the arguments set by the first call.
|
||||
try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
.setArguments(["Arthur"])
|
||||
try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
.execute()
|
||||
|
||||
// GRDB 8: set arguments each time.
|
||||
try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
.execute(arguments: ["Arthur"])
|
||||
```
|
||||
|
||||
Two calls with the same SQL no longer return the same statement when the first one is still in use (held by the application or by a cursor). This allows nested iterations of the same cached SQL.
|
||||
|
||||
## JSON User Info
|
||||
|
||||
The `databaseDecodingUserInfo` and `databaseEncodingUserInfo` properties of record types are now declared as `[CodingUserInfoKey: any Sendable]`, like `JSONDecoder.userInfo` and `JSONEncoder.userInfo`.
|
||||
|
||||
Update the declarations of these properties in your record types, as below. In the Swift 6 language mode, a property declared as `[CodingUserInfoKey: Any]` no longer matches the protocol requirement, and is ignored by GRDB. The compiler does not emit any diagnostic.
|
||||
|
||||
```swift
|
||||
// GRDB 7
|
||||
struct Player: FetchableRecord, Decodable {
|
||||
static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { ... }
|
||||
}
|
||||
|
||||
// GRDB 8
|
||||
struct Player: FetchableRecord, Decodable {
|
||||
static var databaseDecodingUserInfo: [CodingUserInfoKey: any Sendable] { ... }
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,144 @@
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDB scheme: menu Product > Scheme > GRDB
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
|
||||
import GRDB
|
||||
|
||||
//: Open a database connection
|
||||
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { print("SQL> \($0)") }
|
||||
}
|
||||
let dbQueue = try DatabaseQueue(configuration: configuration)
|
||||
|
||||
//: Use a migrator to define the database schema
|
||||
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createLibrary") { db in
|
||||
try db.create(table: "author") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "book") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("title", .text).notNull()
|
||||
t.belongsTo("author", onDelete: .cascade).notNull()
|
||||
}
|
||||
}
|
||||
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
//: Define Record types
|
||||
|
||||
struct Author: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
struct Book: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
//: Define Associations
|
||||
|
||||
extension Author {
|
||||
static let books = hasMany(Book.self)
|
||||
var books: QueryInterfaceRequest<Book> { request(for: Author.books) }
|
||||
}
|
||||
|
||||
extension Book {
|
||||
static let author = belongsTo(Author.self)
|
||||
var author: QueryInterfaceRequest<Author> { request(for: Book.author) }
|
||||
}
|
||||
|
||||
//: Populate the database
|
||||
|
||||
print("----------")
|
||||
print("Populate the database")
|
||||
try dbQueue.write { db in
|
||||
var melville = Author(id: nil, name: "Hermann Melville")
|
||||
try melville.insert(db)
|
||||
var mobyDick = Book(id: nil, authorId: melville.id!, title: "Moby-Dick")
|
||||
try mobyDick.insert(db)
|
||||
|
||||
var genet = Author(id: nil, name: "Jean Genet")
|
||||
try genet.insert(db)
|
||||
var querelle = Book(id: nil, authorId: genet.id!, title: "Querelle de Brest")
|
||||
try querelle.insert(db)
|
||||
var lesBonnes = Book(id: nil, authorId: genet.id!, title: "Les Bonnes")
|
||||
try lesBonnes.insert(db)
|
||||
}
|
||||
|
||||
//: Fetch author information
|
||||
|
||||
print("----------")
|
||||
print("Fetch author information")
|
||||
struct AuthorInfo {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
}
|
||||
let authorId = 2
|
||||
let authorInfo: AuthorInfo? = try dbQueue.read { db in
|
||||
guard let author = try Author.fetchOne(db, key: authorId) else { return nil }
|
||||
let books = try author.books.fetchAll(db)
|
||||
return AuthorInfo(author: author, books: books)
|
||||
}
|
||||
if let authorInfo {
|
||||
print("\(authorInfo.author.name) has written:")
|
||||
for book in authorInfo.books {
|
||||
print("- \(book.title)")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//: Fetch book information
|
||||
|
||||
print("----------")
|
||||
print("Fetch book information")
|
||||
struct BookInfo: FetchableRecord, Codable {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
let bookId = 1
|
||||
let bookInfo: BookInfo? = try dbQueue.read { db in
|
||||
let request = Book
|
||||
.filter(key: bookId)
|
||||
.including(required: Book.author)
|
||||
return try BookInfo.fetchOne(db, request)
|
||||
}
|
||||
if let bookInfo {
|
||||
print("\(bookInfo.book.title) was written by \(bookInfo.author.name)")
|
||||
}
|
||||
|
||||
//: Fetch all authorships
|
||||
|
||||
print("----------")
|
||||
print("Fetch all authorships")
|
||||
struct Authorship: Decodable, FetchableRecord {
|
||||
var book: Book
|
||||
var author: Author
|
||||
}
|
||||
let authorships: [Authorship] = try dbQueue.read { db in
|
||||
let request = Book.including(required: Book.author)
|
||||
return try Authorship.fetchAll(db, request)
|
||||
}
|
||||
for authorship in authorships {
|
||||
print("\(authorship.book.title) was written by \(authorship.author.name)")
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<playground version='5.0' target-platform='macos' buildActiveScheme='true'>
|
||||
<timeline fileName='timeline.xctimeline'/>
|
||||
</playground>
|
||||
@@ -0,0 +1,46 @@
|
||||
// To run this playground, select and build the GRDB scheme.
|
||||
|
||||
import GRDB
|
||||
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { print("SQL> \($0)") }
|
||||
}
|
||||
let dbQueue = try DatabaseQueue(configuration: configuration)
|
||||
|
||||
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
do {
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try player.insert(db)
|
||||
player = Player(id: nil, name: "Barbara", score: 100)
|
||||
try player.insert(db)
|
||||
}
|
||||
|
||||
do {
|
||||
let players = try Player.fetchAll(db)
|
||||
for player in players {
|
||||
print(player)
|
||||
}
|
||||
}
|
||||
|
||||
do {
|
||||
let count = try Player.fetchCount(db)
|
||||
print(count)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<playground version='5.0' target-platform='macos' buildActiveScheme='true'>
|
||||
<timeline fileName='timeline.xctimeline'/>
|
||||
</playground>
|
||||
@@ -0,0 +1,141 @@
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDB scheme: menu Product > Scheme > GRDB
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
//:
|
||||
//: Tour
|
||||
//: ======
|
||||
//:
|
||||
//: This playground is a quick tour of GRDB.
|
||||
|
||||
import GRDB
|
||||
import CoreLocation
|
||||
|
||||
|
||||
//: Open a connection to the database
|
||||
|
||||
// Open an in-memory database that logs all SQL statements
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { print("SQL> \($0)") }
|
||||
}
|
||||
let dbQueue = try DatabaseQueue(configuration: configuration)
|
||||
|
||||
|
||||
//: Execute SQL queries
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE place (
|
||||
id INTEGER PRIMARY KEY,
|
||||
title TEXT,
|
||||
isFavorite BOOLEAN NOT NULL,
|
||||
latitude DOUBLE NOT NULL,
|
||||
longitude DOUBLE NOT NULL
|
||||
)
|
||||
""")
|
||||
|
||||
try db.execute(sql: """
|
||||
INSERT INTO place (title, isFavorite, latitude, longitude)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""", arguments: ["Paris", true, 48.85341, 2.3488])
|
||||
let parisId = db.lastInsertedRowID
|
||||
}
|
||||
|
||||
|
||||
//: Fetch database rows and values
|
||||
|
||||
try! dbQueue.inDatabase { db in
|
||||
let rows = try Row.fetchCursor(db, sql: "SELECT * FROM place")
|
||||
while let row = try rows.next() {
|
||||
let title: String = row["title"]
|
||||
let isFavorite: Bool = row["isFavorite"]
|
||||
let coordinate = CLLocationCoordinate2D(
|
||||
latitude: row["latitude"],
|
||||
longitude: row["longitude"])
|
||||
print("Fetched", title, isFavorite, coordinate)
|
||||
}
|
||||
|
||||
let placeCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! // Int
|
||||
let placeTitles = try String.fetchAll(db, sql: "SELECT title FROM place") // [String]
|
||||
}
|
||||
|
||||
|
||||
//: Insert and fetch records
|
||||
|
||||
struct Place {
|
||||
var id: Int64?
|
||||
var title: String?
|
||||
var isFavorite: Bool
|
||||
var coordinate: CLLocationCoordinate2D
|
||||
}
|
||||
|
||||
// Adopt FetchableRecord
|
||||
extension Place : FetchableRecord {
|
||||
init(row: Row) {
|
||||
id = row[Columns.id]
|
||||
title = row[Columns.title]
|
||||
isFavorite = row[Columns.isFavorite]
|
||||
coordinate = CLLocationCoordinate2DMake(
|
||||
row[Columns.latitude],
|
||||
row[Columns.longitude])
|
||||
}
|
||||
}
|
||||
|
||||
// Adopt TableRecord
|
||||
extension Place : TableRecord {
|
||||
static let databaseTableName = "place"
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let title = Column("title")
|
||||
static let isFavorite = Column("isFavorite")
|
||||
static let latitude = Column("latitude")
|
||||
static let longitude = Column("longitude")
|
||||
}
|
||||
}
|
||||
|
||||
// Adopt MutablePersistableRecord
|
||||
extension Place : MutablePersistableRecord {
|
||||
func encode(to container: inout PersistenceContainer) throws {
|
||||
container[Columns.id] = id
|
||||
container[Columns.title] = title
|
||||
container[Columns.isFavorite] = isFavorite
|
||||
container[Columns.latitude] = coordinate.latitude
|
||||
container[Columns.longitude] = coordinate.longitude
|
||||
}
|
||||
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.inDatabase { db in
|
||||
var berlin = Place(
|
||||
id: nil,
|
||||
title: "Berlin",
|
||||
isFavorite: false,
|
||||
coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053))
|
||||
|
||||
try berlin.insert(db)
|
||||
berlin.id // some value
|
||||
|
||||
berlin.isFavorite = true
|
||||
try berlin.update(db)
|
||||
|
||||
// Fetch from SQL
|
||||
let places = try Place.fetchAll(db, sql: "SELECT * FROM place") // [Place]
|
||||
|
||||
|
||||
//: Avoid SQL with the query interface:
|
||||
|
||||
berlin = try Place.filter { $0.title == "Berlin" }.fetchOne(db)! // Place
|
||||
let paris = try Place.fetchOne(db, key: 1) // Place?
|
||||
let favoritePlaces = try Place // [Place]
|
||||
.filter { $0.isFavorite == true }
|
||||
.order { $0.title }
|
||||
.fetchAll(db)
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<playground version='5.0' target-platform='osx' display-mode='raw' buildActiveScheme='true'>
|
||||
<timeline fileName='timeline.xctimeline'/>
|
||||
</playground>
|
||||
@@ -0,0 +1,84 @@
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDB scheme: menu Product > Scheme > GRDB
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
|
||||
import GRDB
|
||||
|
||||
|
||||
// Create the database
|
||||
|
||||
let dbQueue = try DatabaseQueue() // Memory database
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("createPerson") { db in
|
||||
try db.create(table: "person") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
}
|
||||
migrator.registerMigration("createPet") { db in
|
||||
try db.create(table: "pet") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
t.belongsTo("owner", inTable: "person", onDelete: .cascade)
|
||||
}
|
||||
}
|
||||
try! migrator.migrate(dbQueue)
|
||||
|
||||
|
||||
//
|
||||
|
||||
class TableChangeObserver : NSObject, TransactionObserver {
|
||||
private var changedTableNames: Set<String> = []
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true }
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
changedTableNames.insert(event.tableName)
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
print("Changed table(s): \(changedTableNames.joined(separator: ", "))")
|
||||
changedTableNames = []
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
changedTableNames = []
|
||||
}
|
||||
}
|
||||
|
||||
let observer = TableChangeObserver()
|
||||
dbQueue.add(transactionObserver: observer)
|
||||
|
||||
|
||||
//
|
||||
|
||||
print("-- Changes without transaction")
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Arthur"])
|
||||
let arthurId = db.lastInsertedRowID
|
||||
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Barbara"])
|
||||
try db.execute(sql: "INSERT INTO pet (ownerId, name) VALUES (?, ?)", arguments: [arthurId, "Barbara"])
|
||||
try db.execute(sql: "DELETE FROM person WHERE id = ?", arguments: [arthurId])
|
||||
}
|
||||
|
||||
print("-- Rollbacked changes")
|
||||
try dbQueue.inTransaction { db in
|
||||
try db.execute(sql: "INSERT INTO person (name) VALUES ('Arthur')")
|
||||
try db.execute(sql: "INSERT INTO person (name) VALUES ('Barbara')")
|
||||
return .rollback
|
||||
}
|
||||
|
||||
|
||||
print("-- Changes wrapped in a transaction")
|
||||
try dbQueue.write { db in
|
||||
try db.execute(sql: "DELETE FROM person")
|
||||
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Arthur"])
|
||||
let arthurId = db.lastInsertedRowID
|
||||
try db.execute(sql: "INSERT INTO person (name) VALUES (?)", arguments: ["Barbara"])
|
||||
try db.execute(sql: "INSERT INTO pet (ownerId, name) VALUES (?, ?)", arguments: [arthurId, "Barbara"])
|
||||
try db.execute(sql: "DELETE FROM person WHERE id = ?", arguments: [arthurId])
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<playground version='5.0' target-platform='osx' display-mode='rendered' buildActiveScheme='true'>
|
||||
<timeline fileName='timeline.xctimeline'/>
|
||||
</playground>
|
||||
@@ -3,7 +3,7 @@ Query Interface Organization
|
||||
|
||||
**The [query interface] is a Swift API that approximates the [SQLite SELECT query grammar](https://sqlite.org/lang_select.html) through a hierarchy of values and protocols.**
|
||||
|
||||
This document describes its inner organization, so that you can make the most of those types and protocols when you want it.
|
||||
This document exposes its inner organization, so that you can leverage the most of those types and protocols when you want it.
|
||||
|
||||
In the diagram below, protocols are pale blue and have rounded corners, and standard types are grey rectangles. Solid arrows read "inherits from", and dashed arrows read "produces". Generic types are marked as such, as well as "PATs" (protocols with associated types).
|
||||
|
||||
@@ -132,9 +132,7 @@ DatabaseRegionConvertible feeds [DatabaseRegionObservation], which tracks databa
|
||||
```swift
|
||||
let request = Player.all()
|
||||
let observation = DatabaseRegionObservation(tracking: request)
|
||||
let cancellable = observation.start(in: dbQueue) { error in
|
||||
// Handle error
|
||||
} onChange: { (db: Database) in
|
||||
let observer = try observation.start(in: dbQueue) { (db: Database) in
|
||||
print("Players were changed")
|
||||
}
|
||||
```
|
||||
@@ -321,10 +319,10 @@ let players: [Player] = try request.fetchAll(db)
|
||||
SQL("name = \("O'Brien")").sqlExpression
|
||||
|
||||
// SQLOrdering
|
||||
SQL("name DESC").sqlOrdering
|
||||
SQL("name DESC)").sqlOrdering
|
||||
|
||||
// SQLSelection
|
||||
SQL("score + bonus AS total").sqlSelection
|
||||
SQL("score + bonus AS total)").sqlSelection
|
||||
SQL("*").sqlSelection
|
||||
|
||||
// SQLRequest
|
||||
|
||||
@@ -1,19 +1,27 @@
|
||||
# Releasing a New Version
|
||||
Release Process
|
||||
===============
|
||||
|
||||
**This is internal documentation.**
|
||||
|
||||
To release a new GRDB version:
|
||||
|
||||
- Tests
|
||||
- `make distclean test`
|
||||
- Build and run GRDBDemo
|
||||
- Check for performance regression with GRDBOSXPerformanceTests
|
||||
- On https://github.com/groue/sqlcipher.git upgrade, update SQLCipher version in README.md
|
||||
- On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in Documentation/CustomSQLiteBuilds.md
|
||||
- Update GRDB version number and release date in:
|
||||
- CHANGELOG.md
|
||||
- GRDB.swift.podspec
|
||||
- README.md
|
||||
- Support/Info.plist
|
||||
- Commit and tag
|
||||
- Look for undesired tags: `git for-each-ref --format '%(refname) %(authorname)' refs/tags | sort -V`
|
||||
- Look for undesired tags: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the `master` branch
|
||||
- Push to the `development` branch
|
||||
- Push to the `GRDB8` branch
|
||||
- Push to the `GRDB7` branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
|
||||
|
||||
`make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
|
||||
@@ -40,7 +40,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
SQL interpolation looks and feels just like regular [String interpolation]:
|
||||
SQL interpolation looks and feel just like regular [String interpolation]:
|
||||
|
||||
```swift
|
||||
let name = "World"
|
||||
@@ -84,7 +84,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
**`SQL` is not a Swift String.** You cannot use the `execute(literal:)` method with a String argument:
|
||||
**`SQL` is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
@@ -131,7 +131,7 @@ let query = SQL(
|
||||
arguments: [name, id])
|
||||
```
|
||||
|
||||
`SQL` can embed any [value], as we have seen above, and more. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
|
||||
`SQL` can embed any [value], as we have seen above, but not only. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
|
||||
|
||||
|
||||
## SQL Interpolation and the Query Interface
|
||||
@@ -183,7 +183,7 @@ let request = Player.filter { date($0.createdAt) == "2020-01-23" }
|
||||
|
||||
The [record protocols] extend your application types with database abilities.
|
||||
|
||||
**A record type knows everything about the schema of its underlying database table**. With the [TableRecord] protocol, the `databaseTableName` property contains the table name. With the [Decodable] protocol, the [CodingKeys] enum contains the column names. And with [FetchableRecord], you can decode raw database rows.
|
||||
**A record type knows everything about the schema of its underlying database table**. With the [TableRecord] protocol, the `databaseTableName` property contains the table name. With the [Decodable] protocol, the [CodingKeys] enum contain the column names. And with [FetchableRecord], you can decode raw database rows.
|
||||
|
||||
SQL Interpolation puts this knowledge to good use, so that you can build robust queries that consistently use correct table and column names. Let's start from this record:
|
||||
|
||||
@@ -203,7 +203,7 @@ Let's extend Player with database methods.
|
||||
|
||||
```swift
|
||||
extension Player {
|
||||
/// Deletes all players with no score
|
||||
/// Deletes all player with no score
|
||||
static func deleteAllWithoutScore(_ db: Database) throws {
|
||||
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
|
||||
}
|
||||
@@ -247,12 +247,12 @@ Let's extend Player with database methods.
|
||||
|
||||
```swift
|
||||
let player = try dbQueue.read { db in
|
||||
// SELECT * FROM player WHERE id = 42
|
||||
// SELECT * player WHERE id = 42
|
||||
try Player.filter(id: 42).fetchOne(db) // Player?
|
||||
}
|
||||
```
|
||||
|
||||
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. It profits from SQL interpolation, and this is why this method simply returns an "SQL literal".
|
||||
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. It profits from SQL interpolation, and this is why this method simply returns an "SQL literal"".
|
||||
|
||||
The first "simple" version only embeds the `\(id)` [value].
|
||||
|
||||
@@ -357,7 +357,7 @@ Let's extend Player with database methods.
|
||||
}
|
||||
```
|
||||
|
||||
This last request shows how to build an SQLRequest from an [SQL Literal]. You will need `SQL` when the request cannot be written in a single stroke.
|
||||
This last request shows how to build an SQLRequest from an [SQL Literal]. You will need `SQL` when the request can not be written in a single stroke.
|
||||
|
||||
|
||||
|
||||
@@ -477,7 +477,7 @@ This chapter lists all kinds of supported interpolations.
|
||||
"SELECT * FROM player WHERE \(literal: condition)"
|
||||
```
|
||||
|
||||
- Plain SQL strings and optional arguments:
|
||||
- Plain SQL strings and eventual arguments:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
Why Adopt GRDB?
|
||||
===============
|
||||
|
||||
This document aims at explaining why GRDB could become your favorite database library.
|
||||
This document aims at exposing why GRDB could become your favorite database library.
|
||||
|
||||
We'll start with a few [core principles](#core-principles), so that you see what this library aims at. Then we'll see how GRDB [solves problems](#solving-problems) that developers often face when they use database libraries such as FMDB, FCModel, SQLite.swift, Core Data, or Realm.
|
||||
We'll start with a few [core principles](#core-principles), so that you see where this library aims at. Then we'll see how GRDB [solves problems](#solving-problems) that developers often face when they use database libraries such as FMDB, FCModel, SQLite.swift, Core Data, or Realm.
|
||||
|
||||
|
||||
## Core Principles
|
||||
@@ -12,7 +12,7 @@ We'll start with a few [core principles](#core-principles), so that you see what
|
||||
|
||||
This is because a database row is not an easy type to deal with, and will never be, compared to a regular model. `player.name` looks and feels more natural than `playerRow["name"]`, doesn't it?
|
||||
|
||||
The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that come with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause.
|
||||
The reputation of "active records" and ORMs has been tarnished by the recent focus on immutability, memory safety, and functional idioms that comes with languages like Swift and Rust. Features of 1st-generation records such as auto-updating, uniquing, lazy loading of relations, etc. are now considered ill-advised, if not plain harmful because of the multi-threading headaches they cause.
|
||||
|
||||
Yet recent ORMs such as Rust's [Diesel] have shown that it is possible to build record types that behave as plain and simple values. GRDB belongs to this family.
|
||||
|
||||
@@ -24,14 +24,14 @@ Complex database queries sometimes need to be prototyped and debugged in an SQL
|
||||
|
||||
### The database file is the single source of truth.
|
||||
|
||||
Each Core Data managed object context has its own version of the database. This can be useful when developing a macOS application full of inspector panels and nested undo stacks. But that's about it.
|
||||
Each Core Data's managed object context has its own version of the database. This can be useful when developing a macOS application full of inspector panels and nested undo stacks. But that's about it.
|
||||
|
||||
In the same vein, each application thread has its own version of a Realm database, with non trivial synchronization points.
|
||||
|
||||
Conversely, GRDB assumes that many apps want to use the database as a reliable and unambiguous storage.
|
||||
|
||||
|
||||
### Application developers have specific needs.
|
||||
### Applications developers have specific needs.
|
||||
|
||||
GRDB puts all bets on SQLite, and focuses on front-end GUI applications.
|
||||
|
||||
@@ -39,9 +39,9 @@ This means that dealing with servers, MySQL, or PostgreSQL is out of scope. GRDB
|
||||
|
||||
Focusing on SQLite and applications has allowed GRDB to build features usually only found in company-sponsored libraries: migrations, record comparison, database observation, multi-threading safety, table view animations, support for reactive streams...
|
||||
|
||||
The bet of GRDB is that developers can greatly benefit from a library that provides efficient and community-tested solutions to existing problems. For example, one cannot address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face.
|
||||
The bet of GRDB is that developers can take great profit from a library that provides efficient and community-tested solutions to existing problems. For example, one can not address the multithreading difficulties of Core Data or Realm without looking at database concurrency and records straight in the face.
|
||||
|
||||
Since you don't have to take my word for it, we'll now see how GRDB actually solves common problems that developers face with other database libraries.
|
||||
Since you don't have to take my words for granted, we'll now see how GRDB actually solves common problems that developers face with other database libraries.
|
||||
|
||||
|
||||
## Solving Problems
|
||||
@@ -88,14 +88,14 @@ try place.delete(db)
|
||||
|
||||
For your convenience, those record protocols can be derived from the [Decodable and Encodable](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) protocols of the standard library. [Codable records] are even given free support for JSON columns and other niceties.
|
||||
|
||||
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. In particular, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
|
||||
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
|
||||
|
||||
See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
|
||||
|
||||
|
||||
### Allow database records to cross threads
|
||||
|
||||
Since records are immutable values, they can safely be used from different threads. You no longer have to pass object ids or references between threads, as in Core Data or Realm:
|
||||
As soon as records are immutable values, they can safely be used from different threads. You no longer have to pass object ids or references between threads, as in Core Data or Realm:
|
||||
|
||||
```swift
|
||||
if let player = try Player.fetchOne(db, key: 1) {
|
||||
@@ -115,7 +115,7 @@ let player = Player(name: "arthur", score: 1000)
|
||||
let players = try Player.fetchAll(db)
|
||||
```
|
||||
|
||||
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, or by observing database changes and reacting accordingly.
|
||||
**Fetched records behave just like an in-memory cache of the database content.** Your application is free to decide, on its own, how it should handle the lifetime of those cached values: by ignoring future database changes, or by observing database changes and react accordingly.
|
||||
|
||||
In order to keep your views synchronized with the database content, you can use [ValueObservation]. It notifies fresh values after each database change, with convenient support for [Combine](Combine.md) and [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB).
|
||||
|
||||
@@ -137,13 +137,13 @@ let cancellable = observation.publisher(in: dbQueue).sink(
|
||||
|
||||
// RxGRDB
|
||||
let disposable = observation.rx.observe(in: dbQueue).subscribe(
|
||||
onNext: { (players: [Player]) in print("Fresh players") },
|
||||
onNext: { (players: [Player]) in print("Fresh playerss") },
|
||||
onError: { error in ... })
|
||||
```
|
||||
|
||||
No matter which observation technique you use, you have common guarantees:
|
||||
|
||||
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rolled back.
|
||||
First, notifications only come from database changes safely saved on disk. This is part of the "database as the single source of truth" core principle. You won't get notifications from unsaved changes or changes that have an opportunity to be rollbacked.
|
||||
|
||||
Next, you choose the dispatch queue on which notifications happen (generally the main queue, by default, as in the examples above). GRDB makes sure notifications happen in the same order as database transactions.
|
||||
|
||||
@@ -184,7 +184,7 @@ The more threats are handled by the application, the more skilled and careful a
|
||||
|
||||
I had to omit [Realm] and [FCModel] from the list, because I don't know them well enough. Yet I'd bet that Realm shares some behaviors with Core Data, and FCModel shares some behaviors with FMDatabaseQueue.
|
||||
|
||||
We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can claim that they are easy to plan, use, or test. This is an argument for leaving the application 100% responsible for conflict handling, in the hope that simple ones can be handled in a simple way.
|
||||
We can see that the threat of conflicts is *always* left to the application. Core Data provides conflict policies, but no one can pretend that they are easy to plan, use, or test. This is an argument for leaving the application 100% responsible for conflict handling, in hope that simple ones can be handled in a simple way.
|
||||
|
||||
Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and you'd better be a very skilled developer in order to use them properly.
|
||||
|
||||
@@ -254,7 +254,7 @@ extension Player {
|
||||
let player = try Player.filter(name: "Arthur O'Brien").fetchOne(db)
|
||||
```
|
||||
|
||||
Custom SQL requests such as the one above are welcome in database observation tools like the built-in [ValueObservation] and its [Combine](Combine.md) and [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB) flavors:
|
||||
Custom SQL requests as the one above are welcome in database observation tools like the built-in [ValueObservation] and its [Combine](Combine.md) and [RxSwift](https://github.com/RxSwiftCommunity/RxGRDB) flavors:
|
||||
|
||||
```swift
|
||||
let playerObservation = ValueObservation.tracking { db in
|
||||
|
||||
File renamed without changes.
|
Before Width: | Height: | Size: 86 KiB After Width: | Height: | Size: 86 KiB |
@@ -0,0 +1,38 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '7.6.1'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
s.homepage = 'https://github.com/groue/GRDB.swift'
|
||||
s.author = { 'Gwendal Roué' => 'gr@pierlis.com' }
|
||||
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
|
||||
s.module_name = 'GRDB'
|
||||
|
||||
s.swift_versions = ['6']
|
||||
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|
|
||||
ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h'
|
||||
ss.framework = 'Foundation'
|
||||
ss.library = 'sqlite3'
|
||||
ss.xcconfig = {
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5',
|
||||
}
|
||||
end
|
||||
|
||||
s.subspec 'SQLCipher' do |ss|
|
||||
ss.source_files = 'GRDB/**/*.swift', 'Support/SQLCipher_config.h'
|
||||
ss.framework = 'Foundation'
|
||||
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'
|
||||
}
|
||||
end
|
||||
end
|
||||
+2087
-430
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2720"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -29,8 +29,8 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7F81B4D422D00430942"
|
||||
BuildableName = "GRDBSwift5Tests.xctest"
|
||||
BlueprintName = "GRDBSwift5Tests"
|
||||
BuildableName = "GRDBTests.xctest"
|
||||
BlueprintName = "GRDBTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
@@ -49,38 +49,8 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7F81B4D422D00430942"
|
||||
BuildableName = "GRDBSwift5Tests.xctest"
|
||||
BlueprintName = "GRDBSwift5Tests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56D0F20730C17218004DBD2B"
|
||||
BuildableName = "GRDBSwift6ApproachableConcurrencyTests.xctest"
|
||||
BlueprintName = "GRDBSwift6ApproachableConcurrencyTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AF4E64BCF2E3A40030D9C72E"
|
||||
BuildableName = "GRDBSwift6MainActorIsolationTests.xctest"
|
||||
BlueprintName = "GRDBSwift6MainActorIsolationTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "137ECBDAB512C64A624D7C18"
|
||||
BuildableName = "GRDBSwift6Tests.xctest"
|
||||
BlueprintName = "GRDBSwift6Tests"
|
||||
BuildableName = "GRDBTests.xctest"
|
||||
BlueprintName = "GRDBTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
|
||||
+20
-1
@@ -1,6 +1,22 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<Group
|
||||
location = "group:Documentation/Playgrounds"
|
||||
name = "Playgrounds">
|
||||
<FileRef
|
||||
location = "group:Tour.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:TransactionObserver.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Associations.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:MyPlayground.playground">
|
||||
</FileRef>
|
||||
</Group>
|
||||
<FileRef
|
||||
location = "group:BRAG.md">
|
||||
</FileRef>
|
||||
@@ -14,7 +30,7 @@
|
||||
location = "group:TODO.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:RELEASING.md">
|
||||
location = "group:Documentation/ReleaseProcess.md">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Makefile">
|
||||
@@ -25,6 +41,9 @@
|
||||
<FileRef
|
||||
location = "group:GRDBCustom.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj">
|
||||
</FileRef>
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if !canImport(Darwin)
|
||||
@@ -92,10 +87,10 @@ public struct Configuration: Sendable {
|
||||
/// with the number of snapshots.
|
||||
///
|
||||
/// The default configuration label is nil.
|
||||
public var label: String?
|
||||
public var label: String? = nil
|
||||
|
||||
/// 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 does not match any
|
||||
/// valid identifier.
|
||||
///
|
||||
/// The default and recommended value is false:
|
||||
@@ -107,9 +102,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
|
||||
@@ -128,7 +123,7 @@ public struct Configuration: Sendable {
|
||||
///
|
||||
/// Set this flag to true when you apply the technique described in
|
||||
/// <doc:DatabaseSharing#How-to-limit-the-0xDEAD10CC-exception>. See
|
||||
/// ``Database/suspendNotification`` for more information about
|
||||
/// ``Database/suspendNotification`` for more informations about
|
||||
/// suspended databases.
|
||||
public var observesSuspensionNotifications = false
|
||||
|
||||
@@ -157,7 +152,7 @@ public struct Configuration: Sendable {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// For debugging purposes, you can set this flag to true, and get more
|
||||
/// For debugging purpose, you can set this flag to true, and get more
|
||||
/// precise database reports. It is your responsibility to prevent sensitive
|
||||
/// information from leaking in unexpected locations, so you should not set
|
||||
/// this flag in release builds (think about GDPR and other
|
||||
@@ -238,7 +233,7 @@ public struct Configuration: Sendable {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// On newly created database files, ``DatabasePool`` activates the WAL
|
||||
/// On newly created databases files, ``DatabasePool`` activates the WAL
|
||||
/// mode after the preparation functions have run.
|
||||
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
|
||||
setups.append(setup)
|
||||
@@ -247,7 +242,7 @@ public struct Configuration: Sendable {
|
||||
// MARK: - Transactions
|
||||
|
||||
/// A boolean value indicating whether it is valid to leave a transaction
|
||||
/// open at the end of a database access method.
|
||||
/// opened at the end of a database access method.
|
||||
///
|
||||
/// The default value is false: not completing a transaction is a
|
||||
/// programmer error:
|
||||
@@ -255,13 +250,13 @@ public struct Configuration: Sendable {
|
||||
/// ```swift
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
///
|
||||
/// // fatal error: A transaction has been left open at the end of a database access
|
||||
/// // fatal error: A transaction has been left opened at the end of a database access
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When true, one can leave an open transaction at the end of a database
|
||||
/// When true, one can leave opened transaction at the end of database
|
||||
/// access method:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -279,7 +274,7 @@ public struct Configuration: Sendable {
|
||||
/// ```
|
||||
///
|
||||
/// This configuration flag has no effect on ``DatabasePool`` reader
|
||||
/// connections: those never allow leaving a transaction open at the end
|
||||
/// connections: those never allow leaving a transaction opened at the end
|
||||
/// of a read access.
|
||||
public var allowsUnsafeTransactions = false
|
||||
|
||||
@@ -325,7 +320,7 @@ public struct Configuration: Sendable {
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
/// Defines how `SQLITE_BUSY` errors are handled.
|
||||
/// Defines the how `SQLITE_BUSY` errors are handled.
|
||||
///
|
||||
/// The default is ``Database/BusyMode/immediateError``.
|
||||
///
|
||||
@@ -334,11 +329,11 @@ public struct Configuration: Sendable {
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
|
||||
/// If nil, GRDB picks a default one.
|
||||
var readonlyBusyMode: Database.BusyMode?
|
||||
var readonlyBusyMode: Database.BusyMode? = nil
|
||||
|
||||
/// The maximum number of concurrent reader connections.
|
||||
///
|
||||
/// This configuration has an effect on ``DatabasePool`` and
|
||||
/// This configuration has effect on ``DatabasePool`` and
|
||||
/// ``DatabaseSnapshotPool`` only. The default value is 5.
|
||||
///
|
||||
/// You can query this value at runtime in order to get the actual capacity
|
||||
@@ -392,7 +387,7 @@ public struct Configuration: Sendable {
|
||||
/// ``qos`` property.
|
||||
///
|
||||
/// The default is nil.
|
||||
public var targetQueue: DispatchQueue?
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
|
||||
/// The target dispatch queue for write database accesses.
|
||||
///
|
||||
@@ -400,7 +395,7 @@ public struct Configuration: Sendable {
|
||||
/// by ``targetQueue``.
|
||||
///
|
||||
/// The default is nil.
|
||||
public var writeTargetQueue: DispatchQueue?
|
||||
public var writeTargetQueue: DispatchQueue? = nil
|
||||
|
||||
#if os(iOS)
|
||||
/// A boolean value indicating whether the database connection releases
|
||||
@@ -418,7 +413,7 @@ public struct Configuration: Sendable {
|
||||
/// default value is false.
|
||||
///
|
||||
/// When the flag is false, a `DatabasePool` closes read-only
|
||||
/// connections when requested to dispose of non-essential memory with
|
||||
/// connections when requested to dispose non-essential memory with
|
||||
/// ``DatabasePool/releaseMemory()``. When true, those connections are
|
||||
/// kept open.
|
||||
///
|
||||
@@ -426,22 +421,6 @@ public struct Configuration: Sendable {
|
||||
/// reveals that a lot of time is spent opening new SQLite connections.
|
||||
public var persistentReadOnlyConnections = false
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// A custom schema source.
|
||||
///
|
||||
/// The use case for a custom schema source is enabling GRDB features that
|
||||
/// would not work with the built-in schema introspection that is provided
|
||||
/// by SQLite. For example, a custom schema source can help record types
|
||||
/// that read or write in a database view.
|
||||
///
|
||||
/// The schema source is automatically disabled during database
|
||||
/// migrations performed by ``DatabaseMigrator``: those access the raw
|
||||
/// SQLite schema, unaltered. If a migration needs a schema source,
|
||||
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
|
||||
/// the body of a migration.
|
||||
public var schemaSource: (any DatabaseSchemaSource)?
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration.
|
||||
@@ -41,7 +41,7 @@ extension RangeReplaceableCollection {
|
||||
|
||||
/// Adds the elements of a cursor to the end of this collection.
|
||||
///
|
||||
/// In case of error, an unspecified number of elements have been added to
|
||||
/// In case of error, an unspecified amount of elements have been added to
|
||||
/// the collection.
|
||||
///
|
||||
/// - parameter newElements: The elements to append to the collection.
|
||||
@@ -279,7 +279,7 @@ extension Sequence {
|
||||
///
|
||||
/// - Cursor types are classes, and have a lifetime.
|
||||
/// - Cursor iteration may throw errors.
|
||||
/// - A cursor cannot be repeated.
|
||||
/// - A cursor can not be repeated.
|
||||
///
|
||||
/// The protocol comes with default implementations for many operations similar
|
||||
/// to those defined by Swift's Sequence protocol: `contains`, `dropFirst`,
|
||||
@@ -346,7 +346,7 @@ extension Cursor {
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = try c.next() {
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
@@ -396,10 +396,10 @@ extension Cursor {
|
||||
/// If the number of elements to drop exceeds the number of elements in
|
||||
/// the cursor, the result is an empty cursor.
|
||||
///
|
||||
/// let numbers = [1, 2, 3, 4, 5]
|
||||
/// try print(Array(AnyCursor(numbers).dropFirst(2)))
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropFirst(2))
|
||||
/// // Prints "[3, 4, 5]"
|
||||
/// try print(Array(AnyCursor(numbers).dropFirst(10)))
|
||||
/// try print(numbers.dropFirst(10))
|
||||
/// // Prints "[]"
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop from the beginning of
|
||||
@@ -415,7 +415,7 @@ extension Cursor {
|
||||
/// The following example drops the first element from a cursor of integers.
|
||||
///
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(Array(numbers.dropFirst()))
|
||||
/// try print(numbers.dropFirst())
|
||||
/// // Prints "[2, 3, 4, 5]"
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
@@ -431,10 +431,10 @@ extension Cursor {
|
||||
/// The cursor must be finite. If the number of elements to drop exceeds
|
||||
/// the number of elements in the cursor, the result is an empty array.
|
||||
///
|
||||
/// let numbers = [1, 2, 3, 4, 5]
|
||||
/// try print(AnyCursor(numbers).dropLast(2))
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.dropLast(2))
|
||||
/// // Prints "[1, 2, 3]"
|
||||
/// try print(AnyCursor(numbers).dropLast(10))
|
||||
/// try print(numbers.dropLast(10))
|
||||
/// // Prints "[]"
|
||||
///
|
||||
/// - Parameter n: The number of elements to drop off the end of the
|
||||
@@ -468,7 +468,7 @@ extension Cursor {
|
||||
/// try print(numbers.dropLast())
|
||||
/// // Prints "[1, 2, 3, 4]"
|
||||
///
|
||||
/// If the cursor has no elements, the result is an empty array.
|
||||
/// If the cursor has no elements, the result is an empty cursor.
|
||||
///
|
||||
/// - Returns: An array leaving off the last element of the cursor.
|
||||
public func dropLast() throws -> [Element] {
|
||||
@@ -552,10 +552,10 @@ extension Cursor {
|
||||
/// If the maximum length exceeds the number of elements in the cursor,
|
||||
/// the result contains all the elements in the cursor.
|
||||
///
|
||||
/// let numbers = [1, 2, 3, 4, 5]
|
||||
/// try print(Array(AnyCursor(numbers).prefix(2)))
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.prefix(2))
|
||||
/// // Prints "[1, 2]"
|
||||
/// try print(Array(AnyCursor(numbers).prefix(10)))
|
||||
/// try print(numbers.prefix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
@@ -612,10 +612,10 @@ extension Cursor {
|
||||
/// elements in the cursor, the result contains all the elements in the
|
||||
/// cursor.
|
||||
///
|
||||
/// let numbers = [1, 2, 3, 4, 5]
|
||||
/// try print(AnyCursor(numbers).suffix(2))
|
||||
/// let numbers = AnyCursor([1, 2, 3, 4, 5])
|
||||
/// try print(numbers.suffix(2))
|
||||
/// // Prints "[4, 5]"
|
||||
/// try print(AnyCursor(numbers).suffix(10))
|
||||
/// try print(numbers.suffix(10))
|
||||
/// // Prints "[1, 2, 3, 4, 5]"
|
||||
///
|
||||
/// - Parameter maxLength: The maximum number of elements to return. The
|
||||
@@ -857,7 +857,7 @@ extension DropWhileCursor: Cursor {
|
||||
/// SELECT 'foo' UNION ALL SELECT 'bar'
|
||||
/// """)
|
||||
/// let cursor = base.enumerated()
|
||||
/// while let (n, x) = try cursor.next() {
|
||||
/// while let (n, x) = cursor.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,15 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -53,8 +48,8 @@ extension Database {
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// In the provided literal, either no argument is set, or all arguments
|
||||
/// are set. An error is raised otherwise. For example:
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. An error is raised otherwise. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // OK
|
||||
@@ -94,8 +89,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 {
|
||||
@@ -144,19 +139,14 @@ extension Database {
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// The returned statement has no argument values.
|
||||
///
|
||||
/// The returned statement is distinct from any statement that is still
|
||||
/// in use (held by the application or by a cursor), even if it has the
|
||||
/// same SQL. For example, it is possible to iterate the results of a
|
||||
/// cached statement while executing the same SQL from another cached
|
||||
/// statement.
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL string.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func cachedStatement(sql: String) throws -> Statement {
|
||||
try statementCache.statement(sql)
|
||||
try publicStatementCache.statement(sql)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
@@ -173,8 +163,8 @@ extension Database {
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// In the provided literal, either no argument is set, or all arguments
|
||||
/// are set. An error is raised otherwise. For example:
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. An error is raised otherwise. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // OK
|
||||
@@ -192,15 +182,6 @@ extension Database {
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// When the literal does not set any argument, the returned statement
|
||||
/// has no argument values.
|
||||
///
|
||||
/// The returned statement is distinct from any statement that is still
|
||||
/// in use (held by the application or by a cursor), even if it has the
|
||||
/// same SQL. For example, it is possible to iterate the results of a
|
||||
/// cached statement while executing the same SQL from another cached
|
||||
/// statement.
|
||||
///
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@@ -214,6 +195,11 @@ extension Database {
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedStatement(sql: String) throws -> Statement {
|
||||
try internalStatementCache.statement(sql)
|
||||
}
|
||||
|
||||
/// Returns a cursor of prepared statements.
|
||||
///
|
||||
/// For example:
|
||||
@@ -278,8 +264,8 @@ extension Database {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// In the provided literal, either no argument is set, or all arguments
|
||||
/// are set. The returned cursor will throw an error otherwise. For example:
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. The returned cursor will throw an error otherwise. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // OK
|
||||
@@ -401,7 +387,7 @@ extension SQLStatementCursor: Cursor {
|
||||
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
|
||||
|
||||
// Compile next statement
|
||||
var statementEnd: UnsafePointer<CChar>?
|
||||
var statementEnd: UnsafePointer<CChar>? = nil
|
||||
let statement = try Statement(
|
||||
database: database,
|
||||
statementStart: baseAddress + offset,
|
||||
@@ -483,12 +469,13 @@ extension Database {
|
||||
/// Always throws an error
|
||||
@usableFromInline
|
||||
func statementDidFail(_ statement: Statement, withResultCode resultCode: CInt) throws -> Never {
|
||||
// Failed statements cannot be reused, because `sqlite3_reset` won't
|
||||
// Failed statements can not be reused, because `sqlite3_reset` won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
//
|
||||
// So make sure we clear this statement from the cache.
|
||||
statementCache.remove(statement)
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
|
||||
checkForAutocommitTransition()
|
||||
|
||||
@@ -523,27 +510,6 @@ extension Database {
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
|
||||
/// Always throws an error
|
||||
func statementCompilationDidFail(
|
||||
at statementStart: UnsafePointer<CChar>,
|
||||
withResultCode resultCode: CInt
|
||||
) throws -> Never {
|
||||
switch ResultCode(rawValue: resultCode) {
|
||||
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
try suspensionMutex.load().checkCancellation()
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
// Throw compilation failure
|
||||
throw DatabaseError(
|
||||
resultCode: resultCode,
|
||||
message: lastErrorMessage,
|
||||
sql: String(cString: statementStart))
|
||||
}
|
||||
|
||||
private func checkForAutocommitTransition() {
|
||||
if sqlite3_get_autocommit(sqliteConnection) == 0 {
|
||||
if autocommitState == .on {
|
||||
@@ -564,17 +530,8 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-unsafe statement cache.
|
||||
///
|
||||
/// The cache holds one statement per SQL string. A cached statement is
|
||||
/// returned only if no one else holds a reference to it. Otherwise, the
|
||||
/// cache returns a new statement, which is not cached.
|
||||
///
|
||||
/// This class is a reference type so that `isKnownUniquelyReferenced` can
|
||||
/// check the cached statements in place. A value type would be copied when
|
||||
/// accessed through the lazy `Database.statementCache` property, and the
|
||||
/// copy would retain all statements.
|
||||
final class StatementCache {
|
||||
/// A thread-unsafe statement cache
|
||||
struct StatementCache {
|
||||
unowned let db: Database
|
||||
private var statements: [String: Statement] = [:]
|
||||
|
||||
@@ -582,20 +539,9 @@ final class StatementCache {
|
||||
self.db = database
|
||||
}
|
||||
|
||||
/// - precondition: this method is called on a valid dispatch queue.
|
||||
func statement(_ sql: String) throws -> Statement {
|
||||
if let index = statements.index(forKey: sql) {
|
||||
// Check the statement in place: a local copy would add
|
||||
// a reference.
|
||||
if isKnownUniquelyReferenced(&statements.values[index]) {
|
||||
let statement = statements.values[index]
|
||||
statement.prepareForReuse()
|
||||
return statement
|
||||
}
|
||||
|
||||
// The cached statement is in use: return a new statement,
|
||||
// which is not cached.
|
||||
return try db.makeStatement(sql: sql)
|
||||
mutating func statement(_ sql: String) throws -> Statement {
|
||||
if let statement = statements[sql] {
|
||||
return statement
|
||||
}
|
||||
|
||||
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
|
||||
@@ -609,15 +555,15 @@ final class StatementCache {
|
||||
return statement
|
||||
}
|
||||
|
||||
func clear() {
|
||||
mutating func clear() {
|
||||
statements = [:]
|
||||
}
|
||||
|
||||
func remove(_ statement: Statement) {
|
||||
mutating func remove(_ statement: Statement) {
|
||||
statements.removeFirst { $0.value === statement }
|
||||
}
|
||||
|
||||
func removeAll(where shouldBeRemoved: (Statement) -> Bool) {
|
||||
mutating func removeAll(where shouldBeRemoved: (Statement) -> Bool) {
|
||||
statements = statements.filter { (_, statement) in !shouldBeRemoved(statement) }
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
import GRDBSQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -119,11 +113,6 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``resumeNotification``
|
||||
/// - ``suspendNotification``
|
||||
///
|
||||
/// ### The Schema Source
|
||||
///
|
||||
/// - ``schemaSource``
|
||||
/// - ``withSchemaSource(_:execute:)``
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``add(tokenizer:)``
|
||||
@@ -180,7 +169,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// connection has been opened is an SQLite misuse, and has no effect.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
|
||||
nonisolated(unsafe) public static var logError: LogErrorFunction? {
|
||||
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
|
||||
didSet {
|
||||
if logError != nil {
|
||||
_registerErrorLogCallback { (_, code, message) in
|
||||
@@ -198,19 +187,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// The database configuration.
|
||||
public let configuration: Configuration
|
||||
|
||||
/// The current schema source.
|
||||
///
|
||||
/// By default, it is the ``Configuration/schemaSource``
|
||||
/// of ``configuration``. To modify the schema source,
|
||||
/// use ``withSchemaSource(_:execute:)``.
|
||||
///
|
||||
/// The schema source is automatically disabled (nil) during database
|
||||
/// migrations performed by ``DatabaseMigrator``: those access the raw
|
||||
/// SQLite schema, unaltered. If a migration needs a schema source,
|
||||
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
|
||||
/// the body of a migration.
|
||||
public internal(set) var schemaSource: (any DatabaseSchemaSource)?
|
||||
|
||||
/// A description of this database connection.
|
||||
///
|
||||
/// The returned string is based on the ``Configuration/label``
|
||||
@@ -300,8 +276,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// The cache for the available database schemas (main, temp, attached databases).
|
||||
var schemaCache = SchemaCache()
|
||||
|
||||
/// The cache for statements, used by both GRDB and the user.
|
||||
lazy var statementCache = StatementCache(database: self)
|
||||
/// The cache for statements managed by GRDB. It is distinct from
|
||||
/// `publicStatementCache` so that we do not mess with statement arguments
|
||||
/// set by the user.
|
||||
lazy var internalStatementCache = StatementCache(database: self)
|
||||
|
||||
/// The cache for statements managed by the user.
|
||||
lazy var publicStatementCache = StatementCache(database: self)
|
||||
|
||||
/// The database authorizer provides information about compiled
|
||||
/// database statements, and prevents the truncate optimization when
|
||||
@@ -331,7 +312,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()
|
||||
@@ -396,7 +377,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
var autocommitState = AutocommitState.on
|
||||
|
||||
/// The date of the current transaction, wrapped in a result that is an
|
||||
/// error if there was an error grabbing this date when the transaction
|
||||
/// error if there was an error grabbing this date when the transaction has
|
||||
/// started.
|
||||
///
|
||||
/// Invariant: `transactionDateResult` is nil iff connection is not
|
||||
@@ -461,7 +442,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.description = description
|
||||
self.configuration = configuration
|
||||
self.schemaSource = configuration.schemaSource
|
||||
self.path = path
|
||||
|
||||
// We do not report read-only transactions to transaction observers, so
|
||||
@@ -479,7 +459,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
private static func openConnection(path: String, flags: CInt) throws -> SQLiteConnection {
|
||||
// See <https://www.sqlite.org/c3ref/open.html>
|
||||
var sqliteConnection: SQLiteConnection?
|
||||
var sqliteConnection: SQLiteConnection? = nil
|
||||
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// https://www.sqlite.org/c3ref/open.html
|
||||
@@ -491,11 +471,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// https://www.sqlite.org/c3ref/close.html
|
||||
// > Calling sqlite3_close() or sqlite3_close_v2() with a NULL
|
||||
// > pointer argument is a harmless no-op.
|
||||
//
|
||||
// Read the error message before the connection is closed.
|
||||
let message = sqliteConnection.map { String(cString: sqlite3_errmsg($0)) }
|
||||
_ = sqlite3_close(sqliteConnection) // ignore result code
|
||||
throw DatabaseError(resultCode: code, message: message)
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
guard let sqliteConnection else {
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
@@ -642,6 +619,24 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
private func validateSQLCipher() throws {
|
||||
// https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
//
|
||||
// > In order to avoid situations where SQLite might be used
|
||||
// > improperly at runtime, we strongly recommend that
|
||||
// > applications institute a runtime test to ensure that the
|
||||
// > application is actually using SQLCipher on the active
|
||||
// > connection.
|
||||
if try String.fetchOne(self, sql: "PRAGMA cipher_version") == nil {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: """
|
||||
GRDB is not linked against SQLCipher. \
|
||||
Check https://discuss.zetetic.net/t/important-advisory-sqlcipher-with-xcode-8-and-new-sdks/1688
|
||||
""")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private func validateFormat() throws {
|
||||
// Users are surprised when they open a picture as a database and
|
||||
// see no error (https://github.com/groue/GRDB.swift/issues/54).
|
||||
@@ -667,7 +662,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// Finalize all cached statements since they would prevent
|
||||
// immediate connection closing.
|
||||
statementCache.clear()
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
|
||||
// https://www.sqlite.org/c3ref/close.html
|
||||
// > If the database connection is associated with unfinalized prepared
|
||||
@@ -710,7 +706,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// Finalize all cached statements since they would prevent
|
||||
// immediate connection closing.
|
||||
statementCache.clear()
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
|
||||
// https://www.sqlite.org/c3ref/close.html
|
||||
// > If sqlite3_close_v2() is called with unfinalized prepared
|
||||
@@ -809,7 +806,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
collationPointer,
|
||||
{ (collationPointer, length1, buffer1, length2, buffer2) in
|
||||
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
|
||||
return collation.xCompare(length1, buffer1.unsafelyUnwrapped, length2, buffer2.unsafelyUnwrapped)
|
||||
return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue)
|
||||
}, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
@@ -833,18 +830,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
func beginReadOnly() throws {
|
||||
if configuration.readonly { return }
|
||||
if readOnlyDepth == 0 {
|
||||
// We MUST ignore interruptions when we enter the read-only mode.
|
||||
// An interruption could make the PRAGMA throw after it has
|
||||
// enabled `query_only`. `readOnlyDepth` would not be increased,
|
||||
// `endReadOnly()` would not run, and the user could not write
|
||||
// with this database connection again.
|
||||
//
|
||||
// It's OK to ignore interruption, since interruption is
|
||||
// concurrent and we can pretend it occurred before or after
|
||||
// the PRAGMA.
|
||||
try ignoringInterruption {
|
||||
try cachedStatement(sql: "PRAGMA query_only = 1").execute()
|
||||
}
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 1").execute()
|
||||
}
|
||||
readOnlyDepth += 1
|
||||
}
|
||||
@@ -855,16 +841,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
readOnlyDepth -= 1
|
||||
assert(readOnlyDepth >= 0, "unbalanced endReadOnly()")
|
||||
if readOnlyDepth == 0 {
|
||||
// We MUST ignore interruptions when we leave the read-only mode,
|
||||
// otherwise user could not write with this database
|
||||
// connection again.
|
||||
//
|
||||
// It's OK to ignore interruption, since interruption is
|
||||
// concurrent and we can pretend it occurred before or after
|
||||
// the PRAGMA.
|
||||
try ignoringInterruption {
|
||||
try cachedStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
}
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -877,7 +854,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// try dbQueue.write do { db in
|
||||
/// // Write OK
|
||||
/// try Player(...).insert(db)
|
||||
///
|
||||
@@ -914,7 +891,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// Reports the database region to ``ValueObservation``.
|
||||
///
|
||||
/// Calling this method does not fetch any database values. It just
|
||||
/// helps optimize `ValueObservation`. See
|
||||
/// helps optimizing `ValueObservation`. See
|
||||
/// ``ValueObservation/trackingConstantRegion(_:)`` for more
|
||||
/// information, and some examples of usage.
|
||||
///
|
||||
@@ -1185,7 +1162,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A suspended database does everything to avoid acquiring a lock on the
|
||||
/// A suspended database makes everything to avoid acquiring a lock on the
|
||||
/// database. All database operations may throw a ``DatabaseError`` of code
|
||||
/// `SQLITE_INTERRUPT` or `SQLITE_ABORT`, except reads in WAL mode.
|
||||
///
|
||||
@@ -1301,31 +1278,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return try value()
|
||||
}
|
||||
|
||||
/// Returns the result of `value`. If `value` throws an interruption
|
||||
/// error, it is retried a second time.
|
||||
func ignoringInterruption<T>(_ value: () throws -> T) rethrows -> T {
|
||||
do {
|
||||
return try value() // swiftlint:disable:next statement_position
|
||||
}
|
||||
catch is CancellationError,
|
||||
DatabaseError.SQLITE_INTERRUPT,
|
||||
DatabaseError.SQLITE_ABORT
|
||||
{
|
||||
// Maybe we were unlucky, and user has interrupted the database
|
||||
// during `value` execution.
|
||||
//
|
||||
// Another possible cause for this error is the FTS5 bug
|
||||
// described at <https://sqlite.org/forum/forumpost/137c7662b3>,
|
||||
// which leaves the database in a sticky interrupted state.
|
||||
// To workaround this bug, we must leave the interrupted state
|
||||
// before retrying:
|
||||
resetAllPreparedStatements()
|
||||
|
||||
// Retry
|
||||
return try value()
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
private func journalMode() throws -> String {
|
||||
if let journalMode = journalModeCache {
|
||||
@@ -1334,7 +1286,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so
|
||||
// that we don't create an infinite loop in checkForSuspensionViolation(from:)
|
||||
var statement: SQLiteStatement?
|
||||
var statement: SQLiteStatement? = nil
|
||||
let sql = "PRAGMA journal_mode"
|
||||
sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
|
||||
defer { sqlite3_finalize(statement) }
|
||||
@@ -1355,9 +1307,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// - When database access is cancelled, this method
|
||||
/// throws `CancellationError`.
|
||||
///
|
||||
/// - When database is suspended, and if the statement would lock the
|
||||
/// - When database is suspensed, and if the statement would lock the
|
||||
/// database in a way that may trigger the 0xDEAD10CC exception, this
|
||||
/// method rolls back the current transaction and throws `SQLITE_ABORT`.
|
||||
/// method rollbacks the current transaction and throws `SQLITE_ABORT`.
|
||||
///
|
||||
/// See `cancel()`, `suspend()` and
|
||||
/// ``Configuration/observesSuspensionNotifications``.
|
||||
@@ -1437,7 +1389,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
throw CancellationError()
|
||||
|
||||
case .abort:
|
||||
// Attempt to release a possible lock with ROLLBACK,
|
||||
// Attempt at releasing an eventual lock with ROLLBACk,
|
||||
// as explained in Database.suspend().
|
||||
try? rollback()
|
||||
|
||||
@@ -1453,14 +1405,14 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// MARK: - Transactions & Savepoint
|
||||
|
||||
/// Throws `SQLITE_ABORT` if called from a transaction-wrapping method and
|
||||
/// transaction has been aborted (for example, by `sqlite3_interrupt`, or an
|
||||
/// `ON CONFLICT ROLLBACK` clause).
|
||||
/// transaction has been aborted (for example, by `sqlite3_interrupt`, or a
|
||||
/// `ON CONFLICT ROLLBACK` clause.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// do {
|
||||
/// // Throws an error because the transaction was rolled back.
|
||||
/// // Throws an error because the transaction was rollbacked.
|
||||
/// try ...
|
||||
/// } catch {
|
||||
/// // Catch the error and continue.
|
||||
@@ -1491,7 +1443,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.writeWithoutTransaction { db in
|
||||
/// try dbQueue.writeWithoutTransaction do { db in
|
||||
/// try db.inTransaction {
|
||||
/// try db.execute(sql: "INSERT ...")
|
||||
/// return .commit
|
||||
@@ -1499,13 +1451,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If `operations` throws an error, the transaction is rolled back and the
|
||||
/// If `operations` throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If it returns ``TransactionCompletion/rollback``, the
|
||||
/// transaction is also rolled back, but no error is thrown.
|
||||
/// transaction is also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
|
||||
///
|
||||
/// - warning: This method is not reentrant: you cannot nest transactions.
|
||||
/// - warning: This method is not reentrant: you can not nest transactions.
|
||||
/// Use ``inSavepoint(_:)`` instead.
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -1519,7 +1471,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// error thrown by `operations`.
|
||||
public func inTransaction(_ kind: TransactionKind? = nil, _ operations: () throws -> TransactionCompletion) throws {
|
||||
// Begin transaction
|
||||
let kind = kind ?? defaultTransactionKind
|
||||
try beginTransaction(kind)
|
||||
|
||||
// Support for `checkForAbortedTransaction()`.
|
||||
@@ -1532,20 +1483,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// Now that transaction has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
var firstError: Error?
|
||||
var firstError: Error? = nil
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
// Another connection may have modified the database schema.
|
||||
//
|
||||
// Don't check in a DEFERRED transaction that may write:
|
||||
// reading the schema version would start a read transaction,
|
||||
// and the later upgrade to a write transaction could fail with
|
||||
// SQLITE_BUSY, which can't be avoided with a busy timeout.
|
||||
// See `beginTransaction(_:)`.
|
||||
if kind != .deferred || isReadOnly {
|
||||
try clearSchemaCacheIfNeeded()
|
||||
}
|
||||
|
||||
let completion = try operations()
|
||||
switch completion {
|
||||
case .commit:
|
||||
@@ -1622,7 +1562,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// try dbQueue.write do {
|
||||
/// try db.inSavepoint {
|
||||
/// try db.execute(sql: "INSERT ...")
|
||||
/// return .commit
|
||||
@@ -1630,9 +1570,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If `operations` throws an error, the savepoint is rolled back and the
|
||||
/// If `operations` throws an error, the savepoint is rollbacked and the
|
||||
/// error is rethrown. If it returns ``TransactionCompletion/rollback``, the
|
||||
/// savepoint is also rolled back, but no error is thrown.
|
||||
/// savepoint is also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// This method is reentrant: you can nest savepoints.
|
||||
///
|
||||
@@ -1686,7 +1626,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// Now that savepoint has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
var firstError: Error?
|
||||
var firstError: Error? = nil
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -1744,25 +1684,19 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
|
||||
// SQLite throws an error for non-deferred transactions when read-only.
|
||||
// We prefer immediate transactions for writes, so that write
|
||||
// transactions cannot overlap. This reduces the opportunity for
|
||||
// transactions can not overlap. This reduces the opportunity for
|
||||
// SQLITE_BUSY, which is immediately thrown whenever a transaction
|
||||
// is upgraded after an initial read and a concurrent processes
|
||||
// has acquired the write lock beforehand. This SQLITE_BUSY error
|
||||
// cannot be avoided with a busy timeout.
|
||||
// can not be avoided with a busy timeout.
|
||||
//
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1483>.
|
||||
let kind = kind ?? defaultTransactionKind
|
||||
let kind = kind ?? (isReadOnly ? .deferred : .immediate)
|
||||
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
|
||||
}
|
||||
|
||||
/// The transaction kind of ``beginTransaction(_:)`` when no kind
|
||||
/// is provided.
|
||||
private var defaultTransactionKind: TransactionKind {
|
||||
isReadOnly ? .deferred : .immediate
|
||||
}
|
||||
|
||||
/// Rolls back a database transaction.
|
||||
/// Rollbacks a database transaction.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
|
||||
///
|
||||
@@ -1808,18 +1742,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// which rollback errors should be ignored, and which rollback errors
|
||||
// should be exposed to the library user.
|
||||
if isInsideTransaction {
|
||||
// We MUST ignore interruptions during the rollback, otherwise
|
||||
// we could leave a transaction open, and trigger a fatal error in
|
||||
// `SerializedDatabase.preconditionNoUnsafeTransactionLeft`.
|
||||
//
|
||||
// It's OK to ignore interruption, since interruption is
|
||||
// concurrent and we can pretend it occurred before or after
|
||||
// the rollback.
|
||||
try ignoringInterruption {
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
}
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
}
|
||||
assert(!isInsideTransaction)
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
|
||||
}
|
||||
|
||||
/// Commits a database transaction.
|
||||
@@ -1832,19 +1757,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
|
||||
}
|
||||
|
||||
/// Resets all prepared statements.
|
||||
///
|
||||
/// This method helps clear the interrupted state, as a workaround
|
||||
/// for https://sqlite.org/forum/forumpost/137c7662b3, discovered
|
||||
/// in https://github.com/groue/GRDB.swift/issues/1838.
|
||||
func resetAllPreparedStatements() {
|
||||
var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil)
|
||||
while stmt != nil {
|
||||
sqlite3_reset(stmt)
|
||||
stmt = sqlite3_next_stmt(sqliteConnection, stmt)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Memory Management
|
||||
|
||||
/// Frees as much memory as possible.
|
||||
@@ -1854,14 +1766,43 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
sqlite3_db_release_memory(sqliteConnection)
|
||||
}
|
||||
schemaCache.clear()
|
||||
statementCache.clear()
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
}
|
||||
|
||||
// MARK: - Erasing
|
||||
|
||||
func erase() throws {
|
||||
#if SQLITE_HAS_CODEC
|
||||
try dropAllDatabaseObjects()
|
||||
// SQLCipher does not support the backup API:
|
||||
// https://discuss.zetetic.net/t/using-the-sqlite-online-backup-api/2631
|
||||
// So we'll drop all database objects one after the other.
|
||||
|
||||
// Prevent foreign keys from messing with drop table statements
|
||||
let foreignKeysEnabled = try Bool.fetchOne(self, sql: "PRAGMA foreign_keys")!
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = OFF")
|
||||
}
|
||||
|
||||
try throwingFirstError(
|
||||
execute: {
|
||||
// Remove all database objects, one after the other
|
||||
try inTransaction {
|
||||
let sql = "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'"
|
||||
while let row = try Row.fetchOne(self, sql: sql) {
|
||||
let type: String = row["type"]
|
||||
let name: String = row["name"]
|
||||
try execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
},
|
||||
finally: {
|
||||
// Restore foreign keys if needed
|
||||
if foreignKeysEnabled {
|
||||
try execute(sql: "PRAGMA foreign_keys = ON")
|
||||
}
|
||||
})
|
||||
#else
|
||||
try DatabaseQueue().backup(to: self)
|
||||
#endif
|
||||
@@ -1984,33 +1925,79 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
@available(*, unavailable)
|
||||
extension Database: Sendable { }
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension Database {
|
||||
/// Returns the count of changes executed by one statement execution.
|
||||
func countChanges<T>(_ count: inout Int, forTable tableName: String, updates: () throws -> T) throws -> T {
|
||||
// Database.changesCount calls sqlite3_changes(), whose documentation says:
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.usePassphrase("secret")
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: String) throws {
|
||||
guard var data = passphrase.data(using: .utf8) else {
|
||||
throw DatabaseError(message: "invalid passphrase")
|
||||
}
|
||||
defer {
|
||||
data.resetBytes(in: 0..<data.count)
|
||||
}
|
||||
try usePassphrase(data)
|
||||
}
|
||||
|
||||
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
/// as in the example below:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.usePassphrase(passphraseData)
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: Data) throws {
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_key(sqliteConnection, $0.baseAddress, CInt($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: String) throws {
|
||||
guard var data = passphrase.data(using: .utf8) else {
|
||||
throw DatabaseError(message: "invalid passphrase")
|
||||
}
|
||||
defer {
|
||||
data.resetBytes(in: 0..<data.count)
|
||||
}
|
||||
try changePassphrase(data)
|
||||
}
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: Data) throws {
|
||||
// FIXME: sqlite3_rekey is discouraged.
|
||||
//
|
||||
// > https://sqlite.org/c3ref/changes.html
|
||||
// > Changes to a view that are intercepted by INSTEAD OF triggers are not counted.
|
||||
// https://github.com/ccgus/fmdb/issues/547#issuecomment-259219320
|
||||
//
|
||||
// We want to support INSTEAD OF triggers, so we prefer to use
|
||||
// sqlite3_total_changes() for views.
|
||||
//
|
||||
// At the same time, FTS5 has sqlite3_total_changes() report changes
|
||||
// even when database is not changed (https://github.com/groue/GRDB.swift/issues/1820)
|
||||
//
|
||||
// Well, let's do our best:
|
||||
if try viewExists(tableName) {
|
||||
let prevCount = totalChangesCount
|
||||
let result = try updates()
|
||||
count = totalChangesCount - prevCount
|
||||
return result
|
||||
} else {
|
||||
let result = try updates()
|
||||
count = changesCount
|
||||
return result
|
||||
// > We (Zetetic) have been discouraging the use of sqlite3_rekey in
|
||||
// > favor of attaching a new database with the desired encryption
|
||||
// > options and using sqlcipher_export() to migrate the contents and
|
||||
// > schema of the original db into the new one:
|
||||
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_rekey(sqliteConnection, $0.baseAddress, CInt($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
extension Database {
|
||||
|
||||
@@ -2036,8 +2023,7 @@ extension Database {
|
||||
/// To set the busy mode of a database, use Configuration:
|
||||
///
|
||||
/// // Wait 1 second before failing with SQLITE_BUSY
|
||||
/// var configuration = Configuration()
|
||||
/// configuration.busyMode = .timeout(1)
|
||||
/// let configuration = Configuration(busyMode: .timeout(1))
|
||||
/// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
|
||||
///
|
||||
/// Relevant SQLite documentation:
|
||||
@@ -2109,7 +2095,7 @@ extension Database {
|
||||
/// // CREATE TABLE player(
|
||||
/// // id INTEGER PRIMARY KEY,
|
||||
/// // name TEXT,
|
||||
/// // creationDate DATETIME
|
||||
/// // creationDate DATETIME,
|
||||
/// // )
|
||||
/// try db.create(table: "player") { t in
|
||||
/// t.primaryKey("id", .integer)
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
/// Describes the progress of a database backup.
|
||||
/// Describe the progress of a database backup.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
public struct DatabaseBackupProgress: Sendable {
|
||||
@@ -12,7 +12,7 @@ public struct DatabaseBackupProgress: Sendable {
|
||||
/// It is the result of the `sqlite3_backup_pagecount` function.
|
||||
public let totalPageCount: Int
|
||||
|
||||
/// The number of backed up pages.
|
||||
/// The number of of backed up pages.
|
||||
///
|
||||
/// It is equal to `totalPageCount - remainingPageCount`.
|
||||
public var completedPageCount: Int {
|
||||
@@ -21,7 +21,7 @@ public struct DatabaseBackupProgress: Sendable {
|
||||
|
||||
/// A boolean value indicating whether the backup is complete.
|
||||
///
|
||||
/// It is true if and only if the last call to `sqlite3_backup_step` has
|
||||
/// It is true if and only if the last call the `sqlite3_backup_step` has
|
||||
/// returned `SQLITE_DONE`.
|
||||
public let isCompleted: Bool
|
||||
}
|
||||
@@ -1,15 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -58,21 +53,12 @@ public final class DatabaseCollation: Identifiable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xCompare` parameter of sqlite3_create_collation_v2
|
||||
/// <https://www.sqlite.org/c3ref/create_collation.html>
|
||||
typealias XCompare = @Sendable (
|
||||
_ length1: CInt,
|
||||
_ buffer1: UnsafeRawPointer,
|
||||
_ length2: CInt,
|
||||
_ buffer2: UnsafeRawPointer
|
||||
) -> CInt
|
||||
|
||||
/// The identifier of the collation.
|
||||
public var id: ID { ID(name: name) }
|
||||
|
||||
/// The name of the collation.
|
||||
public let name: String
|
||||
let xCompare: XCompare
|
||||
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
|
||||
|
||||
/// Creates a collation.
|
||||
///
|
||||
@@ -83,22 +69,27 @@ public final class DatabaseCollation: Identifiable, Sendable {
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard)")
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard")
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The collation name.
|
||||
/// - function: A function that compares two strings.
|
||||
public convenience init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
|
||||
self.init(name, xCompare: { (length1, buffer1, length2, buffer2) in
|
||||
let string1 = String(decoding: UnsafeRawBufferPointer(start: buffer1, count: Int(length1)), as: UTF8.self)
|
||||
let string2 = String(decoding: UnsafeRawBufferPointer(start: buffer2, count: Int(length2)), as: UTF8.self)
|
||||
return CInt(function(string1, string2).rawValue)
|
||||
})
|
||||
}
|
||||
|
||||
init(_ name: String, xCompare: @escaping XCompare) {
|
||||
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
|
||||
self.name = name
|
||||
self.xCompare = xCompare
|
||||
self.function = { (length1, buffer1, length2, buffer2) in
|
||||
// Buffers are not C strings: they do not end with \0.
|
||||
let string1 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
|
||||
length: Int(length1),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
let string2 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
|
||||
length: Int(length2),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
return function(string1, string2)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -31,7 +26,7 @@ public struct ResultCode: RawRepresentable, Equatable {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let resultCode = ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
/// ```
|
||||
public var primaryResultCode: ResultCode {
|
||||
@@ -290,7 +285,7 @@ public struct DatabaseError: Error {
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.resultCode == .SQLITE_CONSTRAINT {
|
||||
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// ```
|
||||
@@ -300,7 +295,7 @@ public struct DatabaseError: Error {
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch DatabaseError.SQLITE_CONSTRAINT {
|
||||
/// } catch DatabaseError.SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// ```
|
||||
@@ -355,10 +350,10 @@ public struct DatabaseError: Error {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - resultCode: A ResultCode (defaults to .SQLITE_ERROR).
|
||||
/// - message: An optional error message. If nil, the error message is
|
||||
/// - message: An eventual error message. If nil, the error message is
|
||||
/// derived from the result code.
|
||||
/// - sql: An optional SQL string.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - sql: An eventual SQL string.
|
||||
/// - arguments: Eventual statement arguments.
|
||||
/// - publicStatementArguments: If false (the default), statement
|
||||
/// arguments are not visible in the error's ``description`` property.
|
||||
public init(
|
||||
@@ -377,7 +372,7 @@ public struct DatabaseError: Error {
|
||||
|
||||
/// Creates a Database Error with a raw CInt result code.
|
||||
///
|
||||
/// This initializer is not public because library users are not supposed to
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
@usableFromInline
|
||||
init(resultCode: CInt, message: String? = nil, sql: String? = nil) {
|
||||
@@ -389,7 +384,7 @@ public struct DatabaseError: Error {
|
||||
|
||||
/// Creates a Database Error with a raw CInt result code.
|
||||
///
|
||||
/// This initializer is not public because library users are not supposed to
|
||||
/// This initializer is not public because library user is not supposed to
|
||||
/// be exposed to raw result codes.
|
||||
@usableFromInline
|
||||
init(
|
||||
@@ -561,7 +556,7 @@ extension DatabaseError: CustomStringConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// SQLite error 19: NOT NULL constraint failed: player.score
|
||||
/// - while executing `UPDATE player SET score = ? WHERE email = ?`
|
||||
/// - while executing `UPDATE player SET score = ? WHERE email = ?
|
||||
///
|
||||
/// The format of the error description may change between GRDB releases,
|
||||
/// without notice: don't have your application rely on any specific format.
|
||||
@@ -584,7 +579,7 @@ extension DatabaseError: CustomStringConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// SQLite error 19: NOT NULL constraint failed: player.score
|
||||
/// - while executing `UPDATE player SET score = ? WHERE email = ?`
|
||||
/// - while executing `UPDATE player SET score = ? WHERE email = ?
|
||||
/// with arguments [nil, "arthur@example.com"]
|
||||
///
|
||||
/// The format of the error description may change between GRDB releases,
|
||||
@@ -1,19 +1,12 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A custom SQL function or aggregate.
|
||||
///
|
||||
/// ## Topics
|
||||
@@ -81,7 +74,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// - argumentCount: The number of arguments of the function. If
|
||||
/// omitted, or nil, the function accepts any number of arguments.
|
||||
/// - pure: Whether the function is "pure", which means that its results
|
||||
/// only depend on its inputs. When a function is pure, SQLite has
|
||||
/// only depends on its inputs. When a function is pure, SQLite has
|
||||
/// the opportunity to perform additional optimizations. Default value
|
||||
/// is false.
|
||||
/// - function: A function that takes an array of ``DatabaseValue``
|
||||
@@ -89,45 +82,20 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// such as `Int`, `String`, `Date`, etc. The array is guaranteed to
|
||||
/// have exactly `argumentCount` elements, provided `argumentCount` is
|
||||
/// not nil.
|
||||
public convenience init(
|
||||
public init(
|
||||
_ name: String,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.init(name, argumentCount: argumentCount, pure: pure) { (argc, argv, context) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv[index]!)
|
||||
}
|
||||
let result = try function(arguments)
|
||||
switch result?.databaseValue.storage ?? .null {
|
||||
case .null:
|
||||
sqlite3_result_null(context)
|
||||
case .int64(let int64):
|
||||
sqlite3_result_int64(context, int64)
|
||||
case .double(let double):
|
||||
sqlite3_result_double(context, double)
|
||||
case .string(var string):
|
||||
string.withSQLiteText {
|
||||
sqlite3_result_text(context, $0, $1, SQLITE_TRANSIENT)
|
||||
}
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(context, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init(
|
||||
_ name: String,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
xFunc: @escaping XFunc)
|
||||
{
|
||||
self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.isPure = pure
|
||||
self.kind = .function(xFunc)
|
||||
self.kind = .function { (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
}
|
||||
return try function(arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an SQL aggregate function.
|
||||
@@ -169,7 +137,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// - argumentCount: The number of arguments of the aggregate. If
|
||||
/// omitted, or nil, the aggregate accepts any number of arguments.
|
||||
/// - pure: Whether the aggregate is "pure", which means that its
|
||||
/// results only depend on its inputs. When an aggregate is pure,
|
||||
/// results only depends on its inputs. When an aggregate is pure,
|
||||
/// SQLite has the opportunity to perform additional optimizations.
|
||||
/// Default value is false.
|
||||
/// - aggregate: A type that implements the ``DatabaseAggregate``
|
||||
@@ -217,7 +185,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// db.add(function: square)
|
||||
///
|
||||
/// // SELECT square(score) FROM player
|
||||
/// let squaredScores = try Player
|
||||
/// let squaredScores = let Player
|
||||
/// .select({ square($0.score) }, as: Int.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
@@ -288,10 +256,11 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class FunctionDefinition {
|
||||
let xFunc: XFunc
|
||||
init(xFunc: @escaping XFunc)
|
||||
let compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
|
||||
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
|
||||
throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.xFunc = xFunc
|
||||
self.compute = compute
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,19 +283,11 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
typealias XFunc = @Sendable (
|
||||
_ argc: CInt,
|
||||
_ argv: UnsafeMutablePointer<OpaquePointer?>,
|
||||
_ context: OpaquePointer?
|
||||
) throws -> Void
|
||||
|
||||
/// A function kind: an "SQL function" or an "aggregate".
|
||||
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private enum Kind: Sendable {
|
||||
/// A regular function: SELECT f(1)
|
||||
case function(XFunc)
|
||||
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
|
||||
|
||||
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
|
||||
case aggregate(@Sendable () -> any DatabaseAggregate)
|
||||
@@ -335,8 +296,8 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var definition: AnyObject {
|
||||
switch self {
|
||||
case .function(let xFunc):
|
||||
return FunctionDefinition(xFunc: xFunc)
|
||||
case .function(let compute):
|
||||
return FunctionDefinition(compute: compute)
|
||||
case .aggregate(let makeAggregate):
|
||||
return AggregateDefinition(makeAggregate: makeAggregate)
|
||||
}
|
||||
@@ -351,7 +312,9 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
.fromOpaque(sqlite3_user_data(sqliteContext))
|
||||
.takeUnretainedValue()
|
||||
do {
|
||||
try definition.xFunc(argc, argv.unsafelyUnwrapped, sqliteContext)
|
||||
try DatabaseFunction.report(
|
||||
result: definition.compute(argc, argv),
|
||||
in: sqliteContext)
|
||||
} catch {
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
@@ -451,10 +414,8 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
sqlite3_result_int64(sqliteContext, int64)
|
||||
case .double(let double):
|
||||
sqlite3_result_double(sqliteContext, double)
|
||||
case .string(var string):
|
||||
string.withSQLiteText {
|
||||
sqlite3_result_text(sqliteContext, $0, $1, SQLITE_TRANSIENT)
|
||||
}
|
||||
case .string(let string):
|
||||
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(sqliteContext, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
@@ -59,7 +59,7 @@ public final class DatabasePool {
|
||||
|
||||
// Readers can't allow dangling transactions because there's no
|
||||
// guarantee that one can get the same reader later in order to close
|
||||
// an open transaction.
|
||||
// an opened transaction.
|
||||
readerConfiguration.allowsUnsafeTransactions = false
|
||||
|
||||
readerPool = Pool(
|
||||
@@ -149,7 +149,7 @@ extension DatabasePool {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
/// Frees as much memory as possible, by disposing of non-essential memory.
|
||||
/// Frees as much memory as possible, by disposing non-essential memory.
|
||||
///
|
||||
/// This method is synchronous, and blocks the current thread until all
|
||||
/// database accesses are completed.
|
||||
@@ -178,14 +178,14 @@ extension DatabasePool {
|
||||
// documented.
|
||||
//
|
||||
// Without the barrier, connections would only close _eventually_ (after
|
||||
// their concurrent jobs have completed).
|
||||
// their eventual concurrent jobs have completed).
|
||||
readerPool?.barrier {
|
||||
readerPool?.removeAll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Eventually frees as much memory as possible, by disposing of
|
||||
/// Eventually frees as much memory as possible, by disposing
|
||||
/// non-essential memory.
|
||||
///
|
||||
/// This method eventually closes all read-only connections, unless the
|
||||
@@ -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 {
|
||||
@@ -342,39 +343,33 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
return try readerPool.get { reader in
|
||||
try reader.sync { db in
|
||||
// clearSchemaCacheIfNeeded() is called by the transaction
|
||||
// started by `isolated`.
|
||||
try db.isolated {
|
||||
try value(db)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func read<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let (reader, releaseReader) = try await readerPool.get()
|
||||
defer { releaseReader(.reuse) }
|
||||
return try await reader.execute { db in
|
||||
defer {
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
}
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
return try await readerPool.get { reader in
|
||||
try await reader.execute { db in
|
||||
defer {
|
||||
// Ignore commit error, but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
assert(!db.isInsideTransaction)
|
||||
}
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -392,13 +387,8 @@ extension DatabasePool: DatabaseReader {
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
// Ignore commit error, but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
assert(!db.isInsideTransaction)
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
@@ -417,6 +407,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 {
|
||||
@@ -430,18 +421,18 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let (reader, releaseReader) = try await readerPool.get()
|
||||
defer { releaseReader(.reuse) }
|
||||
return try await reader.execute { db in
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
return try await readerPool.get { reader in
|
||||
try await reader.execute { db in
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -504,8 +495,8 @@ extension DatabasePool: DatabaseReader {
|
||||
/// any transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// The `value` function is guaranteed to see the database in the last
|
||||
/// committed state at the moment this method is called. Concurrent
|
||||
/// database updates are not visible from the function.
|
||||
/// committed state at the moment this method is called. Eventual
|
||||
/// concurrent database updates are not visible from the function.
|
||||
///
|
||||
/// This method returns as soon as the isolation guarantee described above
|
||||
/// has been established.
|
||||
@@ -516,7 +507,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// ```swift
|
||||
/// try writer.asyncWriteWithoutTransaction { db in
|
||||
/// // Delete all players
|
||||
/// try Player.deleteAll(db)
|
||||
/// try Player.deleteAll()
|
||||
///
|
||||
/// // Count players concurrently
|
||||
/// writer.asyncConcurrentRead { dbResult in
|
||||
@@ -560,13 +551,8 @@ extension DatabasePool: DatabaseReader {
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
reader.async { db in
|
||||
defer {
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
// Ignore commit error, but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
assert(!db.isInsideTransaction)
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
@@ -645,7 +631,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// After this method is called, read-only database access methods will use
|
||||
/// new SQLite connections.
|
||||
///
|
||||
/// Concurrent read-only accesses are not interrupted, and
|
||||
/// Eventual concurrent read-only accesses are not interrupted, and
|
||||
/// proceed until completion.
|
||||
///
|
||||
/// - This method closes all read-only connections, even if the
|
||||
@@ -658,10 +644,6 @@ extension DatabasePool: DatabaseReader {
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
if SchedulingWatchdog.current == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let readerPool else {
|
||||
return nil
|
||||
}
|
||||
@@ -687,7 +669,7 @@ extension DatabasePool: DatabaseReader {
|
||||
|
||||
// MARK: - WAL Snapshot Transactions
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
/// Returns a long-lived WAL snapshot transaction on a reader connection.
|
||||
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
|
||||
guard let readerPool else {
|
||||
@@ -783,16 +765,18 @@ 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)
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T>(
|
||||
_ updates: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
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()
|
||||
@@ -802,28 +786,31 @@ extension DatabasePool: DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T>(
|
||||
_ updates: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
// Pool.barrier does not support async calls (yet?).
|
||||
// So we perform cancellation checks just as in
|
||||
// the async version of SerializedDatabase.execute().
|
||||
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
|
||||
try Task.checkCancellation()
|
||||
return try await readerPool.barrier {
|
||||
return try await withTaskCancellationHandler {
|
||||
try Task.checkCancellation()
|
||||
var result = Disconnected<T?>(nil)
|
||||
try writer.sync { db in
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
}
|
||||
cancelMutex.store(db.cancel)
|
||||
return try await readerPool.barrier {
|
||||
try Task.checkCancellation()
|
||||
try result.exchange(newValue: updates(db))
|
||||
return try writer.sync { db in
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
}
|
||||
cancelMutex.store(db.cancel)
|
||||
try Task.checkCancellation()
|
||||
return try updates(db)
|
||||
}
|
||||
}
|
||||
return result.consume()!
|
||||
} onCancel: {
|
||||
cancelMutex.withLock { $0?() }
|
||||
}
|
||||
@@ -846,10 +833,10 @@ extension DatabasePool: DatabaseWriter {
|
||||
/// The `updates` function runs in the writer dispatch queue, serialized
|
||||
/// with all database updates.
|
||||
///
|
||||
/// If `updates` throws an error, the transaction is rolled back and the
|
||||
/// If `updates` throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If it returns
|
||||
/// ``Database/TransactionCompletion/rollback``, the transaction is also
|
||||
/// rolled back, but no error is thrown.
|
||||
/// rollbacked, but no error is thrown.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -896,15 +883,15 @@ extension DatabasePool {
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
/// Creates a database snapshot that serializes accesses to unchanging
|
||||
/// Creates a database snapshot that serializes accesses to an unchanging
|
||||
/// database content, as it exists at the moment the snapshot is created.
|
||||
///
|
||||
/// It is a programmer error to create a snapshot from the writer dispatch
|
||||
/// queue when a transaction is open:
|
||||
/// queue when a transaction is opened:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbPool.write { db in
|
||||
/// try Player.deleteAll(db)
|
||||
/// try Player.deleteAll()
|
||||
///
|
||||
/// // fatal error: makeSnapshot() must not be called from inside a transaction
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
@@ -921,7 +908,7 @@ extension DatabasePool {
|
||||
/// let snapshot = try dbPool.makeSnapshot() // OK
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll(db)
|
||||
/// try Player.deleteAll()
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
@@ -948,8 +935,8 @@ extension DatabasePool {
|
||||
purpose: "snapshot.\(databaseSnapshotCountMutex.increment())")
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
/// Creates a database snapshot that allows concurrent accesses to
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
/// Creates a database snapshot that allows concurrent accesses to an
|
||||
/// unchanging database content, as it exists at the moment the snapshot
|
||||
/// is created.
|
||||
///
|
||||
File renamed without changes.
@@ -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) {
|
||||
@@ -232,15 +233,13 @@ extension DatabaseQueue: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func read<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute { db in
|
||||
var result = Disconnected<T?>(nil)
|
||||
try db.isolated(readOnly: true) {
|
||||
_ = try result.exchange(newValue: value(db))
|
||||
try value(db)
|
||||
}
|
||||
return result.consume()!
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,13 +248,8 @@ extension DatabaseQueue: DatabaseReader {
|
||||
) {
|
||||
writer.async { db in
|
||||
defer {
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
// Ignore commit error (we can not notify it), but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
@@ -266,7 +260,6 @@ extension DatabaseQueue: DatabaseReader {
|
||||
// See <https://github.com/groue/GRDB.swift/pull/1213>.
|
||||
try db.beginReadOnly()
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
@@ -274,13 +267,14 @@ 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)
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(value)
|
||||
}
|
||||
|
||||
@@ -303,13 +297,8 @@ extension DatabaseQueue: DatabaseReader {
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
|
||||
defer {
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
// Ignore commit error (we can not notify it), but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
@@ -320,7 +309,6 @@ extension DatabaseQueue: DatabaseReader {
|
||||
// See <https://github.com/groue/GRDB.swift/pull/1213>.
|
||||
try db.beginReadOnly()
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
value(.success(db))
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
@@ -359,10 +347,10 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
/// The `updates` function runs in the writer dispatch queue, serialized
|
||||
/// with all database updates.
|
||||
///
|
||||
/// If `updates` throws an error, the transaction is rolled back and the
|
||||
/// If `updates` throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If it returns
|
||||
/// ``Database/TransactionCompletion/rollback``, the transaction is also
|
||||
/// rolled back, but no error is thrown.
|
||||
/// rollbacked, but no error is thrown.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -393,23 +381,25 @@ 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)
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T>(
|
||||
_ updates: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
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)
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T>(
|
||||
_ updates: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(updates)
|
||||
}
|
||||
|
||||
@@ -74,12 +74,12 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// every future database access will throw a ``DatabaseError`` of
|
||||
/// code `SQLITE_MISUSE`.
|
||||
///
|
||||
/// Otherwise, there exist concurrent database accesses or living prepared
|
||||
/// Otherwise, there exists concurrent database accesses or living prepared
|
||||
/// statements that prevent the database from closing, and this method
|
||||
/// throws a ``DatabaseError`` of code `SQLITE_BUSY`.
|
||||
/// See <https://www.sqlite.org/c3ref/close.html> for more information.
|
||||
///
|
||||
/// After an error has been thrown, the database may still be open, and
|
||||
/// After an error has been thrown, the database may still be opened, and
|
||||
/// you can keep on accessing it. It may also remain in a "zombie" state,
|
||||
/// in which case it will throw `SQLITE_MISUSE` for all future
|
||||
/// database accesses.
|
||||
@@ -168,7 +168,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by concurrent writes (even writes performed
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
@@ -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
|
||||
@@ -199,7 +200,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by concurrent writes (even writes performed
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
@@ -213,9 +214,9 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// - throws: Any ``DatabaseError`` that happens while establishing the
|
||||
/// database access, or the error thrown by `value`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func read<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T
|
||||
func read<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules read-only database operations for execution, and
|
||||
/// returns immediately.
|
||||
@@ -234,7 +235,7 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by concurrent writes (even writes performed
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
@@ -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
|
||||
@@ -316,9 +318,9 @@ public protocol DatabaseReader: AnyObject, Sendable {
|
||||
/// - throws: Any ``DatabaseError`` that happens while establishing the
|
||||
/// database access, or the error thrown by `value`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func unsafeRead<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T
|
||||
func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
///
|
||||
@@ -515,7 +517,7 @@ extension DatabaseReader {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by concurrent writes (even writes performed
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
@@ -644,13 +646,14 @@ 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)
|
||||
}
|
||||
|
||||
public func read<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.read(value)
|
||||
}
|
||||
|
||||
@@ -660,13 +663,14 @@ 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)
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.unsafeRead(value)
|
||||
}
|
||||
|
||||
@@ -692,7 +696,7 @@ extension AnyDatabaseReader: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that sees unchanging database content.
|
||||
/// A type that sees an unchanging database content.
|
||||
///
|
||||
/// Do not declare new conformances to `DatabaseSnapshotReader`. Only the
|
||||
/// built-in conforming types are valid.
|
||||
@@ -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)
|
||||
}
|
||||
@@ -11,7 +11,7 @@
|
||||
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
|
||||
///
|
||||
/// It is dedicated to helping ``TransactionObserver`` types detect impactful
|
||||
/// It is dedicated to help ``TransactionObserver`` types detect impactful
|
||||
/// database changes.
|
||||
///
|
||||
/// You get `DatabaseRegion` instances from a ``DatabaseRegionConvertible``
|
||||
@@ -41,8 +41,7 @@
|
||||
/// - ``isModified(byEventsOfKind:)``
|
||||
/// - ``isModified(by:)``
|
||||
public struct DatabaseRegion: Sendable {
|
||||
/// Nil means that the region is the full database.
|
||||
private var tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
|
||||
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
|
||||
self.tableRegions = tableRegions
|
||||
@@ -78,26 +77,19 @@ public struct DatabaseRegion: Sendable {
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Some columns from all rows in a table.
|
||||
/// Full columns in a table: (some columns in a table) × (all rows)
|
||||
init(table: String, columns: Set<String>) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
let columns = Set(columns.map(CaseInsensitiveIdentifier.init))
|
||||
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// All columns from some rows in a table.
|
||||
/// Full rows in a table: (all columns in a table) × (some rows)
|
||||
init(table: String, rowIds: Set<Int64>) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
|
||||
}
|
||||
|
||||
/// Some columns from some rows in a table.
|
||||
init(table: String, columns: Set<String>, rowIds: Set<Int64>) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
let columns = Set(columns.map(CaseInsensitiveIdentifier.init))
|
||||
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: rowIds)])
|
||||
}
|
||||
|
||||
/// Returns the intersection of this region and the given one.
|
||||
///
|
||||
/// This method is not public because there is no known public use case for
|
||||
@@ -170,22 +162,6 @@ public struct DatabaseRegion: Sendable {
|
||||
self = union(other)
|
||||
}
|
||||
|
||||
/// Inserts all columns and rows from the given table.
|
||||
mutating func insert(table: String) {
|
||||
guard tableRegions != nil else { return }
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
tableRegions![table, default: TableRegion()].insertAllRowsAndColumns()
|
||||
}
|
||||
|
||||
/// Inserts the specified column and all rows from the given table.
|
||||
mutating func insert(table: String, column: String) {
|
||||
assert(!column.isEmpty)
|
||||
guard tableRegions != nil else { return }
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
let column = CaseInsensitiveIdentifier(rawValue: column)
|
||||
tableRegions![table, default: TableRegion(columns: [column])].insertAllRowsAndColumn(column)
|
||||
}
|
||||
|
||||
/// Returns a region suitable for database observation
|
||||
func observableRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
// SQLite does not expose schema changes to the
|
||||
@@ -280,8 +256,8 @@ extension DatabaseRegion {
|
||||
}
|
||||
} else {
|
||||
// full database
|
||||
return try db.fetchSchemaIdentifiers().flatMap { schemaID in
|
||||
let schema = try db.schema(schemaID)
|
||||
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
|
||||
let schema = try db.schema(schemaIdentifier)
|
||||
return try schema.objects
|
||||
.filter { $0.type == .table }
|
||||
.flatMap { table in
|
||||
@@ -394,18 +370,6 @@ private struct TableRegion: Equatable {
|
||||
return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion)
|
||||
}
|
||||
|
||||
mutating func insertAllRowsAndColumns() {
|
||||
rowIds = nil
|
||||
columns = nil
|
||||
}
|
||||
|
||||
mutating func insertAllRowsAndColumn(_ column: CaseInsensitiveIdentifier) {
|
||||
rowIds = nil
|
||||
if columns != nil {
|
||||
columns!.insert(column)
|
||||
}
|
||||
}
|
||||
|
||||
func contains(rowID: Int64) -> Bool {
|
||||
guard let rowIds else {
|
||||
return true
|
||||
+2
-6
@@ -59,7 +59,7 @@ extension DatabaseRegionObservation {
|
||||
/// ```swift
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
///
|
||||
/// let cancellable = observation.start(in: dbQueue) { error in
|
||||
/// let cancellable = try observation.start(in: dbQueue) { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (db: Database) in
|
||||
/// print("A modification of the player table has just been committed.")
|
||||
@@ -201,11 +201,7 @@ extension DatabasePublishers {
|
||||
self.observation = observation
|
||||
}
|
||||
|
||||
public func receive<S>(subscriber: S)
|
||||
where S: Subscriber & SendableMetatype,
|
||||
Failure == S.Failure,
|
||||
Output == S.Input
|
||||
{
|
||||
public func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = DatabaseRegionSubscription(
|
||||
writer: writer,
|
||||
observation: observation,
|
||||
File renamed without changes.
@@ -1,11 +1,11 @@
|
||||
import Dispatch
|
||||
|
||||
/// A database connection that serializes accesses to unchanging
|
||||
/// A database connection that serializes accesses to an unchanging
|
||||
/// database content, as it existed at the moment the snapshot was created.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// A `DatabaseSnapshot` never sees any database modification during its whole
|
||||
/// A `DatabaseSnapshot` never sees any database modification during all its
|
||||
/// lifetime. All database accesses performed from a snapshot always see the
|
||||
/// same identical database content.
|
||||
///
|
||||
@@ -39,7 +39,7 @@ import Dispatch
|
||||
/// snapshot from within a write access, outside of any transaction.
|
||||
///
|
||||
/// For example, compare the two snapshots below. The first one is guaranteed to
|
||||
/// see an empty table of players, because it is created after all players have
|
||||
/// see an empty table of players, because is is created after all players have
|
||||
/// been deleted, and from the serialized writer dispatch queue which prevents
|
||||
/// any concurrent write. The second is created without this concurrency
|
||||
/// protection, which means that some other threads may already have created
|
||||
@@ -48,7 +48,7 @@ import Dispatch
|
||||
/// ```swift
|
||||
/// let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll(db)
|
||||
/// try Player.deleteAll()
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
@@ -70,7 +70,7 @@ import Dispatch
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseSnapshot` inherits its database access methods from the
|
||||
/// ``DatabaseReader`` protocol.
|
||||
/// ``DatabaseReader`` protocols.
|
||||
///
|
||||
/// `DatabaseSnapshot` serializes database accesses and can't perform concurrent
|
||||
/// reads. For concurrent reads, see ``DatabaseSnapshotPool``.
|
||||
@@ -113,13 +113,8 @@ public final class DatabaseSnapshot {
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
reader.reentrantSync { db in
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
// Ignore commit error (we can not notify it), but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
assert(!db.isInsideTransaction)
|
||||
}
|
||||
}
|
||||
@@ -153,13 +148,14 @@ 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)
|
||||
}
|
||||
|
||||
public func read<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await reader.execute(value)
|
||||
}
|
||||
|
||||
@@ -169,6 +165,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)
|
||||
}
|
||||
@@ -177,9 +174,9 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
// We can't provide this as a default implementation in
|
||||
// `DatabaseSnapshotReader`, because of
|
||||
// <https://github.com/apple/swift/issues/74469>.
|
||||
public func unsafeRead<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await read(value)
|
||||
}
|
||||
|
||||
+24
-42
@@ -1,33 +1,28 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/// A database connection that allows concurrent accesses to unchanging
|
||||
/// A database connection that allows concurrent accesses to an unchanging
|
||||
/// database content, as it existed at the moment the snapshot was created.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// A `DatabaseSnapshotPool` never sees any database modification during its whole
|
||||
/// A `DatabaseSnapshotPool` never sees any database modification during all its
|
||||
/// lifetime. All database accesses performed from a snapshot always see the
|
||||
/// same identical database content.
|
||||
///
|
||||
/// It creates a pool of up to ``Configuration/maximumReaderCount`` read-only
|
||||
/// SQLite connections. All read accesses are executed in **reader dispatch
|
||||
/// queues** (one per read-only SQLite connection). SQLite connections are
|
||||
/// closed when the `DatabaseSnapshotPool` is deallocated.
|
||||
/// closed when the `DatabasePool` is deallocated.
|
||||
///
|
||||
/// An SQLite database in the [WAL mode](https://www.sqlite.org/wal.html) is
|
||||
/// required for creating a `DatabaseSnapshotPool`.
|
||||
@@ -59,7 +54,7 @@ import SQLite3
|
||||
/// }
|
||||
///
|
||||
/// // Start observing the 'player' table
|
||||
/// let cancellable = observation.start(in: dbPool) { error in
|
||||
/// let cancellable = try observation.start(in: dbPool) { error in
|
||||
/// // Handle error
|
||||
/// } onChange: { (snapshot: DatabaseSnapshotPool) in
|
||||
/// // Handle a fresh snapshot
|
||||
@@ -67,7 +62,7 @@ import SQLite3
|
||||
/// ```
|
||||
///
|
||||
/// `DatabaseSnapshotPool` inherits its database access methods from the
|
||||
/// ``DatabaseReader`` protocol.
|
||||
/// ``DatabaseReader`` protocols.
|
||||
///
|
||||
/// Related SQLite documentation:
|
||||
///
|
||||
@@ -107,12 +102,12 @@ public final class DatabaseSnapshotPool {
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// let snapshot = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshotPool in
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll(db)
|
||||
/// try Player.deleteAll()
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// // Create the snapshot after all players have been deleted.
|
||||
/// return try DatabaseSnapshotPool(db)
|
||||
/// return DatabaseSnapshotPool(db)
|
||||
/// }
|
||||
///
|
||||
/// // Later... Maybe some players have been created.
|
||||
@@ -142,7 +137,7 @@ public final class DatabaseSnapshotPool {
|
||||
let walSnapshot = try db.isolated(readOnly: true) {
|
||||
try WALSnapshot(db)
|
||||
}
|
||||
var holderConfig = configuration
|
||||
var holderConfig = Configuration()
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
|
||||
try snapshotHolder.inDatabase { db in
|
||||
@@ -201,7 +196,7 @@ public final class DatabaseSnapshotPool {
|
||||
var configuration = Self.configure(configuration)
|
||||
|
||||
// Acquire and hold WAL snapshot
|
||||
var holderConfig = configuration
|
||||
var holderConfig = Configuration()
|
||||
holderConfig.allowsUnsafeTransactions = true
|
||||
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
|
||||
let walSnapshot = try snapshotHolder.inDatabase { db in
|
||||
@@ -274,6 +269,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 {
|
||||
@@ -297,9 +293,9 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
}
|
||||
}
|
||||
|
||||
public func read<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
@@ -311,22 +307,12 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
releaseReader(readerCompletion ?? .reuse)
|
||||
}
|
||||
let (result, completion) = try await reader.execute { db in
|
||||
let result: Result<T, any Error>
|
||||
do {
|
||||
result = try .success(value(db))
|
||||
} catch {
|
||||
result = .failure(error)
|
||||
}
|
||||
let result = Result { try value(db) }
|
||||
let completion = poolCompletion(db)
|
||||
return (result, completion)
|
||||
}
|
||||
readerCompletion = completion
|
||||
switch result {
|
||||
case let .success(output):
|
||||
return output
|
||||
case let .failure(error):
|
||||
throw error
|
||||
}
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
public func asyncRead(
|
||||
@@ -355,9 +341,9 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
// We can't provide this as a default implementation in
|
||||
// `DatabaseSnapshotReader`, because of
|
||||
// <https://github.com/apple/swift/issues/74469>.
|
||||
public func unsafeRead<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await read(value)
|
||||
}
|
||||
|
||||
@@ -387,10 +373,6 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
if SchedulingWatchdog.current == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let readerPool else {
|
||||
return nil
|
||||
}
|
||||
@@ -1,15 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -18,7 +13,7 @@ import Foundation
|
||||
///
|
||||
/// To get `DatabaseValue` instances, you can:
|
||||
///
|
||||
/// - Fetch `DatabaseValue` from a ``Database`` instance:
|
||||
/// - Fetch `DatabaseValue` from a ``Database`` instace:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
@@ -123,7 +118,7 @@ public struct DatabaseValue: Hashable {
|
||||
|
||||
// MARK: - Extracting Value
|
||||
|
||||
/// A boolean value indicating if the database value is `NULL`.
|
||||
/// A boolean value indicating is the database value is `NULL`.
|
||||
public var isNull: Bool {
|
||||
switch storage {
|
||||
case .null:
|
||||
@@ -149,10 +144,7 @@ public struct DatabaseValue: Hashable {
|
||||
case SQLITE_FLOAT:
|
||||
storage = .double(sqlite3_value_double(sqliteValue))
|
||||
case SQLITE_TEXT:
|
||||
let text = sqlite3_value_text(sqliteValue)
|
||||
let byteCount = Int(sqlite3_value_bytes(sqliteValue))
|
||||
let string = String(decoding: UnsafeBufferPointer(start: text, count: byteCount), as: UTF8.self)
|
||||
storage = .string(string)
|
||||
storage = .string(String(cString: sqlite3_value_text(sqliteValue)!))
|
||||
case SQLITE_BLOB:
|
||||
if let bytes = sqlite3_value_blob(sqliteValue) {
|
||||
let count = Int(sqlite3_value_bytes(sqliteValue))
|
||||
@@ -176,8 +168,7 @@ public struct DatabaseValue: Hashable {
|
||||
case SQLITE_FLOAT:
|
||||
storage = .double(sqlite3_column_double(sqliteStatement, index))
|
||||
case SQLITE_TEXT:
|
||||
let string = String(sqliteStatement: sqliteStatement, index: index)
|
||||
storage = .string(string)
|
||||
storage = .string(String(cString: sqlite3_column_text(sqliteStatement, index)))
|
||||
case SQLITE_BLOB:
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
@@ -229,7 +220,7 @@ extension DatabaseValue: StatementBinding {
|
||||
let code = double.bind(to: sqliteStatement, at: index)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
case .string(var string):
|
||||
case .string(let string):
|
||||
return try string.withBinding(to: sqliteStatement, at: index, do: body)
|
||||
case .blob(let data):
|
||||
return try data.withBinding(to: sqliteStatement, at: index, do: body)
|
||||
@@ -239,7 +230,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
|
||||
|
||||
@@ -262,7 +254,7 @@ extension DatabaseValue.Storage: Equatable {
|
||||
}
|
||||
|
||||
extension DatabaseValue: Equatable {
|
||||
/// Returns whether two ``DatabaseValue`` instances are equal.
|
||||
/// Returns whether two ``DatabaseValue`` are equal.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -271,7 +263,7 @@ extension DatabaseValue: Equatable {
|
||||
/// 1.databaseValue == 1.databaseValue // true
|
||||
/// ```
|
||||
///
|
||||
/// When comparing integers and doubles, the result is true if and only if
|
||||
/// When comparing integers and doubles, the result is true if and only
|
||||
/// values are equal, and if converting one type to the other does
|
||||
/// not lose information:
|
||||
///
|
||||
@@ -279,7 +271,7 @@ extension DatabaseValue: Equatable {
|
||||
/// 1.databaseValue == 1.0.databaseValue // true
|
||||
/// ```
|
||||
///
|
||||
/// For a comparison that distinguishes integers and doubles, compare
|
||||
/// For a comparison that distinguishes integer and doubles, compare
|
||||
/// storages instead:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -367,7 +359,7 @@ extension DatabaseValue: CustomStringConvertible {
|
||||
/// This comparison is not public because it does not handle text collations,
|
||||
/// and may be dangerous when put in user hands.
|
||||
///
|
||||
/// So far, the only goal of this sorting method is aesthetic, and
|
||||
/// So far, the only goal of this sorting method so far is aesthetic, and
|
||||
/// easier testing.
|
||||
func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
|
||||
switch (lhs.storage, rhs.storage) {
|
||||
+5
-5
@@ -64,13 +64,13 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
|
||||
|
||||
/// Returns the `JSONDecoder` that decodes the value.
|
||||
///
|
||||
/// This method is intended for ``DatabaseValueConvertible`` types that
|
||||
/// This method is dedicated to ``DatabaseValueConvertible`` types that
|
||||
/// also conform to the standard `Decodable` protocol.
|
||||
static func databaseJSONDecoder() -> JSONDecoder
|
||||
|
||||
/// Returns the `JSONEncoder` that encodes the value.
|
||||
///
|
||||
/// This method is intended for ``DatabaseValueConvertible`` types that
|
||||
/// This method is dedicated to ``DatabaseValueConvertible`` types that
|
||||
/// also conform to the standard `Encodable` protocol.
|
||||
static func databaseJSONEncoder() -> JSONEncoder
|
||||
}
|
||||
@@ -184,7 +184,7 @@ extension DatabaseValueConvertible {
|
||||
/// let names: DatabaseValueCursor<String> = try String.fetchCursor(db, sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// while let name = try names.next() { // String
|
||||
/// while let name = names.next() { // String
|
||||
/// print(name)
|
||||
/// }
|
||||
/// }
|
||||
@@ -227,7 +227,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
@available(*, unavailable)
|
||||
extension DatabaseValueCursor: Sendable { }
|
||||
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow you to fetch
|
||||
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
|
||||
/// cursors, arrays, or single values:
|
||||
///
|
||||
/// try String.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String
|
||||
@@ -237,7 +237,7 @@ extension DatabaseValueCursor: Sendable { }
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String?
|
||||
/// try String.fetchOne(statement, arguments:...) // String
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension DatabaseValueConvertible {
|
||||
@@ -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
|
||||
@@ -128,9 +129,9 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// - throws: Any ``DatabaseError`` that happens while establishing the
|
||||
/// database access, or the error thrown by `updates`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func writeWithoutTransaction<T>(
|
||||
_ updates: sending (Database) throws -> sending T
|
||||
) async throws -> sending T
|
||||
func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
@@ -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
|
||||
@@ -210,9 +212,9 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// - throws: Any ``DatabaseError`` that happens while establishing the
|
||||
/// database access, or the error thrown by `updates`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func barrierWriteWithoutTransaction<T>(
|
||||
_ updates: sending (Database) throws -> sending T
|
||||
) async throws -> sending T
|
||||
func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
///
|
||||
@@ -334,7 +336,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// any transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// Database operations performed by the `value` closure are isolated in a
|
||||
/// transaction: they do not see changes performed by concurrent
|
||||
/// transaction: they do not see changes performed by eventual concurrent
|
||||
/// writes (even writes performed by other processes).
|
||||
///
|
||||
/// They see the database in the state left by the last updates performed
|
||||
@@ -346,10 +348,10 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// ```swift
|
||||
/// try writer.writeWithoutTransaction { db in
|
||||
/// // Delete all players
|
||||
/// try Player.deleteAll(db)
|
||||
/// try Player.deleteAll()
|
||||
///
|
||||
/// // Count players concurrently
|
||||
/// writer.spawnConcurrentRead { dbResult in
|
||||
/// writer.spawnConcurrentRead { db in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Guaranteed to be zero
|
||||
@@ -390,9 +392,9 @@ extension DatabaseWriter {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are wrapped in a transaction. If they throw an
|
||||
/// error, the transaction is rolled back and the error is rethrown.
|
||||
/// error, the transaction is rollbacked and the error is rethrown.
|
||||
///
|
||||
/// Concurrent database accesses cannot see partial database updates (even
|
||||
/// Concurrent database accesses can not see partial database updates (even
|
||||
/// when performed by other processes).
|
||||
///
|
||||
/// Database operations run in the writer dispatch queue, serialized
|
||||
@@ -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?
|
||||
@@ -435,18 +438,17 @@ extension DatabaseWriter {
|
||||
/// // Handle success
|
||||
/// case let .failure(error):
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Database operations run by the `updates` closure are wrapped in
|
||||
/// a transaction. If they throw an error, the transaction is rolled back.
|
||||
/// a transaction. If they throw an error, the transaction is rollbacked.
|
||||
///
|
||||
/// The `completion` closure has two arguments: a database connection, and
|
||||
/// the result of the transaction. This result is a failure if the
|
||||
/// transaction could not be committed or if `updates` has thrown an error.
|
||||
///
|
||||
/// Concurrent database accesses cannot see partial database updates
|
||||
/// Concurrent database accesses can not see partial database updates
|
||||
/// performed by `updates` (even when performed by other processes).
|
||||
///
|
||||
/// Database operations run in the writer dispatch queue, serialized
|
||||
@@ -524,6 +526,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 +537,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 || GRDBCIPHER
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
@@ -547,11 +562,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
|
||||
|
||||
@@ -592,9 +623,9 @@ extension DatabaseWriter {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are wrapped in a transaction. If they throw an
|
||||
/// error, the transaction is rolled back and the error is rethrown.
|
||||
/// error, the transaction is rollbacked and the error is rethrown.
|
||||
///
|
||||
/// Concurrent database accesses cannot see partial database updates (even
|
||||
/// Concurrent database accesses can not see partial database updates (even
|
||||
/// when performed by other processes).
|
||||
///
|
||||
/// Database operations run in the writer dispatch queue, serialized
|
||||
@@ -608,16 +639,16 @@ extension DatabaseWriter {
|
||||
/// - throws: Any ``DatabaseError`` that happens while establishing the
|
||||
/// database access, or the error thrown by `updates`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
public func write<T>(
|
||||
_ updates: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func write<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writeWithoutTransaction { db in
|
||||
var result = Disconnected<T?>(nil)
|
||||
var result: T?
|
||||
try db.inTransaction {
|
||||
try result.exchange(newValue: updates(db))
|
||||
result = try updates(db)
|
||||
return .commit
|
||||
}
|
||||
return result.consume()!
|
||||
return result!
|
||||
}
|
||||
}
|
||||
|
||||
@@ -634,6 +665,7 @@ extension DatabaseWriter {
|
||||
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
@@ -648,6 +680,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)
|
||||
@@ -670,10 +715,10 @@ extension DatabaseWriter {
|
||||
/// ```
|
||||
///
|
||||
/// Database operations are wrapped in a transaction. If they throw an
|
||||
/// error, the transaction is rolled back and the error completes
|
||||
/// error, the transaction is rollbacked and the error completes
|
||||
/// the publisher.
|
||||
///
|
||||
/// Concurrent database accesses cannot see partial database updates (even
|
||||
/// Concurrent database accesses can not see partial database updates (even
|
||||
/// when performed by other processes).
|
||||
///
|
||||
/// Database operations are asynchronously dispatched in the writer dispatch
|
||||
@@ -731,7 +776,7 @@ extension DatabaseWriter {
|
||||
/// The difference is that the last fetches are performed in the `thenRead`
|
||||
/// closure. This closure accepts two arguments: a read-only database
|
||||
/// connection, and the result of the `updates` function. This allows you to
|
||||
/// pass information from one function to the other (it is ignored in the
|
||||
/// pass information from a function to the other (it is ignored in the
|
||||
/// sample code above).
|
||||
///
|
||||
/// When you use a ``DatabasePool``, this method applies a scheduling
|
||||
@@ -810,7 +855,7 @@ extension Publisher where Failure == Error {
|
||||
public final class AnyDatabaseWriter {
|
||||
private let base: any DatabaseWriter
|
||||
|
||||
/// Creates a new database writer that wraps and forwards operations
|
||||
/// Creates a new database reader that wraps and forwards operations
|
||||
/// to `base`.
|
||||
public init(_ base: any DatabaseWriter) {
|
||||
self.base = base
|
||||
@@ -834,13 +879,14 @@ 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)
|
||||
}
|
||||
|
||||
public func read<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.read(value)
|
||||
}
|
||||
|
||||
@@ -850,13 +896,14 @@ 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)
|
||||
}
|
||||
|
||||
public func unsafeRead<T>(
|
||||
_ value: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.unsafeRead(value)
|
||||
}
|
||||
|
||||
@@ -883,23 +930,25 @@ 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)
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T>(
|
||||
_ updates: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
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)
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T>(
|
||||
_ updates: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
#if os(Linux)
|
||||
@preconcurrency import Dispatch
|
||||
#else
|
||||
import Dispatch
|
||||
#endif
|
||||
|
||||
/// An actor that runs in a DispatchQueue.
|
||||
///
|
||||
@@ -19,24 +15,9 @@ actor DispatchQueueActor {
|
||||
executor.asUnownedSerialExecutor()
|
||||
}
|
||||
|
||||
func execute<T>(_ work: () throws -> sending T) rethrows -> sending T {
|
||||
func execute<T>(_ work: () throws -> T) rethrows -> T {
|
||||
try work()
|
||||
}
|
||||
|
||||
/// Executes `work`, and calls `onCancel` if the current task is
|
||||
/// cancelled during its execution.
|
||||
func execute<T>(
|
||||
_ work: () throws -> sending T,
|
||||
onCancel: sending () -> Void
|
||||
) async rethrows -> sending T {
|
||||
var result = Disconnected<T?>(nil)
|
||||
try await withTaskCancellationHandler {
|
||||
_ = try result.exchange(newValue: work())
|
||||
} onCancel: {
|
||||
onCancel()
|
||||
}
|
||||
return result.consume()!
|
||||
}
|
||||
}
|
||||
|
||||
private final class DispatchQueueExecutor: SerialExecutor {
|
||||
@@ -62,7 +43,3 @@ private final class DispatchQueueExecutor: SerialExecutor {
|
||||
dispatchPrecondition(condition: .onQueue(queue))
|
||||
}
|
||||
}
|
||||
|
||||
#if os(Linux) || os(Android) || os(Windows)
|
||||
extension DispatchQueueExecutor: @unchecked Sendable {}
|
||||
#endif
|
||||
@@ -97,7 +97,7 @@ public protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvert
|
||||
}
|
||||
|
||||
extension FetchRequest {
|
||||
/// Returns the database region that the request looks into.
|
||||
/// Returns the database region that the request feeds from.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
@@ -134,7 +134,7 @@ public struct PreparedRequest {
|
||||
/// A prepared statement with bound parameters.
|
||||
public var statement: Statement
|
||||
|
||||
/// An optional adapter for rows fetched by the select statement.
|
||||
/// An eventual adapter for rows fetched by the select statement.
|
||||
public var adapter: (any RowAdapter)?
|
||||
|
||||
/// A closure that performs supplementary fetches.
|
||||
@@ -166,7 +166,7 @@ extension FetchRequest {
|
||||
///
|
||||
/// The returned request performs an identical database query, but adapts
|
||||
/// the fetched rows. See ``RowAdapter``, and
|
||||
/// ``splittingRowAdapters(columnCounts:)`` for sample code that uses
|
||||
/// ``splittingRowAdapters(columnCounts:)`` for a sample code that uses
|
||||
/// `adapted(_:)`.
|
||||
///
|
||||
/// - parameter adapter: A closure that accepts a database connection and
|
||||
@@ -1,15 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -43,7 +38,7 @@ import Foundation
|
||||
///
|
||||
/// - ``copy()``
|
||||
///
|
||||
/// ### Row Information
|
||||
/// ### Row Informations
|
||||
///
|
||||
/// - ``columnNames``
|
||||
/// - ``containsNonNullValue``
|
||||
@@ -60,6 +55,7 @@ import Foundation
|
||||
/// - ``decode(_:atIndex:)-33ykh``
|
||||
/// - ``decode(_:atIndex:)-3btwn``
|
||||
/// - ``withUnsafeData(atIndex:_:)``
|
||||
/// - ``dataNoCopy(atIndex:)``
|
||||
///
|
||||
/// ### Accessing Row Values by Column Name
|
||||
///
|
||||
@@ -70,6 +66,7 @@ import Foundation
|
||||
/// - ``decode(_:forColumn:)-4i1o4``
|
||||
/// - ``decode(_:forColumn:)-4rhs4``
|
||||
/// - ``withUnsafeData(named:_:)``
|
||||
/// - ``dataNoCopy(named:)``
|
||||
///
|
||||
/// ### Accessing Row Values by Column
|
||||
///
|
||||
@@ -80,6 +77,7 @@ import Foundation
|
||||
/// - ``decode(_:forColumn:)-1ljuo``
|
||||
/// - ``decode(_:forColumn:)-47qeg``
|
||||
/// - ``withUnsafeData(at:_:)``
|
||||
/// - ``dataNoCopy(_:)``
|
||||
///
|
||||
/// ### Row Scopes & Associated Rows
|
||||
///
|
||||
@@ -153,20 +151,7 @@ public final class Row {
|
||||
let sqliteStatement: SQLiteStatement?
|
||||
|
||||
/// The number of columns in the row.
|
||||
@inlinable
|
||||
public var count: Int {
|
||||
// Rows that map an SQLite statement don't cache the number of
|
||||
// columns, because SQLite may recompile the statement after a
|
||||
// schema change, with a different number of columns.
|
||||
if let sqliteStatement {
|
||||
return Int(sqlite3_column_count(sqliteStatement))
|
||||
}
|
||||
return cachedCount
|
||||
}
|
||||
|
||||
/// The number of columns, when the row does not map an SQLite statement.
|
||||
@usableFromInline
|
||||
let cachedCount: Int
|
||||
public let count: Int
|
||||
|
||||
/// A view on the prefetched associated rows.
|
||||
///
|
||||
@@ -250,7 +235,7 @@ public final class Row {
|
||||
self.statement = statement
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement)
|
||||
self.cachedCount = 0 // Unused because sqliteStatement is not nil: see `count`
|
||||
self.count = Int(sqlite3_column_count(sqliteStatement))
|
||||
}
|
||||
|
||||
/// Creates a row that maps an SQLite statement. Further calls to
|
||||
@@ -259,10 +244,10 @@ public final class Row {
|
||||
self.statement = nil
|
||||
self.sqliteStatement = sqliteStatement
|
||||
self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement)
|
||||
self.cachedCount = 0 // Unused because sqliteStatement is not nil: see `count`
|
||||
self.count = Int(sqlite3_column_count(sqliteStatement))
|
||||
}
|
||||
|
||||
/// Creates a row that contains a copy of the current state of the
|
||||
/// Creates a row that contain a copy of the current state of the
|
||||
/// SQLite statement. Further calls to sqlite3_step() do not modify the row.
|
||||
///
|
||||
/// The row is implemented on top of StatementCopyRowImpl, which *copies*
|
||||
@@ -281,7 +266,7 @@ public final class Row {
|
||||
self.statement = nil
|
||||
self.sqliteStatement = nil
|
||||
self.impl = impl
|
||||
self.cachedCount = impl.count
|
||||
self.count = impl.count
|
||||
}
|
||||
}
|
||||
|
||||
@@ -320,13 +305,13 @@ 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)
|
||||
}
|
||||
|
||||
/// Returns a boolean value indicating if the row contains one value that
|
||||
/// Returns a boolean value indicating if the row contains one value this
|
||||
/// is not `NULL`.
|
||||
///
|
||||
/// For example:
|
||||
@@ -424,7 +409,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)
|
||||
@@ -626,7 +611,7 @@ extension Row {
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain any column with that name, or if the SQLite
|
||||
/// value is `NULL`, the data is nil. If the SQLite value cannot be
|
||||
/// value is `NULL`, the data is nil. If the SQLite value can not be
|
||||
/// converted to `Data`, an error is thrown.
|
||||
///
|
||||
/// - warning: The `Data` argument to the body must not be stored or used
|
||||
@@ -644,7 +629,7 @@ extension Row {
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain any column with that name, or if the SQLite
|
||||
/// value is `NULL`, the data is nil. If the SQLite value cannot be
|
||||
/// value is `NULL`, the data is nil. If the SQLite value can not be
|
||||
/// converted to `Data`, an error is thrown.
|
||||
///
|
||||
/// - warning: The `Data` argument to the body must not be stored or used
|
||||
@@ -653,6 +638,56 @@ extension Row {
|
||||
try withUnsafeData(named: column.name, body)
|
||||
}
|
||||
|
||||
/// Returns the optional `Data` at given index.
|
||||
///
|
||||
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
|
||||
/// rightmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, the result is nil. If the SQLite value can
|
||||
/// not be converted to Data, a fatal error is raised.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
@available(*, deprecated, message: "Use withUnsafeData(atIndex:_:) instead.")
|
||||
public func dataNoCopy(atIndex index: Int) -> Data? {
|
||||
try! withUnsafeData(atIndex: index, { $0 })
|
||||
}
|
||||
|
||||
/// Returns the optional `Data` at given column.
|
||||
///
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. If the SQLite value can not be converted to Data, a fatal error
|
||||
/// is raised.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
@available(*, deprecated, message: "Use withUnsafeData(named:_:) instead.")
|
||||
public func dataNoCopy(named columnName: String) -> Data? {
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return try! withUnsafeData(atUncheckedIndex: index, { $0 })
|
||||
}
|
||||
|
||||
/// Returns the optional `Data` at given column.
|
||||
///
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. If the SQLite value can not be converted to Data, a fatal error
|
||||
/// is raised.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
@available(*, deprecated, message: "Use withUnsafeData(at:_:) instead.")
|
||||
public func dataNoCopy(_ column: some ColumnExpression) -> Data? {
|
||||
dataNoCopy(named: column.name)
|
||||
}
|
||||
|
||||
/// Returns the first non-null value, if any. Identical to SQL `COALESCE` function.
|
||||
///
|
||||
/// For example:
|
||||
@@ -718,7 +753,7 @@ extension Row {
|
||||
|
||||
// MARK: - Extracting Records
|
||||
|
||||
/// Returns the record associated with the given key.
|
||||
/// Returns the record associated to the given key.
|
||||
///
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
@@ -764,7 +799,7 @@ extension Row {
|
||||
try! decode(Record.self, forKey: scope)
|
||||
}
|
||||
|
||||
/// Returns the record associated with the given key, if any.
|
||||
/// Returns the eventual record associated to the given key.
|
||||
///
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
@@ -791,7 +826,7 @@ extension Row {
|
||||
///
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// // Fetch a book, with its optional author, and the country of its author.
|
||||
/// // Fetch a book, with its eventual author, and the country of its author.
|
||||
/// let request = Book
|
||||
/// .including(optional: Book.author
|
||||
/// .including(optional: Author.country))
|
||||
@@ -810,7 +845,7 @@ extension Row {
|
||||
try! decodeIfPresent(Record.self, forKey: scope)
|
||||
}
|
||||
|
||||
/// Returns a collection of prefetched records associated with the given
|
||||
/// Returns a collection of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
@@ -844,7 +879,7 @@ extension Row {
|
||||
try! decode(Records.self, forKey: key)
|
||||
}
|
||||
|
||||
/// Returns the set of prefetched records associated with the given
|
||||
/// Returns the set of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
@@ -880,7 +915,7 @@ extension Row {
|
||||
|
||||
/// A view on the scopes defined by row adapters.
|
||||
///
|
||||
/// The returned object provides access to all available scopes in
|
||||
/// The returned object provides an access to all available scopes in
|
||||
/// the row.
|
||||
///
|
||||
/// Row scopes can be defined manually, with ``ScopeAdapter``.
|
||||
@@ -927,7 +962,7 @@ extension Row {
|
||||
|
||||
/// A view on the scopes tree defined by row adapters.
|
||||
///
|
||||
/// The returned object provides access to all available scopes in
|
||||
/// The returned object provides an access to all available scopes in
|
||||
/// the row, recursively. For any given scope identifier, a breadth-first
|
||||
/// search is performed.
|
||||
///
|
||||
@@ -970,7 +1005,7 @@ extension Row {
|
||||
ScopesTreeView(scopes: scopes)
|
||||
}
|
||||
|
||||
/// The row, without any scope or prefetched rows.
|
||||
/// The row, without any scope of prefetched rows.
|
||||
///
|
||||
/// This property is useful when testing the content of rows fetched from
|
||||
/// joined requests.
|
||||
@@ -1202,7 +1237,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,
|
||||
@@ -1342,7 +1377,7 @@ extension Row {
|
||||
// MARK: - Throwing Record Decoding Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the record associated with the given key, if any.
|
||||
/// Returns the eventual record associated to the given key.
|
||||
///
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
@@ -1369,7 +1404,7 @@ extension Row {
|
||||
///
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// // Fetch a book, with its optional author, and the country of its author.
|
||||
/// // Fetch a book, with its eventual author, and the country of its author.
|
||||
/// let request = Book
|
||||
/// .including(optional: Book.author
|
||||
/// .including(optional: Author.country))
|
||||
@@ -1397,7 +1432,7 @@ extension Row {
|
||||
return try Record(row: scopedRow)
|
||||
}
|
||||
|
||||
/// Returns the record associated with the given key.
|
||||
/// Returns the record associated to the given key.
|
||||
///
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
@@ -1480,7 +1515,7 @@ extension Row {
|
||||
// MARK: - Throwing Record RangeReplaceableCollection and Set Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns a collection of prefetched records associated with the given
|
||||
/// Returns a collection of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
@@ -1546,7 +1581,7 @@ extension Row {
|
||||
return collection
|
||||
}
|
||||
|
||||
/// Returns the set of prefetched records associated with the given
|
||||
/// Returns the set of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
@@ -2344,7 +2379,7 @@ extension Row: CustomDebugStringConvertible {
|
||||
|
||||
extension Row: ExpressibleByDictionaryLiteral {
|
||||
/// Creates a row initialized with elements. Column order is preserved, and
|
||||
/// duplicated column names are allowed.
|
||||
/// duplicated columns names are allowed.
|
||||
///
|
||||
/// let row: Row = ["foo": 1, "foo": "bar", "baz": nil]
|
||||
/// print(row)
|
||||
@@ -2356,6 +2391,9 @@ extension Row: ExpressibleByDictionaryLiteral {
|
||||
|
||||
// MARK: - Index
|
||||
|
||||
@available(*, deprecated, renamed: "Row.Index")
|
||||
typealias RowIndex = Row.Index
|
||||
|
||||
extension Row {
|
||||
/// An index to a (column, value) pair in a ``Row``.
|
||||
public struct Index: Sendable {
|
||||
@@ -2513,7 +2551,7 @@ extension Row {
|
||||
// (we preserve the ordering of associations in the request)
|
||||
fileprivate var prefetches: OrderedDictionary<String, Prefetch> = [:]
|
||||
|
||||
/// A boolean value indicating if there are no prefetched
|
||||
/// A boolean value indicating if there is no prefetched
|
||||
/// associated rows.
|
||||
public var isEmpty: Bool {
|
||||
prefetches.isEmpty
|
||||
@@ -2671,7 +2709,7 @@ extension RowImpl {
|
||||
}
|
||||
|
||||
// TODO: merge with StatementCopyRowImpl eventually?
|
||||
/// See Row.init(_:)
|
||||
/// See Row.init(dictionary:)
|
||||
struct ArrayRowImpl: RowImpl {
|
||||
let columns: [(String, DatabaseValue)]
|
||||
|
||||
@@ -2704,7 +2742,7 @@ struct ArrayRowImpl: RowImpl {
|
||||
extension ArrayRowImpl: Sendable { }
|
||||
|
||||
// TODO: merge with ArrayRowImpl eventually?
|
||||
/// See Row.init(copiedFromSQLiteStatement:statement:)
|
||||
/// See Row.init(copiedFromStatementRef:sqliteStatement:)
|
||||
private struct StatementCopyRowImpl: RowImpl {
|
||||
let dbValues: ContiguousArray<DatabaseValue>
|
||||
let columnNames: [String]
|
||||
@@ -2744,10 +2782,19 @@ private struct StatementCopyRowImpl: RowImpl {
|
||||
private struct StatementRowImpl: RowImpl {
|
||||
let statement: Statement
|
||||
let sqliteStatement: SQLiteStatement
|
||||
let lowercaseColumnIndexes: [String: Int]
|
||||
|
||||
init(sqliteStatement: SQLiteStatement, statement: Statement) {
|
||||
self.statement = statement
|
||||
self.sqliteStatement = sqliteStatement
|
||||
// Optimize row[columnName]
|
||||
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement))
|
||||
.map { String(cString: sqlite3_column_name(sqliteStatement, CInt($0))).lowercased() }
|
||||
self.lowercaseColumnIndexes = Dictionary(
|
||||
lowercaseColumnNames
|
||||
.enumerated()
|
||||
.map { ($0.element, $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}
|
||||
|
||||
var count: Int {
|
||||
@@ -2794,7 +2841,6 @@ private struct StatementRowImpl: RowImpl {
|
||||
}
|
||||
|
||||
func index(forColumn name: String) -> Int? {
|
||||
let lowercaseColumnIndexes = statement.columnIndexes
|
||||
if let index = lowercaseColumnIndexes[name] {
|
||||
return index
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import Foundation
|
||||
/// """
|
||||
/// ```
|
||||
///
|
||||
/// The resulting rows contain columns from both player and team tables:
|
||||
/// The resulting rows contains columns from both player and team tables:
|
||||
///
|
||||
/// ```swift
|
||||
/// // [id: 1, name: "Arthur", teamId: 42, id: 42, name: "Reds"]
|
||||
@@ -32,7 +32,7 @@ import Foundation
|
||||
/// access player and team columns independently, with row ``Row/scopes``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let adapters = try splittingRowAdapters(columnCounts: [
|
||||
/// let adapters = try splittingRowAdapters([
|
||||
/// db.columns(in: "player").count,
|
||||
/// db.columns(in: "team").count,
|
||||
/// ])
|
||||
@@ -60,12 +60,12 @@ import Foundation
|
||||
///
|
||||
/// // Team(id: 42, name: "Reds")
|
||||
/// // nil if the LEFT JOIN has fetched NULL team columns
|
||||
/// let team: Team? = row["team"]
|
||||
/// if let team: Team? = row["team"]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can package this technique in a dedicated type, as in the next
|
||||
/// example. It enhances the previous code samples with:
|
||||
/// example. It enhances the previous sample codes with:
|
||||
///
|
||||
/// - Support for record types that customize their fetched columns
|
||||
/// with ``TableRecord/databaseSelection-7iphs``.
|
||||
@@ -96,7 +96,7 @@ import Foundation
|
||||
/// let request: SQLRequest<PlayerInfo> = """
|
||||
/// SELECT
|
||||
/// \(columnsOf: Player.self), -- Instead of player.*
|
||||
/// \(columnsOf: Team.self) -- Instead of team.*
|
||||
/// \(columnsOf: Team.self), -- Instead of team.*
|
||||
/// FROM player
|
||||
/// LEFT JOIN team ON team.id = player.teamId
|
||||
/// WHERE player.id = \(playerId)
|
||||
@@ -159,7 +159,7 @@ public struct _LayoutedColumnMapping {
|
||||
/// that column.
|
||||
public let _layoutColumns: [(Int, String)]
|
||||
|
||||
/// A cache for _layoutIndex(ofColumn:)
|
||||
/// A cache for layoutIndex(ofColumn:)
|
||||
let lowercaseColumnIndexes: [String: Int] // [mappedColumn: layoutColumnIndex]
|
||||
|
||||
/// Creates a _LayoutedColumnMapping from an array of (baseIndex, mappedName)
|
||||
@@ -176,7 +176,7 @@ public struct _LayoutedColumnMapping {
|
||||
/// Use it in your custom RowAdapter type:
|
||||
///
|
||||
/// struct FooBarAdapter : RowAdapter {
|
||||
/// func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
/// func layoutAdapter(layout: _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
/// return _LayoutedColumnMapping(layoutColumns: [(1, "foo"), (2, "bar")])
|
||||
/// }
|
||||
/// }
|
||||
@@ -222,7 +222,7 @@ extension _LayoutedColumnMapping: _RowLayout {
|
||||
|
||||
/// `_LayoutedRowAdapter` is a protocol that supports the `RowAdapter` protocol.
|
||||
///
|
||||
/// GRDB ships with a ready-made type that adopts this protocol:
|
||||
/// GRBD ships with a ready-made type that adopts this protocol:
|
||||
/// `_LayoutedColumnMapping`.
|
||||
public protocol _LayoutedRowAdapter {
|
||||
/// A LayoutedColumnMapping that defines how to map a column name to a
|
||||
@@ -255,7 +255,7 @@ extension Statement: _RowLayout {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type that helps two incompatible row interfaces work together.
|
||||
/// A type that helps two incompatible row interfaces working together.
|
||||
///
|
||||
/// Row adapters present database rows in the way expected by the
|
||||
/// row consumers.
|
||||
@@ -343,7 +343,7 @@ extension RowAdapter {
|
||||
/// Returns an adapter based on self, with added scopes.
|
||||
///
|
||||
/// If self already defines scopes, the added scopes replace
|
||||
/// any existing scopes with the same name.
|
||||
/// eventual existing scopes with the same name.
|
||||
///
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
@@ -495,7 +495,7 @@ public struct RangeRowAdapter: RowAdapter, Sendable {
|
||||
/// `ScopeAdapter` is a row adapter that defines row scopes.
|
||||
///
|
||||
/// `ScopeAdapter` does not change the columns and values of the fetched
|
||||
/// row. Instead, it defines *scopes* based on other adapters, which you
|
||||
/// row. Instead, it defines *scopes* based on other adapter, which you
|
||||
/// access through the ``Row/scopes`` property of the fetched rows.
|
||||
///
|
||||
/// For example:
|
||||
@@ -559,7 +559,7 @@ public struct ScopeAdapter: RowAdapter {
|
||||
/// The scope adapters
|
||||
let scopes: [String: any RowAdapter]
|
||||
|
||||
/// Creates an adapter that preserves row contents and adds scoped rows.
|
||||
/// Creates an adapter that preserves row contents and add scoped rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -575,7 +575,7 @@ public struct ScopeAdapter: RowAdapter {
|
||||
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
|
||||
}
|
||||
|
||||
/// Creates an adapter based on the base adapter, and adds scoped rows.
|
||||
/// Creates an adapter based on the base adapter, and add scoped rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -583,14 +583,15 @@ public struct ScopeAdapter: RowAdapter {
|
||||
/// let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)])
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: adapter)!
|
||||
/// row // [1]
|
||||
/// row.scopes["suffix"] // [2, 3]
|
||||
/// row.scopes["initial"] // [2, 3]
|
||||
///
|
||||
/// If the base adapter already defines scopes, the given scopes replace
|
||||
/// any existing scopes with the same name.
|
||||
/// eventual existing scopes with the same name.
|
||||
///
|
||||
/// This initializer is equivalent to `baseAdapter.addingScopes(scopes)`.
|
||||
///
|
||||
/// - parameter base: A row adapter.
|
||||
/// - parameter base: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(base: some RowAdapter, scopes: [String: any RowAdapter]) {
|
||||
@@ -1,15 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/// A key that is used to decode a value in a row
|
||||
@@ -63,7 +63,7 @@ public struct SQL: Sendable {
|
||||
/// .filter(date(Column("createdAt")) == "2022-08-17")
|
||||
/// .including(required: Player.team)
|
||||
enum Element {
|
||||
/// A raw SQL literal with optional arguments.
|
||||
/// A raw SQL literal with eventual arguments.
|
||||
case sql(String, StatementArguments = StatementArguments())
|
||||
|
||||
/// A subquery.
|
||||
@@ -144,7 +144,7 @@ public struct SQL: Sendable {
|
||||
}
|
||||
|
||||
/// Creates an `SQL` literal from a plain SQL string, and
|
||||
/// optional arguments.
|
||||
/// eventual arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -240,7 +240,7 @@ extension SQL {
|
||||
self += sqlLiteral
|
||||
}
|
||||
|
||||
/// Appends a plain SQL string to the receiver, and optional arguments.
|
||||
/// Appends a plain SQL string to the receiver, and eventual arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -300,7 +300,7 @@ extension SQL: SQLOrderingTerm {
|
||||
/// let request = Player.order(ordering)
|
||||
/// ```
|
||||
///
|
||||
/// An ordering term is only valid if it represents a single ordering term.
|
||||
/// An ordering term is only valid if it represent a single ordering terms.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Valid
|
||||
@@ -11,7 +11,7 @@ public struct SQLInterpolation: StringInterpolationProtocol {
|
||||
elements.append(.sql(sql))
|
||||
}
|
||||
|
||||
/// Appends a raw SQL snippet, with optional arguments.
|
||||
/// Appends a raw SQL snippet, with eventual arguments.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -45,21 +45,33 @@
|
||||
/// - ``init(sql:arguments:adapter:cached:)-3qq8t``
|
||||
/// - ``init(sql:arguments:adapter:cached:)-5ecx2``
|
||||
public struct SQLRequest<RowDecoder> {
|
||||
/// There are two statement caches: one "public" for statements generated by
|
||||
/// the user, and one "internal" for the statements generated by GRDB. Those
|
||||
/// are separated so that GRDB has no opportunity to inadvertently modify
|
||||
/// the arguments of user's cached statements.
|
||||
enum Cache {
|
||||
/// The public cache, for library user
|
||||
case `public`
|
||||
|
||||
/// The internal cache, for GRDB
|
||||
case `internal`
|
||||
}
|
||||
|
||||
/// The row adapter.
|
||||
public var adapter: (any RowAdapter)?
|
||||
|
||||
private(set) var sqlLiteral: SQL
|
||||
let cached: Bool
|
||||
let cache: Cache?
|
||||
|
||||
private init(
|
||||
literal sqlLiteral: SQL,
|
||||
adapter: (any RowAdapter)?,
|
||||
cached: Bool,
|
||||
fromCache cache: Cache?,
|
||||
type: RowDecoder.Type)
|
||||
{
|
||||
self.sqlLiteral = sqlLiteral
|
||||
self.adapter = adapter
|
||||
self.cached = cached
|
||||
self.cache = cache
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,7 +102,7 @@ extension SQLRequest {
|
||||
self.init(
|
||||
literal: SQL(sql: sql, arguments: arguments),
|
||||
adapter: adapter,
|
||||
cached: cached,
|
||||
fromCache: cached ? .public : nil,
|
||||
type: RowDecoder.self)
|
||||
}
|
||||
|
||||
@@ -115,7 +127,7 @@ extension SQLRequest {
|
||||
self.init(
|
||||
literal: sqlLiteral,
|
||||
adapter: adapter,
|
||||
cached: cached,
|
||||
fromCache: cached ? .public : nil,
|
||||
type: RowDecoder.self)
|
||||
}
|
||||
}
|
||||
@@ -144,7 +156,7 @@ extension SQLRequest<Row> {
|
||||
self.init(
|
||||
literal: SQL(sql: sql, arguments: arguments),
|
||||
adapter: adapter,
|
||||
cached: cached,
|
||||
fromCache: cached ? .public : nil,
|
||||
type: Row.self)
|
||||
}
|
||||
|
||||
@@ -169,7 +181,7 @@ extension SQLRequest<Row> {
|
||||
self.init(
|
||||
literal: sqlLiteral,
|
||||
adapter: adapter,
|
||||
cached: cached,
|
||||
fromCache: cached ? .public : nil,
|
||||
type: Row.self)
|
||||
}
|
||||
}
|
||||
@@ -190,9 +202,15 @@ extension SQLRequest: FetchRequest {
|
||||
{
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
let statement = try cached
|
||||
? db.cachedStatement(sql: sql)
|
||||
: db.makeStatement(sql: sql)
|
||||
let statement: Statement
|
||||
switch cache {
|
||||
case .none:
|
||||
statement = try db.makeStatement(sql: sql)
|
||||
case .public:
|
||||
statement = try db.cachedStatement(sql: sql)
|
||||
case .internal:
|
||||
statement = try db.internalCachedStatement(sql: sql)
|
||||
}
|
||||
try statement.setArguments(context.arguments)
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
#endif
|
||||
import Dispatch
|
||||
|
||||
/// SchedulingWatchdog makes sure that database connections are used on correct
|
||||
/// SchedulingWatchdog makes sure that databases connections are used on correct
|
||||
/// dispatch queues, and warns the user with a fatal error whenever she misuses
|
||||
/// a database connection.
|
||||
///
|
||||
@@ -12,14 +12,14 @@ import Dispatch
|
||||
/// <https://github.com/groue/GRDB.swift/issues/55>. To support this use case, a
|
||||
/// single dispatch queue can be temporarily shared by two or more connections.
|
||||
///
|
||||
/// - SchedulingWatchdog.allowDatabase(_:onQueue:) makes a dispatch queue
|
||||
/// allow one database.
|
||||
/// - SchedulingWatchdog.makeSerializedQueue(allowingDatabase:) creates a
|
||||
/// dispatch queue that allows one database.
|
||||
///
|
||||
/// It does so by registering one instance of SchedulingWatchdog as a specific
|
||||
/// of the dispatch queue, a SchedulingWatchdog that allows that database only.
|
||||
///
|
||||
/// Later on, the queue can be shared by several databases with the method
|
||||
/// inheritingAllowedDatabases(_:execute:). See SerializedDatabase.sync()
|
||||
/// inheritingAllowedDatabases(from:execute:). See SerializedDatabase.sync()
|
||||
/// for an example.
|
||||
///
|
||||
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
|
||||
@@ -77,7 +77,6 @@ final class SchedulingWatchdog: @unchecked Sendable {
|
||||
allowedDatabases.contains { $0 === db }
|
||||
}
|
||||
|
||||
/// When nil, no database is allowed in the current execution context.
|
||||
static var current: SchedulingWatchdog? {
|
||||
DispatchQueue.getSpecific(key: watchDogKey)
|
||||
}
|
||||
@@ -235,7 +235,7 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if and only if the current dispatch queue is valid.
|
||||
/// Returns true if any only if the current dispatch queue is valid.
|
||||
var onValidQueue: Bool {
|
||||
SchedulingWatchdog.current?.allows(db) ?? false
|
||||
}
|
||||
@@ -248,20 +248,22 @@ final class SerializedDatabase {
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
/// Asynchronously executes the block.
|
||||
func execute<T>(
|
||||
_ block: sending (Database) throws -> sending T
|
||||
) async throws -> sending T {
|
||||
/// Asynchrously executes the block.
|
||||
func execute<T: Sendable>(
|
||||
_ block: @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
|
||||
return try await actor.execute {
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
preconditionNoUnsafeTransactionLeft(db)
|
||||
return try await withTaskCancellationHandler {
|
||||
try await actor.execute {
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
preconditionNoUnsafeTransactionLeft(db)
|
||||
}
|
||||
cancelMutex.store(db.cancel)
|
||||
try Task.checkCancellation()
|
||||
return try block(db)
|
||||
}
|
||||
cancelMutex.store(db.cancel)
|
||||
try Task.checkCancellation()
|
||||
return try block(db)
|
||||
} onCancel: {
|
||||
cancelMutex.withLock { $0?() }
|
||||
}
|
||||
@@ -291,10 +293,10 @@ final class SerializedDatabase {
|
||||
SchedulingWatchdog.preconditionValidQueue(db, message(), file: file, line: line)
|
||||
}
|
||||
|
||||
/// Fatal error if a transaction has been left open.
|
||||
/// Fatal error if a transaction has been left opened.
|
||||
private func preconditionNoUnsafeTransactionLeft(
|
||||
_ db: Database,
|
||||
_ message: @autoclosure() -> String = "A transaction has been left open at the end of a database access",
|
||||
_ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access",
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
{
|
||||
@@ -1,15 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -26,7 +21,7 @@ extension String {
|
||||
/// SQL statements with `String.trimmedSQLStatement`.
|
||||
private static let sqlStatementSeparators = CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines)
|
||||
|
||||
/// Returns a string trimmed of SQL statement separators.
|
||||
/// Returns a string trimmed from SQL statement separators.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -49,25 +44,6 @@ public final class Statement {
|
||||
case rollbackSavepoint(String)
|
||||
}
|
||||
|
||||
/// The column names and indexes of a statement, for a given compilation
|
||||
/// of the statement.
|
||||
private struct ColumnCache {
|
||||
var reprepareCount: CInt
|
||||
var columnNames: [String]
|
||||
/// Indexes of the leftmost columns. Keys are lowercase.
|
||||
var columnIndexes: [String: Int]
|
||||
|
||||
init(sqliteStatement: SQLiteStatement, reprepareCount: CInt) {
|
||||
self.reprepareCount = reprepareCount
|
||||
self.columnNames = (0..<sqlite3_column_count(sqliteStatement)).map {
|
||||
String(cString: sqlite3_column_name(sqliteStatement, $0))
|
||||
}
|
||||
self.columnIndexes = Dictionary(
|
||||
columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw SQLite statement, suitable for the SQLite C API.
|
||||
public let sqliteStatement: SQLiteStatement
|
||||
|
||||
@@ -80,9 +56,11 @@ public final class Statement {
|
||||
}
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public var columnNames: [String] {
|
||||
columnCache.columnNames
|
||||
}
|
||||
public lazy var columnNames: [String] = {
|
||||
// swiftlint:disable:next redundant_self_in_closure
|
||||
let sqliteStatement = self.sqliteStatement
|
||||
return (0..<CInt(columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
|
||||
// The database region is reported by `sqlite3_set_authorizer`, and maybe
|
||||
// refined in `SQLQueryGenerator.makeStatement(_:)` when we have enough
|
||||
@@ -95,7 +73,7 @@ public final class Statement {
|
||||
///
|
||||
/// ```swift
|
||||
/// // Reads score, writes bonus
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// let statement = db.makeStatement(sql: """
|
||||
/// UPDATE player SET bonus = 0 WHERE score = 0
|
||||
/// """)
|
||||
///
|
||||
@@ -108,13 +86,13 @@ public final class Statement {
|
||||
/// is executed (reported by `sqlite3_set_authorizer`).
|
||||
private(set) var invalidatesDatabaseSchemaCache = false
|
||||
|
||||
/// The optional effect of transactions, as reported by `sqlite3_set_authorizer`.
|
||||
/// The eventual effect of transactions, as reported by `sqlite3_set_authorizer`.
|
||||
private(set) var transactionEffect: TransactionEffect?
|
||||
|
||||
/// The effects on the database (reported by `sqlite3_set_authorizer`).
|
||||
private(set) var authorizerEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// If true, the statement is a `PRAGMA QUERY_ONLY` statement.
|
||||
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
|
||||
private(set) var isQueryOnlyPragma = false
|
||||
|
||||
/// A boolean value indicating if the prepared statement makes no direct
|
||||
@@ -133,29 +111,12 @@ public final class Statement {
|
||||
@usableFromInline
|
||||
unowned let database: Database
|
||||
|
||||
/// Indexes of the leftmost columns. Keys are lowercase.
|
||||
var columnIndexes: [String: Int] {
|
||||
columnCache.columnIndexes
|
||||
}
|
||||
|
||||
/// Storage for `columnCache`.
|
||||
private var _columnCache: ColumnCache?
|
||||
|
||||
/// The column names and indexes.
|
||||
///
|
||||
/// SQLite recompiles statements after schema changes (see
|
||||
/// <https://www.sqlite.org/c3ref/prepare.html>), and this can change
|
||||
/// the result columns (think `SELECT *` after a column was added).
|
||||
/// So the cache is rebuilt whenever the statement is recompiled.
|
||||
private var columnCache: ColumnCache {
|
||||
let reprepareCount = sqlite3_stmt_status(sqliteStatement, SQLITE_STMTSTATUS_REPREPARE, 0)
|
||||
if let _columnCache, _columnCache.reprepareCount == reprepareCount {
|
||||
return _columnCache
|
||||
}
|
||||
let columnCache = ColumnCache(sqliteStatement: sqliteStatement, reprepareCount: reprepareCount)
|
||||
_columnCache = columnCache
|
||||
return columnCache
|
||||
}
|
||||
/// Cache for index(ofColumn:). Keys are lowercase.
|
||||
private lazy var columnIndexes: [String: Int] = {
|
||||
Dictionary(
|
||||
columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}()
|
||||
|
||||
/// Creates a prepared statement. Returns nil if the compiled string is
|
||||
/// blank or empty.
|
||||
@@ -165,8 +126,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,
|
||||
@@ -180,13 +141,16 @@ public final class Statement {
|
||||
let authorizer = database.authorizer
|
||||
authorizer.reset()
|
||||
|
||||
var sqliteStatement: SQLiteStatement?
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
let code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, prepFlags,
|
||||
&sqliteStatement, statementEnd)
|
||||
|
||||
guard code == SQLITE_OK else {
|
||||
try database.statementCompilationDidFail(at: statementStart, withResultCode: code)
|
||||
throw DatabaseError(
|
||||
resultCode: code,
|
||||
message: database.lastErrorMessage,
|
||||
sql: String(cString: statementStart))
|
||||
}
|
||||
|
||||
guard let sqliteStatement else {
|
||||
@@ -279,7 +243,7 @@ public final class Statement {
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
@@ -290,7 +254,7 @@ public final class Statement {
|
||||
/// print(statement.arguments)
|
||||
/// ```
|
||||
///
|
||||
/// It is a programmer error to set arguments that do not provide all
|
||||
/// If is a programmer error to set arguments that do not provide all
|
||||
/// values expected by the statement:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -311,23 +275,23 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
/// Throws a ``DatabaseError`` of code `SQLITE_MISUSE` if the provided
|
||||
/// Throws a ``DatabaseError`` of code `SQLITE_ERROR` if the provided
|
||||
/// arguments do not provide all values expected by the statement.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
/// // OK
|
||||
/// try statement.validateArguments([1, "Arthur"])
|
||||
/// statement.validateArguments([1, "Arthur"])
|
||||
///
|
||||
/// // Throws
|
||||
/// try statement.validateArguments([1])
|
||||
/// try statement.validateArguments([1, "Arthur", Date()])
|
||||
/// try statement.setArguments([1])
|
||||
/// try statement.setArguments([1, "Arthur", Date()])
|
||||
/// ```
|
||||
///
|
||||
/// See also ``setArguments(_:)``.
|
||||
@@ -347,7 +311,7 @@ public final class Statement {
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
@@ -390,7 +354,7 @@ public final class Statement {
|
||||
///
|
||||
/// ```swift
|
||||
/// // This statement expects two arguments
|
||||
/// let statement = try db.makeStatement(sql: """
|
||||
/// let statement = try db.makeUpdateArgument(sql: """
|
||||
/// INSERT INTO player (id, name) VALUES (?, ?)
|
||||
/// """)
|
||||
///
|
||||
@@ -467,20 +431,6 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resets the statement, and clears its arguments, so that it is in the
|
||||
/// same state as a newly prepared statement.
|
||||
///
|
||||
/// - precondition: this method is called on a valid dispatch queue.
|
||||
func prepareForReuse() {
|
||||
// Ignore the result of sqlite3_reset, which might report the error
|
||||
// of the last sqlite3_step(), if any. This should not prevent reuse.
|
||||
// <https://www.sqlite.org/c3ref/reset.html>
|
||||
sqlite3_reset(sqliteStatement)
|
||||
clearBindings()
|
||||
_arguments = StatementArguments()
|
||||
argumentsAreValidAndBound = false
|
||||
}
|
||||
|
||||
// MARK: Execution
|
||||
|
||||
func reset() throws {
|
||||
@@ -492,7 +442,7 @@ public final class Statement {
|
||||
}
|
||||
|
||||
/// Convenience method that resets, sets arguments if needed, and checks
|
||||
/// argument validity.
|
||||
/// arguments validity.
|
||||
///
|
||||
/// - parameter newArguments: if not nil, this method sets arguments.
|
||||
func prepareExecution(withArguments newArguments: StatementArguments? = nil) throws {
|
||||
@@ -563,11 +513,11 @@ public final class Statement {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When arguments are set at the moment of execution, with a non-nil
|
||||
/// When arguments are set at the moment of execution, with an non-nil
|
||||
/// `arguments` parameter, it is assumed that the statement won't be
|
||||
/// reused with the same arguments. When the number of arguments is
|
||||
/// small, execution is performed with temporary SQLite bindings that
|
||||
/// avoid copying string and blob arguments.
|
||||
/// avoid copying strings and blobs arguments.
|
||||
///
|
||||
/// For more information, see [`SQLITE_STATIC` and `SQLITE_TRANSIENT`](https://www.sqlite.org/c3ref/c_static.html).
|
||||
/// Compare:
|
||||
@@ -583,7 +533,7 @@ public final class Statement {
|
||||
/// ```
|
||||
///
|
||||
/// Both techniques have the same results, but when you care about
|
||||
/// performance, monitor your application in order to make the
|
||||
/// performances, monitor your application in order to make the
|
||||
/// best choice.
|
||||
///
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
@@ -632,7 +582,7 @@ public final class Statement {
|
||||
|
||||
/// Calls the given closure after each successful call to `sqlite3_step()`.
|
||||
///
|
||||
/// This method is slightly faster than calling `step(_:)` repeatedly, due
|
||||
/// This method is slighly faster than calling `step(_:)` repeatedly, due
|
||||
/// to the single `sqlite3_stmt_busy` check.
|
||||
@usableFromInline
|
||||
func forEachStep(_ body: (SQLiteStatement) throws -> Void) throws {
|
||||
@@ -825,7 +775,7 @@ extension DatabaseCursor {
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = try db.makeStatement(sql: "SELECT performSideEffect()")
|
||||
/// let cursor = try statement.makeCursor()
|
||||
/// let cursor = statement.makeCursor()
|
||||
/// try cursor.next()
|
||||
/// }
|
||||
/// ```
|
||||
@@ -941,13 +891,13 @@ func withBindings<T>(
|
||||
/// - `@AAAA` (e.g. `@name`): named argument
|
||||
/// - `$AAAA` (e.g. `$name`): named argument
|
||||
///
|
||||
/// All forms are supported, but GRDB does not allow you to distinguish between
|
||||
/// All forms are supported, but GRDB does not allow to distinguish between
|
||||
/// the `:AAAA`, `@AAAA`, and `$AAAA` syntaxes. You are encouraged to write
|
||||
/// named arguments with a colon prefix: `:name`.
|
||||
///
|
||||
/// ## Positional Arguments
|
||||
///
|
||||
/// To fill question mark placeholders, feed `StatementArguments` with an array:
|
||||
/// To fill question marks placeholders, feed `StatementArguments` with an array:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.execute(
|
||||
@@ -999,7 +949,7 @@ func withBindings<T>(
|
||||
/// arguments += ["name": "Barbara"]
|
||||
/// ```
|
||||
///
|
||||
/// On the other hand, `&+` and ``StatementArguments/append(contentsOf:)``
|
||||
/// On the other side, `&+` and ``StatementArguments/append(contentsOf:)``
|
||||
/// allow overriding named arguments:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -1024,7 +974,7 @@ func withBindings<T>(
|
||||
/// print(row)
|
||||
/// ```
|
||||
///
|
||||
/// Mixed arguments exist to support requests like the following:
|
||||
/// Mixed arguments exist as a support for requests like the following:
|
||||
///
|
||||
/// ```swift
|
||||
/// let players = try Player
|
||||
@@ -1057,7 +1007,7 @@ public struct StatementArguments: Hashable {
|
||||
///
|
||||
/// ```swift
|
||||
/// let values: [(any DatabaseValueConvertible)?] = ["foo", 1, nil]
|
||||
/// try db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values))
|
||||
/// db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values))
|
||||
/// ```
|
||||
public init(_ values: some Sequence<(any DatabaseValueConvertible)?>) {
|
||||
self.values = values.map { $0?.databaseValue ?? .null }
|
||||
@@ -1070,7 +1020,7 @@ public struct StatementArguments: Hashable {
|
||||
///
|
||||
/// ```swift
|
||||
/// let values: [String] = ["foo", "bar"]
|
||||
/// try db.execute(sql: "INSERT ... (?,?)", arguments: StatementArguments(values))
|
||||
/// db.execute(sql: "INSERT ... (?,?)", arguments: StatementArguments(values))
|
||||
/// ```
|
||||
public init(_ values: some Sequence<some DatabaseValueConvertible>) {
|
||||
self.values = values.map(\.databaseValue)
|
||||
@@ -1105,7 +1055,7 @@ public struct StatementArguments: Hashable {
|
||||
///
|
||||
/// ```swift
|
||||
/// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"]
|
||||
/// try db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
|
||||
/// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
|
||||
/// ```
|
||||
public init(_ dictionary: [String: (any DatabaseValueConvertible)?]) {
|
||||
namedValues = dictionary.mapValues { $0?.databaseValue ?? .null }
|
||||
@@ -1204,7 +1154,7 @@ public struct StatementArguments: Hashable {
|
||||
return replacedValues
|
||||
}
|
||||
|
||||
/// Creates a new `StatementArguments` by extending the left-hand side
|
||||
/// Creates a new `StatementArguments` by extending the left-hand size
|
||||
/// arguments with the right-hand side arguments.
|
||||
///
|
||||
/// Positional arguments are concatenated:
|
||||
@@ -1225,7 +1175,7 @@ public struct StatementArguments: Hashable {
|
||||
/// print(arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If the arguments on the right-hand side have named parameters that are
|
||||
/// If the arguments on the right-hand side has named parameters that are
|
||||
/// already defined on the left, a fatal error is raised:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -1252,7 +1202,7 @@ public struct StatementArguments: Hashable {
|
||||
return lhs
|
||||
}
|
||||
|
||||
/// Creates a new `StatementArguments` by extending the left-hand side
|
||||
/// Creates a new `StatementArguments` by extending the left-hand size
|
||||
/// arguments with the right-hand side arguments.
|
||||
///
|
||||
/// Positional arguments are concatenated:
|
||||
@@ -1273,7 +1223,7 @@ public struct StatementArguments: Hashable {
|
||||
/// print(arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If a named argument is defined in both arguments, the right-hand
|
||||
/// If a named arguments is defined in both arguments, the right-hand
|
||||
/// side wins:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -1298,7 +1248,7 @@ public struct StatementArguments: Hashable {
|
||||
return lhs
|
||||
}
|
||||
|
||||
/// Extends the left-hand side arguments with the right-hand side arguments.
|
||||
/// Extends the left-hand size arguments with the right-hand side arguments.
|
||||
///
|
||||
/// Positional arguments are concatenated:
|
||||
///
|
||||
@@ -1320,7 +1270,7 @@ public struct StatementArguments: Hashable {
|
||||
/// print(arguments)
|
||||
/// ```
|
||||
///
|
||||
/// If the arguments on the right-hand side have named parameters that are
|
||||
/// If the arguments on the right-hand side has named parameters that are
|
||||
/// already defined on the left, a fatal error is raised:
|
||||
///
|
||||
/// ```swift
|
||||
@@ -1407,7 +1357,7 @@ extension StatementArguments: ExpressibleByArrayLiteral {
|
||||
/// ```swift
|
||||
/// let arguments: StatementArguments = ["Arthur", 41]
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)",
|
||||
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)"
|
||||
/// arguments: arguments)
|
||||
/// ```
|
||||
public init(arrayLiteral elements: (any DatabaseValueConvertible)?...) {
|
||||
@@ -1423,7 +1373,7 @@ extension StatementArguments: ExpressibleByDictionaryLiteral {
|
||||
/// ```swift
|
||||
/// let arguments: StatementArguments = ["name": "Arthur", "score": 41]
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)",
|
||||
/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)"
|
||||
/// arguments: arguments)
|
||||
/// ```
|
||||
public init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) {
|
||||
@@ -1,23 +1,16 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if canImport(string_h)
|
||||
import string_h
|
||||
#elseif os(Linux)
|
||||
import Glibc
|
||||
#elseif os(Android)
|
||||
import Android
|
||||
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
@@ -48,7 +41,7 @@ final class StatementAuthorizer {
|
||||
/// savepoint statement.
|
||||
var transactionEffect: Statement.TransactionEffect?
|
||||
|
||||
/// If true, the statement is a `PRAGMA QUERY_ONLY` statement.
|
||||
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
|
||||
var isQueryOnlyPragma = false
|
||||
|
||||
private var isDropStatement = false
|
||||
@@ -119,10 +112,10 @@ final class StatementAuthorizer {
|
||||
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
|
||||
if columnName.isEmpty {
|
||||
// SELECT COUNT(*) FROM table
|
||||
selectedRegion.insert(table: tableName)
|
||||
selectedRegion.formUnion(DatabaseRegion(table: tableName))
|
||||
} else {
|
||||
// SELECT column FROM table
|
||||
selectedRegion.insert(table: tableName, column: columnName)
|
||||
selectedRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
@@ -215,7 +208,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)
|
||||
+13
-18
@@ -1,15 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/// A type that can decode itself from the low-level C interface to
|
||||
@@ -24,7 +19,7 @@ import SQLite3
|
||||
///
|
||||
/// ```swift
|
||||
/// // Optimized
|
||||
/// let scores = try Int.fetchAll(db, sql: "SELECT score FROM player")
|
||||
/// let scores = Int.fetchAll(db, sql: "SELECT score FROM player")
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, sql: "SELECT * FROM player")
|
||||
/// while let row = try rows.next() {
|
||||
@@ -105,7 +100,7 @@ public protocol StatementColumnConvertible {
|
||||
/// database values are handled
|
||||
/// in ``StatementColumnConvertible/fromStatement(_:atUncheckedIndex:)-2i8y6``.
|
||||
///
|
||||
/// For example, here is how Int64 adopts StatementColumnConvertible:
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
/// ```swift
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
@@ -128,7 +123,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 {
|
||||
@@ -155,7 +150,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
context: context())
|
||||
}
|
||||
|
||||
@inline(always)
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
static func fastDecode(
|
||||
fromRow row: Row,
|
||||
@@ -172,7 +167,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,
|
||||
@@ -188,7 +183,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
}
|
||||
|
||||
// Support for Decodable
|
||||
@inline(always)
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(
|
||||
fromRow row: Row,
|
||||
@@ -213,7 +208,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// let names: FastDatabaseValueCursor<String> = try String.fetchCursor(db, sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// while let name = try names.next() { // String
|
||||
/// while let name = names.next() { // String
|
||||
/// print(name)
|
||||
/// }
|
||||
/// }
|
||||
@@ -727,7 +722,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// SELECT score FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let scores = try Int.fetchSet(db, request)
|
||||
/// let scores = try Int.fetchAll(db, request)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
+1
-3
@@ -1,8 +1,5 @@
|
||||
#if canImport(CoreGraphics)
|
||||
import CoreGraphics
|
||||
#elseif !canImport(Darwin)
|
||||
import Foundation
|
||||
#endif
|
||||
|
||||
/// CGFloat adopts DatabaseValueConvertible
|
||||
extension CGFloat: DatabaseValueConvertible {
|
||||
@@ -18,3 +15,4 @@ extension CGFloat: DatabaseValueConvertible {
|
||||
return CGFloat(double)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
+5
-10
@@ -1,15 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
+6
-11
@@ -1,15 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -81,7 +76,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 {
|
||||
File renamed without changes.
+9
-12
@@ -1,19 +1,15 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
/// NSDate is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension NSDate: DatabaseValueConvertible {
|
||||
@@ -42,6 +38,7 @@ extension NSDate: DatabaseValueConvertible {
|
||||
return cast(date)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
@@ -52,7 +49,7 @@ extension Date: DatabaseValueConvertible {
|
||||
storageDateFormatter.string(from: self).databaseValue
|
||||
}
|
||||
|
||||
/// Creates a `Date` with the specified database value.
|
||||
/// Creates an `Date` with the specified database value.
|
||||
///
|
||||
/// If the database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
@@ -134,7 +131,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) {
|
||||
+13
-15
@@ -1,15 +1,11 @@
|
||||
#if !os(Linux)
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
@@ -23,9 +19,9 @@ extension Decimal: DatabaseValueConvertible {
|
||||
.databaseValue
|
||||
}
|
||||
|
||||
/// Creates a `Decimal` with the specified database value.
|
||||
/// Creates an `Decimal` with the specified database value.
|
||||
///
|
||||
/// If the database value contains an integer or a double, returns a
|
||||
/// If the database value contains a integer or a double, returns a
|
||||
/// `Decimal` initialized from this number.
|
||||
///
|
||||
/// If the database value contains a string, parses the string with the
|
||||
@@ -49,7 +45,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) {
|
||||
@@ -58,8 +54,9 @@ extension Decimal: StatementColumnConvertible {
|
||||
case SQLITE_FLOAT:
|
||||
self.init(sqlite3_column_double(sqliteStatement, index))
|
||||
case SQLITE_TEXT:
|
||||
let string = String(sqliteStatement: sqliteStatement, index: index)
|
||||
self.init(string: string, locale: _posixLocale)
|
||||
self.init(
|
||||
string: String(cString: sqlite3_column_text(sqliteStatement, index)!),
|
||||
locale: _posixLocale)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
@@ -68,3 +65,4 @@ extension Decimal: StatementColumnConvertible {
|
||||
|
||||
@usableFromInline
|
||||
let _posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
+3
-1
@@ -1,3 +1,4 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
@@ -8,7 +9,7 @@ extension NSData: DatabaseValueConvertible {
|
||||
(self as Data).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an `NSData` from the specified database value.
|
||||
/// Returns a `NSData` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a data blob, returns it.
|
||||
///
|
||||
@@ -23,3 +24,4 @@ extension NSData: DatabaseValueConvertible {
|
||||
return cast(data)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
File renamed without changes.
+6
-12
@@ -1,3 +1,4 @@
|
||||
#if !os(Linux) && !os(Windows)
|
||||
import Foundation
|
||||
|
||||
private let integerRoundingBehavior = NSDecimalNumberHandler(
|
||||
@@ -19,7 +20,7 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
/// Otherwise, returns an INTEGER or REAL database value, according to the
|
||||
/// value stored in the `NSNumber`.
|
||||
public var databaseValue: DatabaseValue {
|
||||
// Don't lose precision: store integers that fit in Int64 as Int64
|
||||
// Don't lose precision: store integers that fits in Int64 as Int64
|
||||
if let decimal = self as? NSDecimalNumber,
|
||||
decimal == decimal.rounding(accordingToBehavior: integerRoundingBehavior), // integer
|
||||
decimal.compare(NSDecimalNumber(value: Int64.max)) != .orderedDescending, // decimal <= Int64.max
|
||||
@@ -69,7 +70,7 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an `NSNumber` from the specified database value.
|
||||
/// Returns a `NSNumber` from the specified database value.
|
||||
///
|
||||
/// If the database value is an integer or a double, returns an `NSNumber`
|
||||
/// initialized from this number.
|
||||
@@ -80,18 +81,10 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64) where self is NSDecimalNumber.Type:
|
||||
let number = NSDecimalNumber(value: int64)
|
||||
return number as? Self
|
||||
case .int64(let int64):
|
||||
let number = NSNumber(value: int64)
|
||||
return number as? Self
|
||||
case .double(let double) where self is NSDecimalNumber.Type:
|
||||
let number = NSDecimalNumber(value: double)
|
||||
return number as? Self
|
||||
return self.init(value: int64)
|
||||
case .double(let double):
|
||||
let number = NSNumber(value: double)
|
||||
return number as? Self
|
||||
return self.init(value: double)
|
||||
case let .string(string):
|
||||
// Must match Decimal.fromDatabaseValue(_:)
|
||||
guard let decimal = Decimal(string: string, locale: posixLocale) else { return nil }
|
||||
@@ -103,3 +96,4 @@ extension NSNumber: DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
private let posixLocale = Locale(identifier: "en_US_POSIX")
|
||||
#endif
|
||||
+4
-2
@@ -1,3 +1,4 @@
|
||||
#if !os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// NSString adopts DatabaseValueConvertible
|
||||
@@ -8,11 +9,11 @@ extension NSString: DatabaseValueConvertible {
|
||||
(self as String).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an `NSString` from the specified database value.
|
||||
/// Returns a `NSString` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, returns it.
|
||||
///
|
||||
/// If the database value contains a data blob, parses this data as a
|
||||
/// If the database value contains a data blob, parses this data as an
|
||||
/// UTF8 string.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
@@ -23,3 +24,4 @@ extension NSString: DatabaseValueConvertible {
|
||||
return self.init(string: string)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
File renamed without changes.
+3
-5
@@ -1,15 +1,12 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux) && !os(Windows)
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
extension NSURL: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a TEXT database value containing the absolute URL.
|
||||
public var databaseValue: DatabaseValue {
|
||||
#if !canImport(Darwin)
|
||||
absoluteString.databaseValue
|
||||
#else
|
||||
absoluteString?.databaseValue ?? .null
|
||||
#endif
|
||||
absoluteString?.databaseValue ?? .null
|
||||
}
|
||||
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
@@ -19,6 +16,7 @@ extension NSURL: DatabaseValueConvertible {
|
||||
return cast(URL(string: string))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// URL stores its absoluteString in the database.
|
||||
extension URL: DatabaseValueConvertible { }
|
||||
+16
-26
@@ -1,19 +1,15 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux) && !os(Windows)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
@@ -25,9 +21,9 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an `NSUUID` from the specified database value.
|
||||
/// Returns a `NSUUID` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, parses this string as a uuid.
|
||||
/// If the database value contains a string, parses this string as an uuid.
|
||||
///
|
||||
/// If the database value contains a data blob that contains 16 bytes,
|
||||
/// returns a uuid from those bytes.
|
||||
@@ -37,22 +33,16 @@ extension NSUUID: DatabaseValueConvertible {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data) where data.count == 16:
|
||||
return data.withUnsafeBytes {
|
||||
#if canImport(Darwin)
|
||||
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
|
||||
#else
|
||||
guard let uuidBytes = $0.bindMemory(to: UInt8.self).baseAddress else {
|
||||
return nil as Self?
|
||||
}
|
||||
return NSUUID(uuidBytes: uuidBytes) as? Self
|
||||
#endif
|
||||
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
|
||||
}
|
||||
case .string(let string):
|
||||
return NSUUID(uuidString: string) as? Self
|
||||
return self.init(uuidString: string)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// UUID adopts DatabaseValueConvertible
|
||||
extension UUID: DatabaseValueConvertible {
|
||||
@@ -65,7 +55,7 @@ extension UUID: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a `UUID` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a string, parses this string as a uuid.
|
||||
/// If the database value contains a string, parses this string as an uuid.
|
||||
///
|
||||
/// If the database value contains a data blob that contains 16 bytes,
|
||||
/// returns a uuid from those bytes.
|
||||
@@ -86,20 +76,20 @@ extension UUID: DatabaseValueConvertible {
|
||||
}
|
||||
|
||||
extension UUID: StatementColumnConvertible {
|
||||
@inline(always)
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_TEXT:
|
||||
let string = String(sqliteStatement: sqliteStatement, index: index)
|
||||
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
guard let uuid = UUID(uuidString: string) else {
|
||||
return nil
|
||||
}
|
||||
self.init(uuid: uuid.uuid)
|
||||
case SQLITE_BLOB:
|
||||
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index)
|
||||
else {
|
||||
let blob = sqlite3_column_blob(sqliteStatement, index) else
|
||||
{
|
||||
return nil
|
||||
}
|
||||
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
|
||||
File renamed without changes.
File renamed without changes.
+1
-1
@@ -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 {
|
||||
File renamed without changes.
+6
-11
@@ -1,15 +1,10 @@
|
||||
// Import C SQLite functions
|
||||
#if GRDBFRAMEWORK // GRDB.xcodeproj
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
#else // SPM
|
||||
#if SQLCipher // Takes precedence over SystemSQLite
|
||||
import SQLCipher
|
||||
#elseif SystemSQLite
|
||||
import GRDBSQLite
|
||||
#else
|
||||
#error("Enable a GRDB trait that provides SQLite.")
|
||||
#endif
|
||||
#endif
|
||||
|
||||
extension Optional: StatementBinding where Wrapped: StatementBinding {
|
||||
@@ -87,7 +82,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) {
|
||||
Loaded 100 of 645 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user