Merge pull request #479 from groue/GRDB-4.0

GRDB 4.0
This commit is contained in:
Gwendal Roué authored and GitHub committed 2019-05-23 19:39:32 +02:00
commit d7d3f87921
442 files changed
+30982 -18685

No files matched your search

+2 -1
View File
@@ -1,4 +1,5 @@
source 'https://rubygems.org'
gem 'xcpretty'
gem 'xcpretty-travis-formatter'
gem 'xcpretty-travis-formatter'
gem 'cocoapods', '~> 1.6'
+1 -1
View File
@@ -18,7 +18,7 @@ Please fill out this template when filing an issue.
### Environment
**GRDB flavor(s):** (GRDB, GRDBCipher, GRDBCustom?)
**GRDB flavor(s):** (GRDB, SQLCipher, Custom SQLite build?)
**GRDB version:**
**Installation method:** (CocoaPods, SPM, manual?)
**Xcode version:**
+1 -1
View File
@@ -9,4 +9,4 @@ Please verify that your pull request checks those boxes:
- [ ] This pull request is submitted against the `development` branch.
- [ ] Inline documentation has been updated.
- [ ] README.md or another dedicated guide has been updated.
- [ ] Changes are tested, for all flavors of GRDB, GRDBCipher, and GRDBCustomSQLite.
- [ ] Changes are tested.
-2
View File
@@ -101,9 +101,7 @@ SQLiteCustom/GRDBCustomSQLite-USER.h
SQLiteCustom/GRDBCustomSQLite-USER.xcconfig
# CocoaPods test
Podfile.lock
Pods
Tests/CocoaPods/*/*.xcworkspace
# SPM
.build
+1 -4
View File
@@ -7,9 +7,6 @@
[submodule "Tests/Performance/Realm"]
path = Tests/Performance/Realm
url = https://github.com/realm/realm-cocoa.git
[submodule "SQLCipher/src"]
path = SQLCipher/src
url = https://github.com/groue/sqlcipher.git
[submodule "SQLiteCustom/src"]
path = SQLiteCustom/src
url = https://github.com/swiftlyfalling/SQLiteLib
url = https://github.com/swiftlyfalling/SQLiteLib.git
+1 -1
View File
@@ -1 +1 @@
4.1
4.2
+266 -157
View File
@@ -4,6 +4,16 @@
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:
@@ -13,213 +23,312 @@ jobs:
include:
###########################################
## Test GRDB
# Test GRDBOSX (Xcode 10)
- stage: Test GRDB
## Test GRDB Xcode 10.2
- stage: Test GRDB Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode10.2
env:
- TID=GRDBOSX (Xcode 10, Swift 4.2, macOS)
- TID=GRDBOSX (Swift 5, macOS)
script: make test_framework_GRDBOSX_maxSwift
# Test GRDBOSX (Xcode 10)
- stage: Test GRDB
- stage: Test GRDB Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode10.2
env:
- TID=GRDBOSX (Xcode 10, Swift 4.0, macOS)
- TID=GRDBOSX (Swift 4.2, macOS)
script: make test_framework_GRDBOSX_minSwift
# Test GRDBWatchOS (Xcode 10)
- stage: Test GRDB
- stage: Test GRDB Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode10.2
env:
- TID=GRDBWatchOS (Xcode 10, watchOS)
- TID=GRDBWatchOS (watchOS)
script: make test_framework_GRDBWatchOS
# Test GRDBiOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
- stage: Test GRDB Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode10.2
env:
- TID=GRDBiOS (Xcode 10, Swift 4.2, iOS <MAX>)
- TID=GRDBiOS (Swift 5, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
# Test GRDBiOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
- stage: Test GRDB
- stage: Test GRDB Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
osx_image: xcode10.2
env:
- TID=GRDBiOS (Xcode 9.4, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
# Test GRDBiOS (Xcode 9.3, iOS <MINIMUM VERSION>))
- stage: Test GRDB
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_minSwift
- stage: Test GRDB Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.3
osx_image: xcode10.2
env:
- TID=GRDBiOS (Xcode 9.3, iOS <MIN>)
- TID=GRDBiOS (Swift 5, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
# Test GRDB [SPM] (Xcode 10, macOS)
- stage: Test GRDB
- stage: Test GRDB Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode10.2
env:
- TID=GRDB [SPM] (Xcode 10, macOS)
- TID=GRDB [SPM] (macOS)
script: make test_SPM
###########################################
## Test GRDB (Custom SQLite)
# Test GRDBCustomSQLiteOSX (Xcode 10)
- stage: Test GRDB + Custom SQLite
## Test GRDBCustom Xcode 10.2
- stage: Test GRDBCustom Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode10.2
env:
- TID=GRDBCustomSQLiteOSX (Xcode 10, macOS)
- TID=GRDBOSX (Swift 5, macOS)
script: make test_framework_GRDBCustomSQLiteOSX
# Test GRDBCustomSQLiteiOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
- stage: Test GRDBCustom Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode10.2
env:
- TID=GRDBCustomSQLiteiOS (Xcode 10, Swift 4.2, iOS <MAX>)
- TID=GRDBiOS (Swift 5, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
# Test GRDBCustomSQLiteiOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
- stage: Test GRDBCustom Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode10.2
env:
- TID=GRDBCustomSQLiteiOS (Xcode 10, Swift 4.0, iOS <MAX>)
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift
# Test GRDBCustomSQLiteiOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + Custom SQLite
- stage: Test GRDBCustom Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
osx_image: xcode10.2
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.4, iOS <MAX>)
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget
# Test GRDBCustomSQLiteiOS (Xcode 9.3, iOS <MINIMUM VERSION>))
- stage: Test GRDB + Custom SQLite
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.3
env:
- TID=GRDBCustomSQLiteiOS (Xcode 9.3, iOS <MIN>)
- TID=GRDBiOS (Swift 5, iOS <MIN>)
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test GRDB (SQLCipher)
# Test GRDBCipherOSX (Xcode 10)
- stage: Test GRDB + SQLCipher
## Test SQLCipher Xcode 10.2
- stage: Test SQLCipher Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode10.2
env:
- TID=GRDBCipherOSX (Xcode 10, macOS)
script: make test_framework_GRDBCipherOSX
# Test GRDBCipheriOS (Xcode 10, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
- TID=SQLCipher 3
script: make test_framework_SQLCipher3
- stage: Test SQLCipher Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode10.2
env:
- TID=GRDBCipheriOS (Xcode 10, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 9.4, iOS <MAXIMUM VERSION>)
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.4
env:
- TID=GRDBCipheriOS (Xcode 9.4, iOS <MAX>)
script: make test_framework_GRDBCipheriOS_maxTarget
# Test GRDBCipheriOS (Xcode 9.3, iOS <MINIMUM VERSION>))
- stage: Test GRDB + SQLCipher
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode9.3
env:
- TID=GRDBCipheriOS (Xcode 9.3, iOS <MIN>)
script: make test_framework_GRDBCipheriOS_minTarget
- TID=SQLCipher 4
script: make test_framework_SQLCipher4
###########################################
## Test Installation Methods
# Manual Install (Xcode 10)
- stage: Test Installation
## Test Installation Xcode 10.2
# Manual Install
- stage: Test Installation Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
osx_image: xcode10.2
env:
- TID=Manual Install (Xcode 10)
- TID=Manual Install
script: make test_install_manual
# Manual Install (GRDBCipher, Xcode 10)
- stage: Test Installation
# CocoaPods Lint
- stage: Test Installation Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.2
env:
- TID=CocoaPods Lint
script: make test_CocoaPodsLint_GRDB
# CocoaPods Install GRDB
- stage: Test Installation Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.2
env:
- TID=CocoaPods GRDB
script: make test_install_GRDB_CocoaPods
# SPM Install
- stage: Test Installation Xcode 10.2
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.2
env:
- TID=SPM
script: make test_install_SPM
###########################################
## Test GRDB Xcode 10.1
- stage: Test GRDB Xcode 10.1
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.1
env:
- TID=GRDBOSX (Swift 4.2, macOS)
script: make test_framework_GRDBOSX_maxSwift
- stage: Test GRDB Xcode 10.1
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.1
env:
- TID=GRDBWatchOS (watchOS)
script: make test_framework_GRDBWatchOS
- stage: Test GRDB Xcode 10.1
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.1
env:
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 10.1
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.1
env:
- TID=GRDBiOS (Swift 4.2, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
- stage: Test GRDB Xcode 10.1
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10.1
env:
- TID=GRDB [SPM] (macOS)
script: make test_SPM
# ###########################################
# ## Test GRDBCustom Xcode 10.1
#
# - stage: Test GRDBCustom Xcode 10.1
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10.1
# env:
# - TID=GRDBOSX (Swift 4.2, macOS)
# script: make test_framework_GRDBCustomSQLiteOSX
#
# - stage: Test GRDBCustom Xcode 10.1
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10.1
# env:
# - TID=GRDBiOS (Swift 4.2, iOS <MAX>)
# script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
#
# - stage: Test GRDBCustom Xcode 10.1
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10.1
# env:
# - TID=GRDBiOS (Swift 4.2, iOS <MIN>)
# script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test GRDB Xcode 10
- stage: Test GRDB Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=Manual Install (GRDBCipher, Xcode 10)
script: make test_install_GRDBCipher
# CocoaPods Lint (Xcode 10)
- stage: Test Installation
- TID=GRDBOSX (Swift 4.2, macOS)
script: make test_framework_GRDBOSX_maxSwift
- stage: Test GRDB Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
env:
- TID=CocoaPods Lint GRDB.swift (Xcode 10)
script: make test_CocoaPodsLint_GRDB
# CocoaPods Lint (Xcode 10)
- stage: Test Installation
- TID=GRDBWatchOS (watchOS)
script: make test_framework_GRDBWatchOS
- stage: Test GRDB Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
env:
- TID=CocoaPods Lint GRDBCipher (Xcode 10)
script: make test_CocoaPodsLint_GRDBCipher
# CocoaPods Install (Xcode 10)
- stage: Test Installation
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- stage: Test GRDB Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
install:
- gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
env:
- TID=CocoaPods GRDB (Xcode 10)
script: make test_install_GRDB_CocoaPods
# Disabled until we understand the reason for this failure:
# https://travis-ci.org/groue/GRDB.swift/jobs/503214543
#
# # CocoaPods Install (Xcode 10)
# - stage: Test Installation
- TID=GRDBiOS (Swift 4.2, iOS <MIN>)
script: make test_framework_GRDBiOS_minTarget
- stage: Test GRDB Xcode 10
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode10
env:
- TID=GRDB [SPM] (macOS)
script: make test_SPM
# ###########################################
# ## Test GRDBCustom Xcode 10
#
# - stage: Test GRDBCustom Xcode 10
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10
# install:
# - gem install cocoapods --pre # >= 1.6.0.beta.1 for cocoapods lint
# env:
# - TID=CocoaPods GRDBCipher (Xcode 10)
# script: make test_install_GRDBCipher_CocoaPods
# SPM Install (Xcode 10)
- stage: Test Installation
osx_image: xcode10
env:
- TID=SPM (Xcode 10)
script: make test_install_SPM
## Carthage Build
- stage: Test Installation
osx_image: xcode10
before_install:
- brew update
- brew outdated carthage || brew upgrade carthage
env:
- TID=Carthages
script: make test_CarthageBuild
# - TID=GRDBOSX (Swift 4.2, macOS)
# script: make test_framework_GRDBCustomSQLiteOSX
#
# - stage: Test GRDBCustom Xcode 10
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10
# env:
# - TID=GRDBiOS (Swift 4.2, iOS <MAX>)
# script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
#
# - stage: Test GRDBCustom Xcode 10
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10
# env:
# - TID=GRDBiOS (Swift 4.2, iOS <MIN>)
# script: make test_framework_GRDBCustomSQLiteiOS_minTarget
#
# ###########################################
# ## Test SQLCipher Xcode 10
#
# - stage: Test SQLCipher Xcode 10
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10
# env:
# - TID=SQLCipher 3
# script: make test_framework_SQLCipher3
#
# - stage: Test SQLCipher Xcode 10
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10
# env:
# - TID=SQLCipher 4
# script: make test_framework_SQLCipher4
#
# ###########################################
# ## Test Installation Xcode 10
#
# # Manual Install
# - stage: Test Installation Xcode 10
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10
# env:
# - TID=Manual Install
# script: make test_install_manual
#
# # CocoaPods Lint
# - stage: Test Installation Xcode 10
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10
# env:
# - TID=CocoaPods Lint
# script: make test_CocoaPodsLint_GRDB
#
# # CocoaPods Install GRDB
# - stage: Test Installation Xcode 10
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10
# env:
# - TID=CocoaPods GRDB
# script: make test_install_GRDB_CocoaPods
#
# # SPM Install
# - stage: Test Installation Xcode 10
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode10
# env:
# - TID=SPM
# script: make test_install_SPM
+497 -1
View File
@@ -3,7 +3,11 @@ Release Notes
All notable changes to this project will be documented in this file.
GRDB adheres to [Semantic Versioning](https://semver.org/).
GRDB adheres to [Semantic Versioning](https://semver.org/), with one expection: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library.
#### 4.x Releases
- `4.0.x` Releases - [4.0.0](#400)
#### 3.x Releases
@@ -43,6 +47,498 @@ GRDB adheres to [Semantic Versioning](https://semver.org/).
- [0.110.0](#01100), ...
## 4.0.0
Released May 23, 2019 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v3.7.0...v4.0.0)
GRDB 4 is a release focused on **Swift 5**, and **enhancements on associations between record types**.
It comes with new features, but also a few breaking changes. The [GRDB 4 Migration Guide](Documentation/GRDB3MigrationGuide.md) will help you upgrading your applications.
### New
- [#478](https://github.com/groue/GRDB.swift/pull/478): Swift 5: SQL interpolation
- [#484](https://github.com/groue/GRDB.swift/pull/484): SE-0193 Cross-module inlining and specialization
- [#486](https://github.com/groue/GRDB.swift/pull/486): Refactor PersistenceError.recordNotFound
- [#488](https://github.com/groue/GRDB.swift/pull/488): ValueObservation Cleanup
- [#490](https://github.com/groue/GRDB.swift/pull/490): Indirect Associations
- [#493](https://github.com/groue/GRDB.swift/pull/493): Bump SQLite to [3.27.2](https://www.sqlite.org/releaselog/3_27_2.html)
- [#499](https://github.com/groue/GRDB.swift/pull/499): Extract EncodableRecord from MutablePersistableRecord
- [#502](https://github.com/groue/GRDB.swift/pull/502): Rename Future to DatabaseFuture
- [#503](https://github.com/groue/GRDB.swift/pull/503): IFNULL support for association aggregates
- [#508](https://github.com/groue/GRDB.swift/pull/508) by [@michaelkirk-signal](https://github.com/michaelkirk-signal): Allow Database Connection Configuration
- [#510](https://github.com/groue/GRDB.swift/pull/510) by [@charlesmchen-signal](https://github.com/charlesmchen-signal): Expose DatabaseRegion(table:) initializer
- [#515](https://github.com/groue/GRDB.swift/pull/515) by [@alextrob](https://github.com/alextrob): Add "LIMIT 1" to `fetchOne` requests
- [#517](https://github.com/groue/GRDB.swift/pull/517): Support for SQLCipher 4
- [#525](https://github.com/groue/GRDB.swift/pull/525): Eager Loading of HasMany associations
### Fixed
- [#511](https://github.com/groue/GRDB.swift/pull/511) by [@charlesmchen-signal](https://github.com/charlesmchen-signal): Fix DatabasePool.setupMemoryManagement()
### Breaking Changes
- Swift 4.0 and Swift 4.1 are no longer supported. Minimum Swift version is now Swift 4.2.
- iOS 8 is no longer supported. Minimum deployment target is now iOS 9.0.
- Deprecated APIs are no longer available.
- See the [Migration Guide](Documentation/GRDB3MigrationGuide.md) and the API diff below for other changes.
### Documentation Diff
- [SQL Interpolation](Documentation/SQLInterpolation.md): this new document describes the new SQL interpolation feature.
- The [Associations Guide](Documentation/AssociationsBasics.md) has been updated:
- [Required Protocols](Documentation/AssociationsBasics.md#required-protocols) describes which protocols your record types have to conform to in order to use Associations features.
- [The Types of Associations](Documentation/AssociationsBasics.md#the-types-of-associations) introduces the new HasManyThrough and HasOneThrough associations.
- [Convention for Database Table Names](Documentation/AssociationsBasics.md#convention-for-database-table-names) describes how GRDB inflects database table names into their singular or plural forms, depending on your usages of associations.
- [Joining And Prefetching Associated Records](Documentation/AssociationsBasics.md#joining-and-prefetching-associated-records) describes the new `including(all:)` method.
- [Fetching Values from Associations](Documentation/AssociationsBasics.md#fetching-values-from-associations) explains how to decode record types from associated requests, including requests built with the new `including(all:)` method.
- [Aggregate Operations](Documentation/AssociationsBasics.md#aggregate-operations) describes all the ways to transform association aggregates with logical, comparison and arithmetic operators.
### API diff
<details>
<summary>Associations: indirect associations and eager loading of HasMany associations</summary>
**New AssociationToOne and AssociationToMany protocols**
```diff
+protocol AssociationToOne: Association { }
+protocol AssociationToMany: Association { }
+extension AssociationToMany {
+ var count: AssociationAggregate<OriginRowDecoder> { get }
+ var isEmpty: AssociationAggregate<OriginRowDecoder> { get }
+ func average(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder>
+ func max(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder>
+ func min(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder>
+ func sum(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder>
+}
+extension BelongsToAssociation: AssociationToOne { }
+extension HasManyAssociation: AssociationToMany { }
+extension HasOneAssociation: AssociationToOne { }
```
**New HasManyThroughAssociation and HasOneThroughAssociation**
```diff
+struct HasManyThroughAssociation<Origin, Destination>: AssociationToMany { }
+extension HasManyThroughAssociation: TableRequest where Destination: TableRecord { }
+struct HasOneThroughAssociation<Origin, Destination>: AssociationToOne { }
+extension HasOneThroughAssociation: TableRequest where Destination: TableRecord { }
extension TableRecord {
+ static func hasMany<Pivot, Target>(_ destination: Target.RowDecoder.Type, through pivot: Pivot, using target: Target, key: String? = nil) -> HasManyThroughAssociation<Self, Target.RowDecoder> where Pivot: Association, Target: Association, Pivot.OriginRowDecoder == Self, Pivot.RowDecoder == Target.OriginRowDecoder
+ static func hasOne<Pivot, Target>(_ destination: Target.RowDecoder.Type, through pivot: Pivot, using target: Target, key: String? = nil) -> HasOneThroughAssociation<Self, Target.RowDecoder> where Pivot: AssociationToOne, Target: AssociationToOne, Pivot.OriginRowDecoder == Self, Pivot.RowDecoder == Target.OriginRowDecoder
}
```
**Eager loading of HasMany associations**
```diff
extension TableRecord {
+ static func including<A: AssociationToMany>(all association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self
}
extension Association {
+ func including<A: AssociationToMany>(all association: A) -> Self where A.OriginRowDecoder == RowDecoder
}
extension QueryInterfaceRequest {
+ func including<A: AssociationToMany>(all association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder
}
```
**Accessing eager loaded rows**
```diff
class Row {
+ var prefetchedRows: Row.PrefetchedRowsView { get }
+ subscript<Collection>(_ key: String) -> Collection where Collection: RangeReplaceableCollection, Collection.Element: FetchableRecord { get }
+ subscript<Record: FetchableRecord & Hashable>(_ key: String) -> Set<Record> { get }
}
extension Row {
+ struct PrefetchedRowsView: Equatable {
+ var isEmpty: Bool { get }
+ var keys: Set<String> { get }
+ subscript(_ key: String) -> [Row]? { get }
+ }
}
```
</details>
<details>
<summary>SQL Interpolation</summary>
```diff
+extension SQLRequest: ExpressibleByStringInterpolation {
+ init(stringInterpolation sqlInterpolation: SQLInterpolation)
+}
+struct SQLLiteral: ExpressibleByStringInterpolation {
+ var sql: String { get }
+ var arguments: StatementArguments { get }
+ init(stringInterpolation sqlInterpolation: SQLInterpolation)
+ init(sql: String, arguments: StatementArguments = StatementArguments())
+ func mapSQL(_ transform: (String) throws -> String) rethrows -> SQLLiteral
+ mutating func append(sql: String, arguments: StatementArguments = StatementArguments())
+ mutating func append(literal sqlLiteral: SQLLiteral)
+ static func + (lhs: SQLLiteral, rhs: SQLLiteral) -> SQLLiteral
+ static func += (lhs: inout SQLLiteral, rhs: SQLLiteral)
+}
+extension Sequence where Element == SQLLiteral {
+ func joined(separator: String = "") -> SQLLiteral
+}
+struct SQLInterpolation: StringInterpolationProtocol {
+ mutating func appendLiteral(_ sql: String)
+ mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments())
+ mutating func appendInterpolation(literal sqlLiteral: SQLLiteral)
+ mutating func appendInterpolation<T: TableRecord>(_ table: T.Type)
+ mutating func appendInterpolation<T: TableRecord>(tableOf record: T)
+ mutating func appendInterpolation(_ selection: SQLSelectable)
+ mutating func appendInterpolation<T: SQLExpressible>(_ expressible: T?)
+ mutating func appendInterpolation(_ codingKey: CodingKey)
+ mutating func appendInterpolation<S>(_ sequence: S) where S: Sequence, S.Element: SQLExpressible
+ mutating func appendInterpolation(_ ordering: SQLOrderingTerm)
+ mutating func appendInterpolation<T>(_ request: SQLRequest<T>)
+}
```
</details>
<details>
<summary>Raw SQL breaking changes</summary>
```diff
class Database {
- func makeSelectStatement(_ sql: String) throws -> SelectStatement
- func makeUpdateStatement(_ sql: String) throws -> UpdateStatement
+ func makeSelectStatement(sql: String) throws -> SelectStatement
+ func makeUpdateStatement(sql: String) throws -> UpdateStatement
- func cachedSelectStatement(_ sql: String) throws -> SelectStatement
- func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement
+ func cachedSelectStatement(sql: String) throws -> SelectStatement
+ func cachedUpdateStatement(sql: String) throws -> UpdateStatement
- func execute(_ sql: String, arguments: StatementArguments? = nil) throws
+ func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws
}
class Row {
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row]
- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row?
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row]
+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row?
}
extension FetchableRecord {
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
}
extension DatabaseValueConvertible {
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
}
extension Optional where Wrapped: DatabaseValueConvertible {
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?]
}
extension TableRecord {
- static func select(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self>
+ static func select(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest<Self>
+ static func select(literal sqlLiteral: SQLLiteral) -> QueryInterfaceRequest<Self>
- static func select<RowDecoder>(sql: String, arguments: StatementArguments? = nil, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
+ static func select<RowDecoder>(sql: String, arguments: StatementArguments = StatementArguments(), as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
+ static func select<RowDecoder>(literal sqlLiteral: SQLLiteral, as type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder>
- static func filter(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self>
+ static func filter(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest<Self>
+ static func filter(literal sqlLiteral: SQLLiteral) -> QueryInterfaceRequest<Self>
- static func order(sql: String, arguments: StatementArguments? = nil) -> QueryInterfaceRequest<Self>
+ static func order(sql: String, arguments: StatementArguments = StatementArguments()) -> QueryInterfaceRequest<Self>
+ static func order(literal sqlLiteral: SQLLiteral) -> QueryInterfaceRequest<Self>
}
final class FetchedRecordsController<Record: FetchableRecord> {
- func setRequest(sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws
+ func setRequest(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws
}
extension SelectionRequest {
- func select(sql: String, arguments: StatementArguments? = nil) -> Self
+ func select(sql: String, arguments: StatementArguments = StatementArguments()) -> Self
+ func select(literal sqlLiteral: SQLLiteral) -> Self
}
extension FilteredRequest {
- func filter(sql: String, arguments: StatementArguments? = nil) -> Self
+ func filter(sql: String, arguments: StatementArguments = StatementArguments()) -> Self
+ func filter(literal sqlLiteral: SQLLiteral) -> Self
}
extension AggregatingRequest {
- func group(sql: String, arguments: StatementArguments? = nil) -> Self
+ func group(sql: String, arguments: StatementArguments = StatementArguments()) -> Self
+ func group(literal sqlLiteral: SQLLiteral) -> Self
- func having(sql: String, arguments: StatementArguments? = nil) -> Self
+ func having(sql: String, arguments: StatementArguments = StatementArguments()) -> Self
+ func having(literal sqlLiteral: SQLLiteral) -> Self
}
extension OrderedRequest {
- func order(sql: String, arguments: StatementArguments? = nil) -> Self
+ func order(sql: String, arguments: StatementArguments = StatementArguments()) -> Self
+ func order(literal sqlLiteral: SQLLiteral) -> Self
}
struct SQLRequest<T> : FetchRequest {
- init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false)
+ init(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil, cached: Bool = false)
+ init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false)
}
struct SQLExpressionLiteral {
- init(_ sql: String, arguments: StatementArguments? = nil)
+ init(sql: String, arguments: StatementArguments = StatementArguments())
+ init(literal sqlLiteral: SQLLiteral)
}
```
</details>
<details>
<summary>EncodableRecord</summary>
```diff
+protocol EncodableRecord {
+ func encode(to container: inout PersistenceContainer)
+ static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { get }
+ static func databaseJSONEncoder(for column: String) -> JSONEncoder
+ static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get }
+ static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get }
+}
+
+extension EncodableRecord where Self: Encodable {
+ func encode(to container: inout PersistenceContainer)
+}
+
+extension EncodableRecord {
+ var databaseDictionary: [String: DatabaseValue] { get }
+ func databaseEquals(_ record: Self) -> Bool
+ func databaseChanges<Record: EncodableRecord>(from record: Record) -> [String: DatabaseValue]
+}
-protocol MutablePersistableRecord: TableRecord { }
+protocol MutablePersistableRecord: EncodableRecord, TableRecord { }
```
</details>
<details>
<summary>ValueObservation breaking changes</summary>
```diff
enum ValueScheduling {
- case onQueue(DispatchQueue, startImmediately: Bool)
+ case async(onQueue: DispatchQueue, startImmediately: Bool)
}
struct ValueObservation<Reducer> {
- var extent: Database.TransactionObservationExtent
- static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation
- static func tracking<Value>(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (Database) throws -> Value) -> ValueObservation<DistinctUntilChangedValueReducer<RawValueReducer<Value>>> where Value: Equatable
}
```
</details>
<details>
<summary>Customizing pluralization and singularization</summary>
```diff
+struct Inflections {
+ init()
+ func pluralize(_ string: String) -> String
+ func singularize(_ string: String) -> String
// Configuration
+ mutating func plural(_ pattern: String, options: NSRegularExpression.Options = [.caseInsensitive], _ template: String)
+ mutating func singular(_ pattern: String, options: NSRegularExpression.Options = [.caseInsensitive], _ template: String)
+ mutating func uncountableWords(_ words: [String])
+ mutating func irregularSuffix(_ singular: String, _ plural: String)
+}
+
+extension Inflections {
+ static var `default`: Inflections { get set }
+}
```
</details>
<details>
<summary>Full Text Search breaking changes: support for SQLite 3.27</summary>
```diff
struct FTS3 {
+ enum Diacritics {
+ case keep
+ case removeLegacy
+ #if GRDBCUSTOMSQLITE
+ case remove
+ #endif
+ }
}
struct FTS3TokenizerDescriptor {
- static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor
+ static func unicode61(diacritics: FTS3.Diacritics = .removeLegacy, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor
}
struct FTS5 {
+ enum Diacritics {
+ case keep
+ case removeLegacy
+ #if GRDBCUSTOMSQLITE
+ case remove
+ #endif
+ }
}
struct FTS5TokenizerDescriptor {
- static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS5TokenizerDescriptor
+ static func unicode61(diacritics: FTS5.Diacritics = .removeLegacy, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS5TokenizerDescriptor
}
```
</details>
<details>
<summary>SQLCipher breaking changes</summary>
```diff
struct Configuration {
- var cipherPageSize: Int
- var kdfIterations: Int
}
```
</details>
<details>
<summary>Miscellaneous additions</summary>
**Column initializer from CodingKey**
```diff
struct Column {
+ init(_ codingKey: CodingKey)
}
```
**Association aggregates: support for the IFNULL sql operator**
```diff
+func ?? <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder>
```
**Remove all orderings from a request**
```diff
protocol OrderedRequest {
+ func unordered()
}
```
**Annotate requests with any value, not only association aggregates**
```diff
protocol SelectionRequest {
+ annotated(with selection: [SQLSelectable]) -> Self
}
extension SelectionRequest {
+ func annotated(with selection: SQLSelectable...) -> Self
}
extension TableRecord {
+ static func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest<Self>
+ static func annotated(with selection: SQLSelectable...) -> QueryInterfaceRequest<Self>
}
```
**Build a DatabaseRegion from a table name**
```diff
struct DatabaseRegion {
+ init(table: String)
}
```
</details>
<details>
<summary>Miscellaneous breaking changes</summary>
```diff
enum PersistenceError: Error {
- case recordNotFound(MutablePersistableRecord)
+ case recordNotFound(databaseTableName: String, key: [String: DatabaseValue])
}
- class Future<Value> { }
+ class DatabaseFuture<Value> { }
protocol FetchRequest {
- func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
+ func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
}
struct AnyFetchRequest<T> : FetchRequest {
- init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?))
+ init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?))
}
-final class StatementCursor: Cursor { }
```
**Discarded deprecated methods**
```diff
extension Cursor {
- func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult>
}
struct DatabaseValue {
- func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T : DatabaseValueConvertible
- func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T : DatabaseValueConvertible
}
protocol DatabaseWriter {
- func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
}
```
</details>
## 3.7.0
Released March 9, 2019 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v3.6.2...v3.7.20)
+1 -15
View File
@@ -86,7 +86,6 @@ The ideas, in alphabetical order:
- [Linux]
- [More SQL Generation]
- [Reactive Database Observation]
- [Records: Splitting Database Encoding from Ability to Write in the Database]
- [SQL Console in the Debugger]
- [SQLCipher in a Shared App Container]
- [Static Library]
@@ -97,7 +96,7 @@ The ideas, in alphabetical order:
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
Associations can be enhanced in several ways. See the "Known Issues" and "Future Directions" chapter of the [Associations Guide](Documentation/AssociationsBasics.md)
Associations can be enhanced in several ways. See the "Known Issues" chapter of the [Associations Guide](Documentation/AssociationsBasics.md)
### CloudKit
@@ -303,19 +302,6 @@ We already have the [RxGRDB] companion library, which offers [RxSwift](https://g
We need more choices of reactive engines.
### Records: Splitting Database Encoding from Ability to Write in the Database
:baby: Starter Task :pencil: Documentation
Record types that know how to encode themselves in the database (converting themselves into columns and database values) currently are granted with [persistence methods] which can write in the database. Those record types all adopt the [PersistableRecord] protocol.
But encoding a record grants other features, such as [Record Comparison], or [Requesting Associated Records].
This is a problem: one should not have to grant a type with persistence methods, when one just needs read-only features.
The fix is to split database encoding from persistence methods. See [#426](https://github.com/groue/GRDB.swift/issues/426) for more information.
### SQL Console in the Debugger
:question: Unknown Difficulty :hammer: Tooling
@@ -25,7 +25,7 @@
<key>NSExtensionAttributes</key>
<dict>
<key>WKAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS.watchkitapp</string>
<string>com.github.groue.GRDBDemoiOS2.watchkitapp</string>
</dict>
<key>NSExtensionPointIdentifier</key>
<string>com.apple.watchkit</string>
@@ -26,7 +26,7 @@
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>WKCompanionAppBundleIdentifier</key>
<string>com.github.groue.GRDBDemoiOS</string>
<string>com.github.groue.GRDBDemoiOS2</string>
<key>WKWatchKitApp</key>
<true/>
</dict>
@@ -361,7 +361,7 @@
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0830;
LastUpgradeCheck = 0930;
LastUpgradeCheck = 1020;
ORGANIZATIONNAME = "Gwendal Roué";
TargetAttributes = {
568E5FBE1E926430002582E0 = {
@@ -383,7 +383,7 @@
};
buildConfigurationList = 56B035FE1E8D9EBE003B6DA4 /* Build configuration list for PBXProject "GRDBDemoiOS" */;
compatibilityVersion = "Xcode 3.2";
developmentRegion = English;
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
@@ -589,7 +589,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -606,7 +606,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist";
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @executable_path/../../Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp.watchkitextension;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension;
PRODUCT_NAME = "${TARGET_NAME}";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -624,7 +624,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -642,7 +642,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
IBSC_MODULE = GRDBDemoWatchOS_Extension;
INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS.watchkitapp;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp;
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = watchos;
SKIP_INSTALL = YES;
@@ -655,6 +655,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
@@ -713,6 +714,7 @@
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
@@ -769,7 +771,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
@@ -783,7 +785,7 @@
DEVELOPMENT_TEAM = AMD8W895CT;
INFOPLIST_FILE = GRDBDemoiOS/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS;
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "1020"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "1020"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -13,13 +13,11 @@ struct Player {
// Turn Player into a Codable Record.
// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Add ColumnExpression to Codable's CodingKeys so that we can use them
// as database columns.
//
// See https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
// for more information about CodingKeys.
private enum CodingKeys: String, CodingKey, ColumnExpression {
case id, name, score
// Define database columns from CodingKeys
private enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
}
// Update a player id after it has been inserted in the database.
@@ -34,11 +32,11 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
extension Player {
static func orderedByName() -> QueryInterfaceRequest<Player> {
return Player.order(CodingKeys.name)
return Player.order(Columns.name)
}
static func orderedByScore() -> QueryInterfaceRequest<Player> {
return Player.order(CodingKeys.score.desc, CodingKeys.name)
return Player.order(Columns.score.desc, Columns.name)
}
}
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -3,7 +3,7 @@ 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.25.2](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.27.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](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
@@ -15,7 +15,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```sh
cd [GRDB directory]
git checkout v3.7.0
git checkout v4.0.0
git submodule update --init SQLiteCustom/src
````
+1 -1
View File
@@ -81,7 +81,7 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
The full-text table can be fed and queried in [a regular way](../../../#full-text-search):
```swift
try db.execute("INSERT INTO documents VALUES (?)", arguments: ["..."])
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["..."])
try Document(content: "...").insert(db)
let pattern = FTS5Pattern(matchingAnyTokenIn:"...")
+11 -21
View File
@@ -172,43 +172,33 @@ extension Player {
}
```
When your record adopts the Codable protocol, you can use its [coding keys](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) as columns:
When your record adopts the Codable protocol, you can use its [coding keys](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types) to safely define database columns:
```swift
// GRDB 3
struct Player: Codable, FetchableRecord, PersistableRecord {
struct Player: Codable {
var id: Int64
var name: String
var score: Int
// Add ColumnExpression conformance
private enum CodingKeys: String, CodingKey, ColumnExpression {
case id, name, score
}
}
extension Player {
extension Player: FetchableRecord, PersistableRecord {
enum Columns {
static let id = Column(CodingKeys.id.stringValue)
static let name = Column(CodingKeys.name.stringValue)
static let score = Column(CodingKeys.score.stringValue)
}
static func filter(name: String) -> QueryInterfaceRequest<Player> {
return filter(CodingKeys.name == name)
return filter(Columns.name == name)
}
static var maximumScore: QueryInterfaceRequest<Int> {
return select(max(CodingKeys.score), as: Int.self)
return select(max(Columns.score), as: Int.self)
}
}
```
GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol whenever you define a custom column type:
```swift
struct TypedColumn: ColumnExpression {
var name: String
var sqlType: String
}
let nameColumn = TypedColumn(name: "name", sqlType: "VARCHAR")
let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
```
## If You Use Database Queues
+183
View File
@@ -0,0 +1,183 @@
Migrating From GRDB 3 to GRDB 4
===============================
GRDB 4 comes with new features, but also a few breaking changes. This guide aims at helping you upgrading your applications.
- [New requirements](#new-requirements)
- [Raw SQL](#raw-sql)
- [ValueObservation](#valueobservation)
- [Associations](#associations)
- [SQLCipher](#sqlcipher)
- [PersistenceError.recordNotFound](#persistenceerrorrecordnotfound)
### New requirements
GRDB now requires Swift 4.2+ and Xcode 10+. Swift 4.0 and 4.1 are no longer supported. Xcode 9 is no longer supported.
iOS 8 is no longer supported. The minimum iOS target is now iOS 9.
### Raw SQL
Whenever your application uses raw SQL queries or snippets, you will now always have to use the `sql` argument label:
```swift
// GRDB 3
try db.execute("INSERT INTO player (name) VALUES (?)", arguments: ["Arthur"])
let playerCount = try Int.fetchOne(db, "SELECT COUNT(*) FROM player")
// GRDB 4
try db.execute(sql: "INSERT INTO player (name) VALUES (?)", arguments: ["Arthur"])
let playerCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player")
```
This change was made necessary by the introduction of [SQL Interpolation].
### ValueObservation
[ValueObservation] has been refreshed in GRDB 4.
To guarantee asynchronous notifications, and never ever block your main thread, use the `.async(onQueue:startImmediately:)` scheduling:
```swift
// On main queue
var observation = ValueObservation.trackingAll(Player.all())
observation.scheduling = .async(onQueue: .main, startImmediately: true)
let observer = try observation.start(in: dbQueue) { (players: [Player]) in
// On main queue
print("fresh players: \(players)")s
}
// <- here "fresh players" is not printed yet.
```
In GRDB 3, this scheduling used to be named `.queue(_: startImmediately:)`.
The second breaking change is `ValueObservation.extent`, which was removed in GRDB 4. Now all observations last until the observer returned by the `start` method is deallocated.
### Associations
GRDB 4 brought a few new [associations] features:
- **Indirect associations** [HasOneThrough] and [HasManyThrough] let you define associations from a record to another through a third one. For example, they let you easily express many-to-many relations such as "a country has many citizens through its passports":
```swift
struct Country: TableRecord, EncodableRecord {
static let passports = hasMany(Passport.self)
// New!
static let citizens = hasMany(Citizen.self, through: passports, using: Passport.citizen)
var citizens: QueryInterfaceRequest<Citizen> {
return request(for: Country.citizens)
}
}
struct Passport: TableRecord {
static let citizen = belongsTo(Citizen.self)
}
struct Citizen: TableRecord {
}
let country: Country = ...
let citizens: [Citizen] = try dbQueue.read { db in
try country.citizens.fetchAll(db)
}
```
![HasManyThroughSchema](https://cdn.rawgit.com/groue/GRDB.swift/master/Documentation/Images/Associations2/HasManyThroughSchema.svg)
- **Eager loading of HasMany associations**: The new `including(all:)` method lets you load arrays or sets of associated records in a single request:
```swift
// All authors with their respective books
let request = Author.including(all: Author.books)
// This request can feed the following record:
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var books: [Book] // all associated books
}
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
```
See [Joining And Prefetching Associated Records] for more information.
- **Automatic pluralization and singularization** of association identifiers.
GRDB will automatically **pluralize** or **singularize** names in order to help you easily associate records.
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 from the battle-tested [Ruby on Rails inflections](https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-pluralize)).
However, this change may have introduced some incompatibilities with GRDB 3 associations. Check [The Structure of a Joined Request] for more information.
### SQLCipher
The integration of GRDB with SQLCipher has changed.
1. With GRDB 3, it was possible to perform a manual installation, or to use CocoaPods and the GRDBCipher pod.
With GRDB 4, CocoaPods is the only supported installation method. And the GRDBCipher pod is discontinued, replaced with GRDB.swift/SQLCipher:
```diff
-pod 'GRDBCipher'
+pod 'GRDB.swift/SQLCipher'
```
In your Swift code, you no longer import the GRDBCipher module, but GRDB:
```diff
-import GRDBCipher
+import GRDB
```
2. The default SQLCipher version which comes with GRDB 4 is now SQLCipher 4, which is incompatible with SQLCipher 3. SQLCipher 3 is still supported, though. See [Encryption] for more details.
3. The `cipherPageSize` and `kdfIterations` configuration properties are discontinued. With GRDB 4, run sql pragmas in the `prepareDatabase` property of the configuration:
```swift
var configuration = Configuration()
configuration.passphrase = "secret"
configuration.prepareDatabase = { db in
try db.execute(sql: "PRAGMA cipher_page_size = 4096")
try db.execute(sql: "PRAGMA kdf_iter = 128000")
}
let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
```
### PersistenceError.recordNotFound
PersistenceError.recordNotFound is thrown whenever a record update method does not find any database row to update. It was refactored in GRDB 4:
```swift
public enum PersistenceError: Error {
case recordNotFound(databaseTableName: String, key: [String: DatabaseValue])
}
do {
try player.updateChanges {
$0.score += 1000
}
} catch let error as PersistenceError.recordNotFound {
// Update failed because player does not exist in the database
print(error)
// prints "Key not found in table player: [id:42]"
}
```
[SQL Interpolation]: SQLInterpolation.md
[ValueObservation]: ../README.md#valueobservation
[Encryption]: ../README.md#encryption
[HasOneThrough]: AssociationsBasics.md#hasonethrough
[HasManyThrough]: AssociationsBasics.md#hasmanythrough
[PersistableRecord]: ../README.md#persistablerecord-protocol
[associations]: AssociationsBasics.md
[EncodableRecord]: ../README.md#persistablerecord-protocol
[The Structure of a Joined Request]: AssociationsBasics.md#the-structure-of-a-joined-request
[Joining And Prefetching Associated Records]: AssociationsBasics.md#joining-and-prefetching-associated-records
-2
View File
@@ -17,14 +17,12 @@ To release a new GRDB version:
- CHANGELOG.md
- Documentation/CustomSQLiteBuilds.md
- GRDB.swift.podspec
- GRDBCipher.podspec
- README.md
- Support/Info.plist
- Commit and tag
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
- Push to the master branch
- `pod trunk push --allow-warnings GRDB.swift.podspec`
- `pod trunk push --allow-warnings GRDBCipher.podspec`
- `make doc`, and update index.html in the `gh-pages` branch
- Update http://github.com/groue/WWDCCompanion
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
+418
View File
@@ -0,0 +1,418 @@
SQL Interpolation
=================
Your SQL skills are [welcomed] throughout GRDB. Yet writing raw SQL presents commonplace challenges. For example, you want to make sure your queries don't break whenever the database schema changes as you ship new versions of your application. When you inject user values in the database, you have to use statement arguments, and it is easy to make a mistake in the process.
The query below exemplifies this situation. It even contains a bug that is not quite easy to spot:
```swift
try db.execute(
sql: """
UPDATE student
SET firstName = ?, lastName = ?, department = ?, birthDate = ?,
registrationDate = ?, mainTeacherId = ?
WHERE id = ?
""",
arguments: [firstName, lastName, department, birthDate,
registrationDate, mainTeacherId])
```
SQL Interpolation is an answer to these troubles. It is available in Swift 5.
- [Introduction]
- [SQLLiteral]
- [SQL Interpolation and Record Protocols]
- [SQL Interpolation Reference]
## Introduction
**SQL Interpolation** lets you embed values in your SQL queries by wrapping them inside `\(` and `)`:
```swift
let name: String = ...
let id: Int64 = ...
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
```
SQL interpolation looks and feel just like regular [String interpolation]:
```swift
let name = "World"
print("Hello \(name)!") // prints "Hello World!"
```
The difference is that it generates valid SQL which does not suffer from syntax errors or [SQL injection]. For example, you do not need to validate input or process single quotes:
```swift
// Executes `UPDATE player SET name = 'O''Brien' WHERE id = 42`
let name = "O'Brien"
let id = 42
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
```
Under the hood, SQL interpolation generates a plain SQL string. It runs exactly as below:
```swift
try db.execute(sql: "UPDATE player SET name = ? WHERE id = ?", arguments: [name, id])
```
Plain SQL strings are indeed still available, and SQL interpolation only kicks in when you ask for it. There is a simple rule to remember:
- For plain SQL strings, use the `sql` argument label:
```swift
try db.execute(sql: "UPDATE player SET name = ? WHERE id = ?", arguments: [name, id])
```
- For SQL interpolation, use the `literal` argument label:
```swift
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
```
## SQLLiteral
**SQLLiteral** is the type that looks like a plain String, but profits from SQL interpolation:
```swift
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
try db.execute(literal: query)
```
**SQLLiteral is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
```swift
// Compiler error:
// Cannot convert value of type 'String' to expected argument type 'SQLLiteral'
let query = "UPDATE player SET name = \(name) WHERE id = \(id)" // a String
try db.execute(literal: query)
```
SQLLiteral can build your queries step by step, with regular operators and methods:
```swift
// +, +=, append
var query: SQLLiteral = "UPDATE player "
query += "SET name = \(name) "
query.append(literal: "WHERE id = \(id)")
// joined(), joined(separator:)
let components: [SQLLiteral] = [
"UPDATE player",
"SET name = \(name)",
"WHERE id = \(id)"
]
let query = components.joined(separator: " ")
```
Extract the plain SQL string from a literal:
```swift
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(query.arguments) // prints ["O'Brien", 42]
```
Build a literal from a plain SQL string:
```swift
let query = SQLLiteral(
sql: "UPDATE player SET name = ? WHERE id = ?",
arguments: [name, id])
```
SQLLiteral 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 Record Protocols
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 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:
```swift
struct Player {
var id: Int64
var name: String
var score: Int?
}
extension Player: Decodable, FetchableRecord, TableRecord {
/// Deletes all player with no score
static func deleteAllWithoutScore(_ db: Database) throws {
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
}
/// The player with a given id
static func filter(id: Int64) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
}
/// All players with the given ids
static func filter(ids: [Int64]) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
}
/// The maximum score
static func maximumScore() -> SQLRequest<Int> {
return "SELECT MAX(\(CodingKeys.score)) FROM \(self)"
}
/// All players whose score is the maximum score
static func leaders() -> SQLRequest<Player> {
return """
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
"""
}
/// A complex request
static func complexRequest() -> SQLRequest<Player> {
let query: SQLLiteral = "SELECT * FROM \(self) "
query += "JOIN \(Team.self) ON ..."
query += "GROUP BY ..."
return SQLRequest(literal: query)
}
}
```
Let's breakdown each one of those methods.
- `deleteAllWithoutScore(_:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// Deletes all player with no score
static func deleteAllWithoutScore(_ db: Database) throws {
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
}
}
```
Usage:
```swift
try dbQueue.write { db in
// DELETE FROM player WHERE score IS NULL
try Player.deleteAllWithoutScore(db)
}
```
`DELETE FROM \(self) ...` embeds the Player type itself. Since Player adopts the [TableRecord] protocol, this embeds `Player.databaseTableName` in the SQL query.
`... \(CodingKeys.score) IS NULL` embeds CodingKeys.score. This one has been synthesized by the Swift compiler because Player adopts the Decodable protocol. It embeds the column name in the SQL query.
- `filter(id:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// The player with a given id
static func filter(id: Int64) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
}
}
```
Usage:
```swift
let player = try dbQueue.read { db in
// 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]. And it profits from SQL interpolation: this is why this method can simply return an "SQL literal"".
It embeds `\(self)` (the Player type which adopts the TableRecord protocol) and `\(CodingKeys.id)` (the coding key synthesized by the Decodable protocol), and `\(id)` (a [value]).
- `filter(ids:)`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// All players with the given ids
static func filter(ids: [Int64]) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
}
}
```
Usage:
```swift
let players = try dbQueue.read { db in
// SELECT * player WHERE id IN (1, 2, 3)
try Player.filter(ids: [1, 2, 3]).fetchAll(db) // [Player]
}
```
It embeds `\(ids)`, an array of ids. All [value] sequences are supported (arrays, sets, etc.) Empty sequences are supported as well, with both `IN` and `NOT IN` SQL operators.
- `maximumScore()`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// The maximum score
static func maximumScore() -> SQLRequest<Int> {
return "SELECT MAX(\(CodingKeys.score)) FROM \(self)"
}
}
```
Usage:
```swift
let maximumScore = try dbQueue.read { db in
// SELECT MAX(score) FROM player
try Player.maximumScore().fetchOne(db) // Int?
}
```
The result is `SQLRequest<Int>`, unlike previous requests of type `SQLRequest<Player>`. SQLRequest accepts any fetchable type (database [row], simple [value], or custom [record]).
- `leaders()`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// All players whose score is the maximum score
static func leaders() -> SQLRequest<Player> {
return """
SELECT * FROM \(self)
WHERE \(CodingKeys.score) = \(maximumScore())
"""
}
}
```
Usage:
```swift
let leaders = try dbQueue.read { db in
// SELECT * FROM player
// WHERE score = (SELECT MAX(score) FROM player)
try Player.leaders().fetchAll(db) // [Player]
}
```
This request embeds `\(maximumScore())`, the `SQLRequest<Int>` returned by the `maximumScore` method. After values, coding keys, and types that adopt the TableRecord protocol, this ends our quick tour of things you can embed between `\(` and `)`. Check out the [SQL Interpolation Reference] for the full list of supported interpolations.
- `complexRequest()`
```swift
extension Player: Decodable, FetchableRecord, TableRecord {
/// A complex request
static func complexRequest() -> SQLRequest<Player> {
let query: SQLLiteral = "SELECT * FROM \(self) "
query += "JOIN \(Team.self) ON ..."
query += "GROUP BY ..."
return SQLRequest(literal: query)
}
}
```
This last request shows how to build an SQLRequest from an [SQLLiteral]. You will need SQLLiteral when the request can not be expressed in a single "SQL literal".
## SQL Interpolation Reference
This chapter lists all kinds of supported interpolations.
- Types adopting the [TableRecord] protocol:
```swift
// SELECT * FROM player
extension Player: TableRecord { }
"SELECT * FROM \(Player.self)"
// INSERT INTO player ...
let player: Player = ...
"INSERT INTO \(tableOf: player) ..."
```
- [Expressions] and [values]:
```swift
// SELECT name FROM player
"SELECT \(Column("name")) FROM player"
// SELECT (score + 100) AS points FROM player
let bonus = 100
"SELECT \(Column("score") + bonus) AS points FROM player"
// SELECT (score + 100) AS points FROM player
"SELECT (score + \(bonus)) AS points FROM player"
```
- Coding keys:
```swift
// SELECT name FROM player
"SELECT \(CodingKeys.name) FROM player"
```
- Sequences:
```swift
// SELECT * FROM player WHERE id IN (1, 2, 3)
let ids = [1, 2, 3]
"SELECT * FROM player WHERE id IN \(ids)"
```
- Orderings:
```swift
// SELECT * FROM player ORDER BY name DESC
"SELECT * FROM player WHERE id IN \(Column("name").desc)"
```
- SQLRequest:
```swift
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
"SELECT * FROM player WHERE score = \(subQuery)"
```
- SQLLiteral:
```swift
// SELECT * FROM player WHERE name = 'O''Brien'
let condition: SQLLiteral = "name = \("O'Brien")"
"SELECT * FROM player WHERE \(literal: condition)"
```
- Plain SQL strings and eventual arguments:
```swift
// SELECT * FROM player
"SELECT * FROM \(sql: "player")"
// SELECT * FROM player WHERE name = 'O''Brien'
"SELECT * FROM player WHERE \(sql: "name = ?", arguments: ["O'Brien"])"
```
[Introduction]: #introduction
[SQLLiteral]: #sqlliteral
[SQL Interpolation and Record Protocols]: #sql-interpolation-and-record-protocols
[SQL Interpolation Reference]: #sql-interpolation-reference
[String interpolation]: https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID292
[SQL injection]: ../README.md#avoiding-sql-injection
[record protocols]: ../README.md#record-protocols-overview
[FetchableRecord]: ../README.md#fetchablerecord-protocol
[TableRecord]: ../README.md#tablerecord-protocol
[Decodable]: ../README.md#codable-records
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[value]: ../README.md#values
[values]: ../README.md#values
[request types]: ../README.md#custom-requests
[row]: ../README.md#row-queries
[record]: ../README.md#records
[Expressions]: ../README.md#expressions
[welcomed]: ../README.md#sqlite-api
[SE-0228 Fix ExpressibleByStringInterpolation]: https://github.com/apple/swift-evolution/blob/master/proposals/0228-fix-expressiblebystringinterpolation.md
+40 -28
View File
@@ -69,7 +69,7 @@ By adopting the [FetchableRecord] protocol, places can be loaded from SQL reques
```swift
extension Place: FetchableRecord { ... }
let places = try Place.fetchAll(db, "SELECT * FROM place") // [Place]
let places = try Place.fetchAll(db, sql: "SELECT * FROM place") // [Place]
```
Add the [TableRecord] protocol, and SQL requests are generated for you:
@@ -177,9 +177,14 @@ For further information about GRDB concurrency, check its detailed [Concurrency
SQL is a weird language. Born in the 70s, easy to [misuse](https://xkcd.com/327/), feared by some developers, despised by others, and yet wonderfully concise and powerful.
GRDB [query interface] and [associations] can generate SQL for you:
GRDB [records], [query interface] and [associations] can generate SQL for you:
```swift
// UPDATE player SET score = 950 WHERE id = 42
try player.updateChanges {
$0.score += 10
}
// SELECT * FROM player ORDER BY score DESC LIMIT 10
let bestPlayers: [Player] = try Player
.order(scoreColumn.desc)
@@ -202,19 +207,47 @@ let bookInfos: [BookInfo] = BookInfo.fetchAll(db, request)
But you can always switch to SQL when you want to:
```swift
let bestPlayers: [Player] = try Player.fetchAll(db, """
try db.execute(
sql: "UPDATE player SET score = ? WHERE id = ?",
arguments: [950, 42])
let bestPlayers: [Player] = try Player.fetchAll(db, sql: """
SELECT * FROM player ORDER BY score DESC LIMIT 10
""")
let maximumScore: Int? = try Int.fetchOne(db, """
let maximumScore: Int? = try Int.fetchOne(db, sql: """
SELECT MAX(score) FROM player
""")
```
With Swift 5, you can profit from **SQL interpolation**. It lets you build SQL queries from natural looking strings, but without any risk of syntax error or [SQL injection](https://xkcd.com/327/):
```swift
try db.execute(literal: "UPDATE player SET score = \(score) WHERE id = \(id)")
extension Player {
static func filter(name: String) -> SQLRequest<Player> {
return "SELECT * FROM \(self) WHERE \(CodingKeys.name) = \(name)"
}
}
let player = try Player.filter(name: "Arthur O'Brien").fetchOne(db)
```
Custom SQL requests as the one above are welcome in database observation tools like [ValueObservation] and [RxGRDB]:
```swift
Player.filter(name: "Arthur O'Brien").rx
.fetchOne(in: dbQueue)
.subscribe(onNext: { (player: Player?) in
print("Player has changed")
})
```
Power users can also consume complex joined SQL queries into handy record values, by *adapting* raw database rows to the decoded records (see [Joined Queries Support](#../README.md#joined-queries-support)):
```swift
let bookInfos: [BookInfo] = SQLRequest<BookInfo>("""
let bookInfos: [BookInfo] = SQLRequest<BookInfo>(sql: """
SELECT book.*, author.*
FROM book
LEFT JOIN author ON author.id = book.authorId
@@ -232,7 +265,7 @@ let bookInfos: [BookInfo] = SQLRequest<BookInfo>("""
In performance-critical sections, you may want to deal with raw database rows, and fetch [lazy cursors](../README.md#cursors) instead of arrays:
```swift
let rows = try Row.fetchCursor(db, "SELECT id, name, score FROM player")
let rows = try Row.fetchCursor(db, sql: "SELECT id, name, score FROM player")
while let row = try rows.next() {
let id: Int64 = row[0]
let name: String = row[1]
@@ -240,28 +273,6 @@ while let row = try rows.next() {
}
```
When you feel like your code clarity would be enhanced by hiding your custom SQL in a dedicated method, you can build [custom requests](../README.md#custom-requests):
```swift
extension Player {
static func customRequest(...) -> SQLRequest<Player> {
return SQLRequest<Player>("SELECT ...", arguments: ...)
}
}
let players = try Player.customRequest(...).fetchAll(db)
```
Those custom requests are welcome in database observation tools like [ValueObservation] and [RxGRDB]:
```swift
Player.customRequest(...).rx
.fetchAll(in: dbQueue)
.subscribe(onNext: { players: [Player] in
print("Players have changed")
})
```
---
If this little tour of GRDB has convinced you, the real trip starts here: [GRDB].
@@ -294,3 +305,4 @@ Happy GRDB! :gift:
[query interface]: ../README.md#the-query-interface
[associations]: AssociationsBasics.md
[Codable records]: ../README.md#codable-records
[records]: ../README.md#records
+20 -6
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '3.7.0'
s.version = '4.0.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
@@ -9,12 +9,26 @@ Pod::Spec.new do |s|
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
s.module_name = 'GRDB'
s.ios.deployment_target = '8.0'
s.ios.deployment_target = '9.0'
s.osx.deployment_target = '10.9'
s.watchos.deployment_target = '2.0'
s.source_files = 'GRDB/**/*.swift', 'Support/*.h'
s.module_map = 'Support/module.modulemap'
s.framework = 'Foundation'
s.library = 'sqlite3'
s.default_subspec = 'standard'
s.subspec 'standard' do |ss|
ss.source_files = 'GRDB/**/*.swift', 'Support/*.h'
ss.framework = 'Foundation'
ss.library = 'sqlite3'
end
s.subspec 'SQLCipher' do |ss|
ss.source_files = 'GRDB/**/*.swift', 'Support/*.h'
ss.framework = 'Foundation'
ss.dependency 'SQLCipher', '>= 3.4.0'
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
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "1020"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "1020"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "1020"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -10,7 +10,6 @@
buildConfiguration = "Release"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
@@ -31,7 +30,6 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
language = ""
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "1020"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0930"
LastUpgradeVersion = "1020"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
-6
View File
@@ -10,9 +10,6 @@
<FileRef
location = "group:JSONSynchronization.playground">
</FileRef>
<FileRef
location = "group:Record.playground">
</FileRef>
<FileRef
location = "group:TransactionObserver.playground">
</FileRef>
@@ -50,9 +47,6 @@
<FileRef
location = "group:GRDBCustom.xcodeproj">
</FileRef>
<FileRef
location = "group:GRDBCipher.xcodeproj">
</FileRef>
<FileRef
location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj">
</FileRef>
+17 -14
View File
@@ -2,6 +2,8 @@ import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -82,21 +84,22 @@ public struct Configuration {
/// Default: nil
public var passphrase: String?
/// The cipher_page_size setting for the encrypted database.
///
/// See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_page_size
///
/// Default: 1024 - this corresponds to the default used by SQLCipher 3
public var cipherPageSize: Int = 1024
/// The kdf_iter setting for the encrypted database.
///
/// See https://www.zetetic.net/sqlcipher/sqlcipher-api/#kdf_iter
///
/// Default: 64000 - this corresponds to the default used by SQLCipher 3
public var kdfIterations: Int = 64000
#endif
/// If set, allows custom configuration to be run every time
/// a new connection is opened.
///
/// This block is run after the Database's connection has opened, but
/// before that connection has been made available to any read/write
/// API's.
///
/// For example:
///
/// var config = Configuration()
/// config.prepareDatabase = { db in
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
/// }
public var prepareDatabase: ((Database) throws -> Void)?
// MARK: - Transactions
+5 -9
View File
@@ -14,8 +14,9 @@
extension Array {
/// Creates an array containing the elements of a cursor.
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let strings = try Array(cursor) // ["foo", "bar"]
@inlinable
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
while let element = try cursor.next() {
@@ -36,7 +37,7 @@ extension Sequence {
extension Set {
/// Creates a set containing the elements of a cursor.
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'foo'")
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'foo'")
/// let strings = try Set(cursor) // ["foo"]
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
@@ -111,7 +112,7 @@ extension Cursor {
/// Returns a cursor of pairs (n, x), where n represents a consecutive
/// integer starting at zero, and x represents an element of the cursor.
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let c = cursor.enumerated()
/// while let (n, x) = c.next() {
/// print("\(n): \(x)")
@@ -144,11 +145,6 @@ extension Cursor {
return map(transform).filter { $0 != nil }.map { $0! }
}
@available(*, deprecated, renamed: "compactMap")
public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> {
return compactMap(transform)
}
/// Returns a cursor that skips any initial elements that satisfy
/// `predicate`.
///
@@ -600,7 +596,7 @@ public final class DropWhileCursor<Base: Cursor> : Cursor {
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
/// on a cursor:
///
/// let cursor = try String.fetchCursor(db, "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let c = cursor.enumerated()
/// while let (n, x) = c.next() {
/// print("\(n): \(x)")
+9 -18
View File
@@ -1,5 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -171,13 +173,13 @@ extension Database {
}
let indexes = try Row
.fetchAll(self, "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
.fetchAll(self, sql: "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
.map { row -> IndexInfo in
// [seq:0 name:"index" unique:0 origin:"c" partial:0]
let indexName: String = row[1]
let unique: Bool = row[2]
let columns = try Row
.fetchAll(self, "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.fetchAll(self, sql: "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
.map { row -> (Int, String) in
// [seqno:0 cid:2 name:"column"]
(row[0] as Int, row[2] as String)
@@ -213,7 +215,7 @@ extension Database {
var rawForeignKeys: [(destinationTable: String, mapping: [(origin: String, destination: String?, seq: Int)])] = []
var previousId: Int? = nil
for row in try Row.fetchAll(self, "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
for row in try Row.fetchAll(self, sql: "PRAGMA foreign_key_list(\(tableName.quotedDatabaseIdentifier))") {
// row = [id:0 seq:0 table:"parents" from:"parentId" to:"id" on_update:"..." on_delete:"..." match:"..."]
let id: Int = row[0]
let seq: Int = row[1]
@@ -320,7 +322,7 @@ extension Database {
}
}
let columns = try ColumnInfo
.fetchAll(self, "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
.fetchAll(self, sql: "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))")
.sorted(by: { $0.cid < $1.cid })
guard columns.count > 0 else {
throw DatabaseError(message: "no such table: \(tableName)")
@@ -386,7 +388,7 @@ public struct ColumnInfo : FetchableRecord {
///
/// For example:
///
/// try db.execute("""
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY,
/// name TEXT DEFAULT 'Anonymous',
@@ -579,7 +581,7 @@ struct SchemaInfo: Equatable {
private var objects: Set<SchemaObject>
init(_ db: Database) throws {
objects = try Set(SchemaObject.fetchCursor(db, """
objects = try Set(SchemaObject.fetchCursor(db, sql: """
SELECT type, name, tbl_name, sql, 0 AS isTemporary FROM sqlite_master \
UNION \
SELECT type, name, tbl_name, sql, 1 FROM sqlite_temp_master
@@ -597,7 +599,7 @@ struct SchemaInfo: Equatable {
/// Returns the canonical name of the object:
///
/// try db.execute("CREATE TABLE FooBar (...)")
/// try db.execute(sql: "CREATE TABLE FooBar (...)")
/// try db.schema().canonicalName("foobar", ofType: .table) // "FooBar"
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
let name = name.lowercased()
@@ -610,16 +612,5 @@ struct SchemaInfo: Equatable {
var tbl_name: String?
var sql: String?
var isTemporary: Bool
#if !swift(>=4.2)
var hashValue: Int {
var hash = type.hashValue
hash ^= name.hashValue
hash ^= (tbl_name?.hashValue ?? 0)
hash ^= (sql?.hashValue ?? 0)
hash ^= isTemporary.hashValue
return hash
}
#endif
}
}
+119 -82
View File
@@ -1,4 +1,11 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
extension Database {
@@ -6,20 +13,20 @@ extension Database {
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
/// - parameter sql: An SQL query.
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeSelectStatement(_ sql: String) throws -> SelectStatement {
return try makeSelectStatement(sql, prepFlags: 0)
public func makeSelectStatement(sql: String) throws -> SelectStatement {
return try makeSelectStatement(sql: sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
@@ -28,13 +35,13 @@ extension Database {
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeSelectStatement(_ sql: String, prepFlags: Int32) throws -> SelectStatement {
func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement {
return try SelectStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
/// let statement = try db.cachedSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
///
@@ -44,31 +51,31 @@ extension Database {
/// - parameter sql: An SQL query.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func cachedSelectStatement(_ sql: String) throws -> SelectStatement {
public func cachedSelectStatement(sql: String) throws -> SelectStatement {
return try publicStatementCache.selectStatement(sql)
}
/// Returns a cached statement that does not conflict with user's cached statements.
func internalCachedSelectStatement(_ sql: String) throws -> SelectStatement {
func internalCachedSelectStatement(sql: String) throws -> SelectStatement {
return try internalStatementCache.selectStatement(sql)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// - parameter sql: An SQL query.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement {
return try makeUpdateStatement(sql, prepFlags: 0)
public func makeUpdateStatement(sql: String) throws -> UpdateStatement {
return try makeUpdateStatement(sql: sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)", prepFlags: 0)
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)", prepFlags: 0)
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
@@ -77,13 +84,13 @@ extension Database {
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
func makeUpdateStatement(_ sql: String, prepFlags: Int32) throws -> UpdateStatement {
func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement {
return try UpdateStatement.prepare(sql: sql, prepFlags: prepFlags, in: self)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedUpdateStatement("INSERT INTO player (name) VALUES (?)")
/// let statement = try db.cachedUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
@@ -93,97 +100,121 @@ extension Database {
/// - parameter sql: An SQL query.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
public func cachedUpdateStatement(sql: String) throws -> UpdateStatement {
return try publicStatementCache.updateStatement(sql)
}
/// Returns a cached statement that does not conflict with user's cached statements.
func internalCachedUpdateStatement(_ sql: String) throws -> UpdateStatement {
func internalCachedUpdateStatement(sql: String) throws -> UpdateStatement {
return try internalStatementCache.updateStatement(sql)
}
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try db.execute(
/// "INSERT INTO player (name) VALUES (:name)",
/// sql: "INSERT INTO player (name) VALUES (:name)",
/// arguments: ["name": "Arthur"])
///
/// try db.execute("""
/// try db.execute(sql: """
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// """, arguments; ['Arthur', 'Barbara', 'Craig'])
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
///
/// This method may throw a DatabaseError.
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws {
public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws {
try execute(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Executes one or several SQL statements, separated by semi-colons.
///
/// try db.execute(literal: SQLLiteral(
/// sql: "INSERT INTO player (name) VALUES (:name)",
/// arguments: ["name": "Arthur"]))
///
/// try db.execute(literal: SQLLiteral(sql: """
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// """, arguments: ["Arthur", "Barbara", "O'Brien"]))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// try db.execute(literal: """
/// INSERT INTO player (name) VALUES (\("Arthur"));
/// INSERT INTO player (name) VALUES (\("Barbara"));
/// INSERT INTO player (name) VALUES (\("O'Brien"));
/// """)
///
/// This method may throw a DatabaseError.
///
/// - parameter sqlLiteral: An SQLLiteral.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(literal sqlLiteral: SQLLiteral) throws {
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
// It adds support for arguments, and the tricky part is to consume
// arguments as statements are executed.
//
// Here we build two functions:
// - consumeArguments returns arguments for a statement
// - validateRemainingArguments validates the remaining arguments, after
// all statements have been executed, in the same way
// as Statement.validate(arguments:)
// This job is performed by StatementArguments.extractBindings(forStatement:allowingRemainingValues:)
//
// And before we return, we'll check that all arguments were consumed.
var arguments = arguments ?? StatementArguments()
var arguments = sqlLiteral.arguments
let initialValuesCount = arguments.values.count
let consumeArguments = { (statement: UpdateStatement) throws -> StatementArguments in
let bindings = try arguments.consume(statement, allowingRemainingValues: true)
return StatementArguments(bindings)
}
let validateRemainingArguments = {
if !arguments.values.isEmpty {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)")
}
}
// Iterate SQL statements
let sqlCodeUnits = sql.utf8CString
try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let sqlStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
let sqlEnd = sqlStart + sqlCodeUnits.count
// Build a C string (SQLite wants that), and execute SQL statements one
// after the other.
try sqlLiteral.sql.utf8CString.withUnsafeBufferPointer { buffer in
guard let sqlStart = buffer.baseAddress else { return }
let sqlEnd = sqlStart + buffer.count // past \0
var statementStart = sqlStart
while statementStart < sqlEnd - 1 {
while statementStart < sqlEnd {
var statementEnd: UnsafePointer<Int8>? = nil
let nextStatement: UpdateStatement?
// Compile
do {
let statement: UpdateStatement
// Compile
do {
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
authorizer = statementCompilationAuthorizer
defer { authorizer = nil }
statement = try UpdateStatement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: 0,
authorizer: statementCompilationAuthorizer)
}
let statementCompilationAuthorizer = StatementCompilationAuthorizer()
authorizer = statementCompilationAuthorizer
defer { authorizer = nil }
// Execute
let arguments = try consumeArguments(statement)
statement.unsafeSetArguments(arguments)
try statement.execute()
// Next
statementStart = statementEnd!
} catch is EmptyStatementError {
// End
nextStatement = try UpdateStatement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: 0,
authorizer: statementCompilationAuthorizer)
}
guard let statement = nextStatement else {
// End of SQL string
break
}
// Extract statement arguments
let bindings = try arguments.extractBindings(forStatement: statement, allowingRemainingValues: true)
// unsafe is OK because we just extracted the correct number of arguments
statement.unsafeSetArguments(StatementArguments(bindings))
// Execute
try statement.execute()
// Next
statementStart = statementEnd!
}
}
// Force arguments validity: it is a programmer error to provide
// arguments that do not match the statement.
try! validateRemainingArguments() // throws if there are remaining arguments.
// Check that all arguments were consumed: it is a programmer error to
// provide arguments that do not match the statement.
if arguments.values.isEmpty == false {
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "wrong number of statement arguments: \(initialValuesCount)")
}
}
}
@@ -248,12 +279,17 @@ struct StatementCache {
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
//
// TODO: use SQLITE_PREPARE_PERSISTENT if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let statement = try db.makeSelectStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
let statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement = try db.makeSelectStatement(sql)
let statement: SelectStatement
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
// SQLite 3.24.0 or more
statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
} else {
// SQLite 3.19.3 or less
statement = try db.makeSelectStatement(sql: sql)
}
#endif
selectStatements[sql] = statement
return statement
@@ -273,12 +309,17 @@ struct StatementCache {
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
//
// TODO: use SQLITE_PREPARE_PERSISTENT if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *)
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let statement = try db.makeUpdateStatement(sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
let statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement = try db.makeUpdateStatement(sql)
let statement: UpdateStatement
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
// SQLite 3.24.0 or more
statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
} else {
// SQLite 3.19.3 or less
statement = try db.makeUpdateStatement(sql: sql)
}
#endif
updateStatements[sql] = statement
return statement
@@ -290,14 +331,10 @@ struct StatementCache {
}
mutating func remove(_ statement: SelectStatement) {
if let index = selectStatements.index(where: { $0.1 === statement }) {
selectStatements.remove(at: index)
}
selectStatements.removeFirst { $0.value === statement }
}
mutating func remove(_ statement: UpdateStatement) {
if let index = updateStatements.index(where: { $0.1 === statement }) {
updateStatements.remove(at: index)
}
updateStatements.removeFirst { $0.value === statement }
}
}
+95 -126
View File
@@ -1,6 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -151,7 +153,7 @@ public final class Database {
/// The list of compile options used when building SQLite
static let sqliteCompileOptions: Set<String> = DatabaseQueue().inDatabase {
try! Set(String.fetchCursor($0, "PRAGMA COMPILE_OPTIONS"))
try! Set(String.fetchCursor($0, sql: "PRAGMA COMPILE_OPTIONS"))
}
// MARK: - Private properties
@@ -166,28 +168,9 @@ public final class Database {
// MARK: - Initializer
init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws {
let sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
do {
try Database.activateExtendedCodes(sqliteConnection)
#if SQLITE_HAS_CODEC
try Database.validateSQLCipher(sqliteConnection)
if let passphrase = configuration.passphrase {
try Database.set(passphrase: passphrase, forConnection: sqliteConnection)
try Database.set(cipherPageSize: configuration.cipherPageSize, forConnection: sqliteConnection)
try Database.set(kdfIterations: configuration.kdfIterations, forConnection: sqliteConnection)
}
#endif
try Database.validateDatabaseFormat(sqliteConnection)
} catch {
Database.closeConnection(sqliteConnection)
throw error
}
self.sqliteConnection = sqliteConnection
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
self.configuration = configuration
self.schemaCache = schemaCache
configuration.SQLiteConnectionDidOpen?()
}
deinit {
@@ -221,91 +204,6 @@ extension Database {
}
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
}
private static func activateExtendedCodes(_ sqliteConnection: SQLiteConnection) throws {
let code = sqlite3_extended_result_codes(sqliteConnection, 1)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
#if SQLITE_HAS_CODEC
private static func validateSQLCipher(_ sqliteConnection: SQLiteConnection) 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.
var sqliteStatement: SQLiteStatement? = nil
let code = sqlite3_prepare_v2(sqliteConnection, "PRAGMA cipher_version", -1, &sqliteStatement, nil)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
defer {
sqlite3_finalize(sqliteStatement)
}
if sqlite3_step(sqliteStatement) != SQLITE_ROW || (sqlite3_column_text(sqliteStatement, 0) == 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
""")
}
}
private static func set(passphrase: String, forConnection sqliteConnection: SQLiteConnection) throws {
let data = passphrase.data(using: .utf8)!
let code = data.withUnsafeBytes { bytes in
sqlite3_key(sqliteConnection, bytes, Int32(data.count))
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
private static func set(cipherPageSize: Int, forConnection sqliteConnection: SQLiteConnection) throws {
var sqliteStatement: SQLiteStatement? = nil
var code = sqlite3_prepare_v2(sqliteConnection, "PRAGMA cipher_page_size = \(cipherPageSize)", -1, &sqliteStatement, nil)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
defer {
sqlite3_finalize(sqliteStatement)
}
code = sqlite3_step(sqliteStatement)
if code != SQLITE_DONE {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
private static func set(kdfIterations: Int, forConnection sqliteConnection: SQLiteConnection) throws {
var sqliteStatement: SQLiteStatement? = nil
var code = sqlite3_prepare_v2(sqliteConnection, "PRAGMA kdf_iter = \(kdfIterations)", -1, &sqliteStatement, nil)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
defer {
sqlite3_finalize(sqliteStatement)
}
code = sqlite3_step(sqliteStatement)
if code != SQLITE_DONE {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
#endif
private static func validateDatabaseFormat(_ sqliteConnection: SQLiteConnection) throws {
// Users are surprised when they open a picture as a database and
// see no error (https://github.com/groue/GRDB.swift/issues/54).
//
// So let's fail early if file is not a database, or encrypted with
// another passphrase.
let code = sqlite3_exec(sqliteConnection, "SELECT * FROM sqlite_master LIMIT 1", nil, nil, nil)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
}
extension Database {
@@ -321,6 +219,21 @@ extension Database {
setupDefaultFunctions()
setupDefaultCollations()
observationBroker.installCommitAndRollbackHooks()
try activateExtendedCodes()
#if SQLITE_HAS_CODEC
try validateSQLCipher()
if let passphrase = configuration.passphrase {
try setCipherPassphrase(passphrase)
}
#endif
// Last step before we can start accessing the database.
// This is the opportunity to run SQLCipher configuration
// pragmas such as cipher_page_size, for example.
try configuration.prepareDatabase?(self)
try validateFormat()
configuration.SQLiteConnectionDidOpen?()
}
private func setupTrace() {
@@ -375,11 +288,11 @@ extension Database {
db.configuration.trace!(sql)
return SQLITE_OK
}
private func setupForeignKeys() throws {
// Foreign keys are disabled by default with SQLite3
if configuration.foreignKeysEnabled {
try execute("PRAGMA foreign_keys = ON")
try execute(sql: "PRAGMA foreign_keys = ON")
}
}
@@ -411,7 +324,7 @@ extension Database {
add(function: .lowercase)
add(function: .uppercase)
if #available(iOS 9.0, OSX 10.11, watchOS 3.0, *) {
if #available(OSX 10.11, watchOS 3.0, *) {
add(function: .localizedCapitalize)
add(function: .localizedLowercase)
add(function: .localizedUppercase)
@@ -425,6 +338,56 @@ extension Database {
add(collation: .localizedCompare)
add(collation: .localizedStandardCompare)
}
private func activateExtendedCodes() throws {
let code = sqlite3_extended_result_codes(sqliteConnection, 1)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
#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
""")
}
}
private func setCipherPassphrase(_ passphrase: String) throws {
let data = passphrase.data(using: .utf8)!
#if swift(>=5.0)
let code = data.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count))
}
#else
let code = data.withUnsafeBytes {
sqlite3_key(sqliteConnection, $0, Int32(data.count))
}
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
}
}
#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).
//
// So let's fail early if file is not a database, or encrypted with
// another passphrase.
try makeSelectStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next()
}
}
extension Database {
@@ -450,7 +413,7 @@ extension Database {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, *) {
if #available(OSX 10.10, OSXApplicationExtension 10.10, *) {
closeConnection_v2(sqliteConnection, sqlite3_close_v2)
} else {
closeConnection_v1(sqliteConnection)
@@ -515,7 +478,7 @@ extension Database {
/// return int + 1
/// }
/// db.add(function: fn)
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
public func add(function: DatabaseFunction) {
functions.update(with: function)
function.install(in: self)
@@ -538,7 +501,7 @@ extension Database {
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// db.add(collation: collation)
/// try db.execute("CREATE TABLE files (name TEXT COLLATE localized_standard")
/// try db.execute(sql: "CREATE TABLE files (name TEXT COLLATE localized_standard")
public func add(collation: DatabaseCollation) {
collations.update(with: collation)
let collationPointer = Unmanaged.passUnretained(collation).toOpaque()
@@ -581,8 +544,8 @@ extension Database {
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
// Assume those pragmas never fail
try! internalCachedUpdateStatement("PRAGMA query_only = 1").execute()
defer { try! internalCachedUpdateStatement("PRAGMA query_only = 0").execute() }
try! internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute()
defer { try! internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute() }
return try block()
}
}
@@ -595,7 +558,7 @@ extension Database {
///
/// try dbQueue.inDatabase do {
/// try db.inTransaction {
/// try db.execute("INSERT ...")
/// try db.execute(sql: "INSERT ...")
/// return .commit
/// }
/// }
@@ -655,7 +618,7 @@ extension Database {
///
/// try dbQueue.inDatabase do {
/// try db.inSavepoint {
/// try db.execute("INSERT ...")
/// try db.execute(sql: "INSERT ...")
/// return .commit
/// }
/// }
@@ -691,7 +654,7 @@ extension Database {
// using unique savepoint names. User could still mess with them
// with raw SQL queries, but let's assume that it is unlikely that
// the user uses "grdb" as a savepoint name.
try execute("SAVEPOINT grdb")
try execute(sql: "SAVEPOINT grdb")
// Now that savepoint has begun, we'll rollback in case of error.
// But we'll throw the first caught error, so that user knows
@@ -702,7 +665,7 @@ extension Database {
let completion = try block()
switch completion {
case .commit:
try execute("RELEASE SAVEPOINT grdb")
try execute(sql: "RELEASE SAVEPOINT grdb")
assert(!topLevelSavepoint || !isInsideTransaction)
needsRollback = false
case .rollback:
@@ -721,8 +684,8 @@ extension Database {
// Rollback, and release the savepoint.
// Rollback alone is not enough to clear the savepoint from
// the SQLite savepoint stack.
try execute("ROLLBACK TRANSACTION TO SAVEPOINT grdb")
try execute("RELEASE SAVEPOINT grdb")
try execute(sql: "ROLLBACK TRANSACTION TO SAVEPOINT grdb")
try execute(sql: "RELEASE SAVEPOINT grdb")
}
} catch {
if firstError == nil {
@@ -745,7 +708,7 @@ extension Database {
/// - throws: The error thrown by the block.
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
let kind = kind ?? configuration.defaultTransactionKind
try execute("BEGIN \(kind.rawValue) TRANSACTION")
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
assert(isInsideTransaction)
}
@@ -795,7 +758,7 @@ extension Database {
// UPDATE ...
// Here the change is not visible by GRDB user
try beginTransaction(.deferred)
try internalCachedSelectStatement("SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
try internalCachedSelectStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
}
/// Rollbacks a database transaction.
@@ -841,14 +804,14 @@ extension Database {
// should be exposed to the library user.
SchedulingWatchdog.preconditionValidQueue(self) // guard sqlite3_get_autocommit
if sqlite3_get_autocommit(sqliteConnection) == 0 {
try execute("ROLLBACK TRANSACTION")
try execute(sql: "ROLLBACK TRANSACTION")
}
assert(!isInsideTransaction)
}
/// Commits a database transaction.
public func commit() throws {
try execute("COMMIT TRANSACTION")
try execute(sql: "COMMIT TRANSACTION")
assert(!isInsideTransaction)
}
}
@@ -924,9 +887,15 @@ extension Database {
// > 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 data = passphrase.data(using: .utf8)!
let code = data.withUnsafeBytes { bytes in
sqlite3_rekey(sqliteConnection, bytes, Int32(data.count))
#if swift(>=5.0)
let code = data.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
}
#else
let code = data.withUnsafeBytes {
sqlite3_rekey(sqliteConnection, $0, Int32(data.count))
}
#endif
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: lastErrorMessage)
}
+3 -8
View File
@@ -1,6 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -16,7 +18,7 @@ public final class DatabaseCollation {
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// db.add(collation: collation)
/// try db.execute("CREATE TABLE file (name TEXT COLLATE localized_standard")
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard")
///
/// - parameters:
/// - name: The function name.
@@ -39,17 +41,10 @@ extension DatabaseCollation: Hashable {
// implies hash equality) is thus non trivial. But it's not that
// important, since this hashValue is only used when one adds
// or removes a collation from a database connection.
#if swift(>=4.2)
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(0)
}
#else
/// :nodoc:
public var hashValue: Int {
return 0
}
#endif
/// Two collations are equal if they share the same name (case insensitive)
/// :nodoc:
+3 -1
View File
@@ -1,6 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -147,7 +149,7 @@ extension ResultCode {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
return String(cString: sqlite3_errstr(rawValue))
#else
if #available(iOS 8.2, OSX 10.10, OSXApplicationExtension 10.10, iOSApplicationExtension 8.2, *) {
if #available(OSX 10.10, OSXApplicationExtension 10.10, *) {
return String(cString: sqlite3_errstr(rawValue))
} else {
return nil
+22 -21
View File
@@ -1,5 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -27,7 +29,7 @@ public final class DatabaseFunction: Hashable {
/// return int + 1
/// }
/// db.add(function: fn)
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
///
/// - parameters:
/// - name: The function name.
@@ -73,10 +75,10 @@ public final class DatabaseFunction: Hashable {
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
/// dbQueue.add(function: fn)
/// try dbQueue.write { db in
/// try db.execute("CREATE TABLE test(i)")
/// try db.execute("INSERT INTO test(i) VALUES (1)")
/// try db.execute("INSERT INTO test(i) VALUES (2)")
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
/// try db.execute(sql: "CREATE TABLE test(i)")
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
/// }
///
/// - parameters:
@@ -262,7 +264,7 @@ public final class DatabaseFunction: Hashable {
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!, count: stride)
if aggregateContextBufferP.contains(where: { $0 != 0 }) {
if aggregateContextBufferP.contains(where: { $0 != 0 }) { // TODO: This testt looks weird. Review.
// Buffer contains non-null pointer: load aggregate context
let aggregateContextP = aggregateContextBufferP.baseAddress!.assumingMemoryBound(to: Unmanaged<AggregateContext>.self)
return aggregateContextP.pointee
@@ -275,8 +277,8 @@ public final class DatabaseFunction: Hashable {
// retain and store in SQLite's buffer
let aggregateContextU = Unmanaged.passRetained(aggregateContext)
var aggregateContextP = aggregateContextU.toOpaque()
withUnsafeBytes(of: &aggregateContextP) {
let aggregateContextP = aggregateContextU.toOpaque()
withUnsafeBytes(of: aggregateContextP) {
aggregateContextBufferP.copyMemory(from: $0)
}
return aggregateContextU
@@ -294,9 +296,15 @@ public final class DatabaseFunction: Hashable {
case .string(let string):
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
case .blob(let data):
data.withUnsafeBytes { bytes in
sqlite3_result_blob(sqliteContext, bytes, Int32(data.count), SQLITE_TRANSIENT)
#if swift(>=5.0)
data.withUnsafeBytes {
sqlite3_result_blob(sqliteContext, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
}
#else
data.withUnsafeBytes {
sqlite3_result_blob(sqliteContext, $0, Int32(data.count), SQLITE_TRANSIENT)
}
#endif
}
}
@@ -313,17 +321,10 @@ public final class DatabaseFunction: Hashable {
}
extension DatabaseFunction {
#if swift(>=4.2)
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(identity)
}
#else
/// :nodoc:
public var hashValue: Int {
return identity.hashValue
}
#endif
/// Two functions are equal if they share the same name and arity.
/// :nodoc:
@@ -354,10 +355,10 @@ extension DatabaseFunction {
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
/// dbQueue.add(function: fn)
/// try dbQueue.write { db in
/// try db.execute("CREATE TABLE test(i)")
/// try db.execute("INSERT INTO test(i) VALUES (1)")
/// try db.execute("INSERT INTO test(i) VALUES (2)")
/// try Int.fetchOne(db, "SELECT mysum(i) FROM test")! // 3
/// try db.execute(sql: "CREATE TABLE test(i)")
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
/// }
public protocol DatabaseAggregate {
/// Creates an aggregate.
+31 -104
View File
@@ -2,6 +2,8 @@ import Foundation
import Dispatch
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -58,14 +60,14 @@ public final class DatabasePool: DatabaseWriter {
// Activate WAL Mode unless readonly
if !configuration.readonly {
try writer.sync { db in
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode = WAL")
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode = WAL")
guard journalMode == "wal" else {
throw DatabaseError(message: "could not activate WAL Mode at path: \(path)")
}
// https://www.sqlite.org/pragma.html#pragma_synchronous
// > Many applications choose NORMAL when in WAL mode
try db.execute("PRAGMA synchronous = NORMAL")
try db.execute(sql: "PRAGMA synchronous = NORMAL")
if !FileManager.default.fileExists(atPath: path + "-wal") {
// Create the -wal file if it does not exist yet. This
@@ -73,7 +75,7 @@ public final class DatabasePool: DatabaseWriter {
// opens a pool to an existing non-WAL database, and
// attempts to read from it.
// See https://github.com/groue/GRDB.swift/issues/102
try db.execute("CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); DROP TABLE grdb_issue_102;")
try db.execute(sql: "CREATE TABLE grdb_issue_102 (id INTEGER PRIMARY KEY); DROP TABLE grdb_issue_102;")
}
}
}
@@ -177,13 +179,16 @@ extension DatabasePool {
public func setupMemoryManagement(in application: UIApplication) {
self.application = application
let center = NotificationCenter.default
#if swift(>=4.2)
center.addObserver(self, selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
center.addObserver(self, selector: #selector(DatabasePool.applicationDidEnterBackground(_:)), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
#else
center.addObserver(self, selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
center.addObserver(self, selector: #selector(DatabasePool.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
#endif
center.addObserver(
self,
selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabasePool.applicationDidEnterBackground(_:)),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
@@ -192,12 +197,7 @@ extension DatabasePool {
}
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
#if swift(>=4.2)
let taskIsInvalid = task == UIBackgroundTaskIdentifier.invalid
#else
let taskIsInvalid = task == UIBackgroundTaskInvalid
#endif
if taskIsInvalid {
if task == .invalid {
// Perform releaseMemory() synchronously.
releaseMemory()
} else {
@@ -249,13 +249,13 @@ extension DatabasePool : DatabaseReader {
/// try dbPool.read { db in
/// // Those two values are guaranteed to be equal, even if the
/// // `wine` table is modified between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// try dbPool.read { db in
/// // Now this value may be different:
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// This method is *not* reentrant.
@@ -290,15 +290,15 @@ extension DatabasePool : DatabaseReader {
/// try dbPool.unsafeRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// Cursor iteration is safe, though:
///
/// try dbPool.unsafeRead { db in
/// // No concurrent update can mess with this iteration:
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
/// while let row = try rows.next() { ... }
/// }
///
@@ -327,15 +327,15 @@ extension DatabasePool : DatabaseReader {
/// try dbPool.unsafeReentrantRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// Cursor iteration is safe, though:
///
/// try dbPool.unsafeReentrantRead { db in
/// // No concurrent update can mess with this iteration:
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
/// while let row = try rows.next() { ... }
/// }
///
@@ -359,80 +359,7 @@ extension DatabasePool : DatabaseReader {
}
}
/// This method is deprecated. Use concurrentRead instead.
///
/// Asynchronously executes a read-only block in a protected dispatch queue,
/// wrapped in a deferred transaction.
///
/// This method must be called from the writing dispatch queue, outside of a
/// transaction. You'll get a fatal error otherwise.
///
/// The *block* argument is guaranteed to see the database in the last
/// committed state at the moment this method is called. Eventual concurrent
/// database updates are *not visible* inside the block.
///
/// try dbPool.write { db in
/// try db.execute("DELETE FROM player")
/// try dbPool.readFromCurrentState { db in
/// // Guaranteed to be zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM player")!
/// }
/// try db.execute("INSERT INTO player ...")
/// }
///
/// This method blocks the current thread until the isolation guarantee has
/// been established, and before the block argument has run.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
@available(*, deprecated, message: "Use concurrentRead instead")
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
GRDBPrecondition(!db.isInsideTransaction, """
readFromCurrentState must not be called from inside a transaction. \
If this error is raised from a DatabasePool.write block, use \
DatabasePool.writeWithoutTransaction instead (and use \
transactions when needed).
""")
}
// The semaphore that blocks the writing dispatch queue until snapshot
// isolation has been established:
let semaphore = DispatchSemaphore(value: 0)
var snapshotIsolationError: Error? = nil
let (reader, releaseReader) = try readerPool.get()
reader.async { db in
defer {
_ = try? db.commit() // Ignore commit error
releaseReader()
}
do {
try db.beginSnapshotIsolation()
} catch {
snapshotIsolationError = error
semaphore.signal() // Release the writer queue and rethrow error
return
}
semaphore.signal() // We can release the writer queue now that we are isolated for good
// Reset the schema cache before running user code in snapshot isolation
db.schemaCache = SimpleDatabaseSchemaCache()
block(db)
}
_ = semaphore.wait(timeout: .distantFuture)
if let error = snapshotIsolationError {
// TODO: write a test for this
throw error
}
}
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T> {
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
// Check that we're on the writer queue...
writer.execute { db in
// ... and that no transaction is opened.
@@ -479,16 +406,16 @@ extension DatabasePool : DatabaseReader {
futureSemaphore.signal()
}
} catch {
return Future { throw error }
return DatabaseFuture { throw error }
}
// Block the writer queue until snapshot isolation success or error
_ = isolationSemaphore.wait(timeout: .distantFuture)
return Future {
return DatabaseFuture {
// Block the future until results are fetched
_ = futureSemaphore.wait(timeout: .distantFuture)
return try futureResult!.unwrap()
return try futureResult!.get()
}
}
@@ -632,7 +559,7 @@ extension DatabasePool : DatabaseReader {
/// }
/// dbPool.add(function: fn)
/// try dbPool.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
/// try Int.fetchOne(db, sql: "SELECT succ(1)") // 2
/// }
public func add(function: DatabaseFunction) {
functions.update(with: function)
@@ -654,7 +581,7 @@ extension DatabasePool : DatabaseReader {
/// }
/// dbPool.add(collation: collation)
/// try dbPool.write { db in
/// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func add(collation: DatabaseCollation) {
collations.update(with: collation)
+15 -37
View File
@@ -94,13 +94,16 @@ extension DatabaseQueue {
public func setupMemoryManagement(in application: UIApplication) {
self.application = application
let center = NotificationCenter.default
#if swift(>=4.2)
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)), name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
#else
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)), name: .UIApplicationDidReceiveMemoryWarning, object: nil)
center.addObserver(self, selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)), name: .UIApplicationDidEnterBackground, object: nil)
#endif
center.addObserver(
self,
selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil)
center.addObserver(
self,
selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
@objc private func applicationDidEnterBackground(_ notification: NSNotification) {
@@ -109,12 +112,7 @@ extension DatabaseQueue {
}
let task: UIBackgroundTaskIdentifier = application.beginBackgroundTask(expirationHandler: nil)
#if swift(>=4.2)
let taskIsInvalid = task == UIBackgroundTaskIdentifier.invalid
#else
let taskIsInvalid = task == UIBackgroundTaskInvalid
#endif
if taskIsInvalid {
if task == .invalid {
// Perform releaseMemory() synchronously.
releaseMemory()
} else {
@@ -203,30 +201,10 @@ extension DatabaseQueue {
return try writer.reentrantSync(block)
}
/// This method is deprecated. Use concurrentRead instead.
///
/// Synchronously executes *block*.
///
/// This method must be called from the protected database dispatch queue,
/// outside of a transaction. You'll get a fatal error otherwise.
///
/// Starting SQLite 3.8.0 (iOS 8.2+, OSX 10.10+, custom SQLite builds and
/// SQLCipher), attempts to write in the database from this meethod throw a
/// DatabaseError of resultCode `SQLITE_READONLY`.
@available(*, deprecated, message: "Use concurrentRead instead")
public func readFromCurrentState(_ block: @escaping (Database) -> Void) {
// Check that we're on the correct queue...
writer.execute { db in
// ... and that no transaction is opened.
GRDBPrecondition(!db.isInsideTransaction, "readFromCurrentState must not be called from inside a transaction.")
db.readOnly { block(db) }
}
}
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T> {
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
// DatabaseQueue can't perform parallel reads.
// Perform a blocking read instead.
return Future(Result {
return DatabaseFuture(Result {
// Check that we're on the writer queue...
try writer.execute { db in
// ... and that no transaction is opened.
@@ -354,7 +332,7 @@ extension DatabaseQueue {
/// }
/// dbQueue.add(function: fn)
/// try dbQueue.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)") // 2
/// try Int.fetchOne(db, sql: "SELECT succ(1)") // 2
/// }
public func add(function: DatabaseFunction) {
writer.sync { $0.add(function: function) }
@@ -374,7 +352,7 @@ extension DatabaseQueue {
/// }
/// dbQueue.add(collation: collation)
/// try dbQueue.write { db in
/// try db.execute("CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE LOCALIZED_STANDARD")
/// }
public func add(collation: DatabaseCollation) {
writer.sync { $0.add(collation: collation) }
+13 -11
View File
@@ -1,5 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -32,13 +34,13 @@ public protocol DatabaseReader : class {
/// try reader.read { db in
/// // Those two values are guaranteed to be equal, even if the
/// // `wine` table is modified between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// try reader.read { db in
/// // Now this value may be different:
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
@@ -61,15 +63,15 @@ public protocol DatabaseReader : class {
/// try reader.unsafeRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// Cursor iterations are isolated, though:
///
/// try reader.unsafeRead { db in
/// // No concurrent update can mess with this iteration:
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
/// while let row = try rows.next() { ... }
/// }
///
@@ -92,15 +94,15 @@ public protocol DatabaseReader : class {
/// try reader.unsafeReentrantRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wine")!
/// let count1 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// let count2 = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM wine")!
/// }
///
/// Cursor iterations are isolated, though:
///
/// try reader.unsafeReentrantRead { db in
/// // No concurrent update can mess with this iteration:
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
/// while let row = try rows.next() { ... }
/// }
///
@@ -128,7 +130,7 @@ public protocol DatabaseReader : class {
/// }
/// reader.add(function: fn)
/// try reader.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
/// }
func add(function: DatabaseFunction)
@@ -144,7 +146,7 @@ public protocol DatabaseReader : class {
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// reader.add(collation: collation)
/// try reader.execute("SELECT * FROM file ORDER BY name COLLATE localized_standard")
/// try reader.execute(sql: "SELECT * FROM file ORDER BY name COLLATE localized_standard")
func add(collation: DatabaseCollation)
/// Remove a collation.
+16 -25
View File
@@ -3,8 +3,7 @@
/// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods.
///
/// A database region is the union of any number of "table regions", which can
/// cover a full table, or the combination of columns and rows (identified by
/// their rowids):
/// cover a full table, or the combination of columns and rows:
///
/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
/// |-------| |-------| |-------| |-------| |-------|
@@ -13,32 +12,23 @@
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
///
/// You don't create a database region directly. Instead, you use one of
/// those methods:
/// To create a database region, you use one of those methods:
///
/// - `DatabaseRegion.fullDatabase`: the region that covers all database tables.
///
/// - `DatabaseRegion()`: the empty region.
///
/// - `DatabaseRegion(table:)`: the region that covers one database table.
///
/// - `SelectStatement.databaseRegion`:
///
/// let statement = db.makeSelectStatement("SELECT name, score FROM player")
/// print(statement.databaseRegion)
/// // prints "player(name,score)"
/// let statement = try db.makeSelectStatement(sql: "SELECT name, score FROM player")
/// let region = statement.databaseRegion
///
/// - `FetchRequest.databaseRegion(_:)`
///
/// let request = Player.filter(key: 1)
/// try print(request.databaseRegion(db))
/// // prints "player(*)[1]"
///
/// Database regions returned by requests can be more precise than regions
/// returned by select statements. Especially, regions returned by statements
/// don't know about rowids:
///
/// // A plain statement
/// let statement = db.makeSelectStatement("SELECT * FROM player WHERE id = 1")
/// statement.databaseRegion // "player(*)"
///
/// // A query interface request that executes the same statement:
/// let request = Player.filter(key: 1)
/// try request.databaseRegion(db) // "player(*)[1]"
/// let region = try request.databaseRegion(db)
public struct DatabaseRegion: CustomStringConvertible, Equatable {
private let tableRegions: [String: TableRegion]?
private init(tableRegions: [String: TableRegion]?) {
@@ -58,13 +48,15 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
/// from all tables.
public static let fullDatabase = DatabaseRegion(tableRegions: nil)
/// The empty database region
/// Creates an empty database region.
public init() {
self.init(tableRegions: [:])
}
/// A full table: (all columns in the table) × (all rows)
init(table: String) {
/// Creates a region that spans all rows and columns of a database table.
///
/// - parameter table: A table name.
public init(table: String) {
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
}
@@ -302,7 +294,6 @@ private struct TableRegion: Equatable {
return TableRegion(columns: columnsUnion, rowIds: rowIdsUnion)
}
@inline(__always)
func contains(rowID: Int64) -> Bool {
guard let rowIds = rowIds else {
return true
+2 -2
View File
@@ -28,7 +28,7 @@ public class DatabaseSnapshot : DatabaseReader {
try serializedDatabase.sync { db in
// Assert WAL mode
let journalMode = try String.fetchOne(db, "PRAGMA journal_mode")
let journalMode = try String.fetchOne(db, sql: "PRAGMA journal_mode")
guard journalMode == "wal" else {
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
}
@@ -116,7 +116,7 @@ extension DatabaseSnapshot {
}
}
}
case let .onQueue(queue, startImmediately: startImmediately):
case let .async(onQueue: queue, startImmediately: startImmediately):
if startImmediately {
if let value = try unsafeReentrantRead(observation.initialValue) {
queue.async {
+46 -78
View File
@@ -1,6 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -149,7 +151,6 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
// Hashable
extension DatabaseValue {
#if swift(>=4.2)
/// :nodoc:
public func hash(into hasher: inout Hasher) {
switch storage {
@@ -166,24 +167,6 @@ extension DatabaseValue {
hasher.combine(data)
}
}
#else
/// :nodoc:
public var hashValue: Int {
switch storage {
case .null:
return 0
case .int64(let int64):
// 1 == 1.0, hence 1 and 1.0 must have the same hash:
return Double(int64).hashValue
case .double(let double):
return double.hashValue
case .string(let string):
return string.hashValue
case .blob(let data):
return data.hashValue
}
}
#endif
/// Returns whether two DatabaseValues are equal.
///
@@ -222,57 +205,6 @@ extension DatabaseValue {
}
}
// MARK: - Lossless conversions
extension DatabaseValue {
// TODO: deprecate and rename to DatabaseValue.decode(_:sql:arguments:)
/// Converts the database value to the type T.
///
/// let dbValue = "foo".databaseValue
/// let string = dbValue.losslessConvert() as String // "foo"
///
/// Conversion is successful if and only if T.fromDatabaseValue returns a
/// non-nil value.
///
/// This method crashes with a fatal error when conversion fails.
///
/// let dbValue = "foo".databaseValue
/// let int = dbValue.losslessConvert() as Int // fatalError
///
/// - parameters:
/// - sql: Optional SQL statement that enhances the eventual
/// conversion error
/// - arguments: Optional statement arguments that enhances the eventual
/// conversion error
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T : DatabaseValueConvertible {
return T.decode(from: self, conversionContext: sql.map { ValueConversionContext(sql: $0, arguments: arguments) })
}
// TODO: deprecate and rename to DatabaseValue.decodeIfPresent(_:sql:arguments:)
/// Converts the database value to the type Optional<T>.
///
/// let dbValue = "foo".databaseValue
/// let string = dbValue.losslessConvert() as String? // "foo"
/// let null = DatabaseValue.null.losslessConvert() as String? // nil
///
/// Conversion is successful if and only if T.fromDatabaseValue returns a
/// non-nil value.
///
/// This method crashes with a fatal error when conversion fails.
///
/// let dbValue = "foo".databaseValue
/// let int = dbValue.losslessConvert() as Int? // fatalError
///
/// - parameters:
/// - sql: Optional SQL statement that enhances the eventual
/// conversion error
/// - arguments: Optional statement arguments that enhances the eventual
/// conversion error
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T : DatabaseValueConvertible {
return T.decodeIfPresent(from: self, conversionContext: sql.map { ValueConversionContext(sql: $0, arguments: arguments) })
}
}
// DatabaseValueConvertible
extension DatabaseValue {
/// Returns self
@@ -305,12 +237,12 @@ extension DatabaseValue {
return "NULL"
}
if context.appendArguments([self]) {
if context.append(arguments: [self]) {
return "?"
} else {
// Correctness above all: use SQLite to quote the value.
// Assume that the Quote function always succeeds
return DatabaseQueue().inDatabase { try! String.fetchOne($0, "SELECT QUOTE(?)", arguments: [self])! }
return DatabaseQueue().inDatabase { try! String.fetchOne($0, sql: "SELECT QUOTE(?)", arguments: [self])! }
}
}
@@ -345,12 +277,6 @@ extension DatabaseValue {
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
return self
}
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
/// :nodoc:
public func resolvedExpression(inContext context: [TableAlias: PersistenceContainer]) -> SQLExpression {
return self
}
}
// CustomStringConvertible
@@ -371,3 +297,45 @@ extension DatabaseValue {
}
}
}
/// Compares DatabaseValue like SQLite.
///
/// See RxGRDB for tests.
///
/// 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 so far is aesthetic, and
/// easier testing.
func < (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
switch (lhs.storage, rhs.storage) {
case (.int64(let lhs), .int64(let rhs)):
return lhs < rhs
case (.double(let lhs), .double(let rhs)):
return lhs < rhs
case (.int64(let lhs), .double(let rhs)):
return Double(lhs) < rhs
case (.double(let lhs), .int64(let rhs)):
return lhs < Double(rhs)
case (.string(let lhs), .string(let rhs)):
return lhs.utf8.lexicographicallyPrecedes(rhs.utf8)
case (.blob(let lhs), .blob(let rhs)):
return lhs.lexicographicallyPrecedes(rhs, by: <)
case (.blob, _):
return false
case (_, .blob):
return true
case (.string, _):
return false
case (_, .string):
return true
case (.int64, _), (.double, _):
return false
case (_, .int64), (_, .double):
return true
case (.null, _):
return false
case (_, .null):
return true
}
}
+68 -26
View File
@@ -1,5 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -68,7 +70,7 @@ extension ValueConversionContext {
arguments: statement.arguments,
column: nil)
} else if let sqliteStatement = row.sqliteStatement {
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: statementSeparatorCharacterSet)
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators)
self.init(
row: row.copy(),
sql: sql,
@@ -82,14 +84,6 @@ extension ValueConversionContext {
column: nil)
}
}
init(sql: String, arguments: StatementArguments?) {
self.init(
row: nil,
sql: sql,
arguments: arguments,
column: nil)
}
}
/// The canonical conversion error message
@@ -138,7 +132,16 @@ func fatalConversionError<T>(to: T.Type, from dbValue: DatabaseValue?, conversio
fatalError(conversionErrorMessage(to: T.self, from: dbValue, conversionContext: conversionContext), file: file, line: line)
}
func fatalConversionError<T>(to: T.Type, sqliteStatement: SQLiteStatement, index: Int32) -> Never {
@usableFromInline
func fatalConversionError<T>(to: T.Type, from dbValue: DatabaseValue?, in row: Row, atColumn columnName: String, file: StaticString = #file, line: UInt = #line) -> Never {
fatalConversionError(
to: T.self,
from: dbValue,
conversionContext: ValueConversionContext(row).atColumn(columnName))
}
@usableFromInline
func fatalConversionError<T>(to: T.Type, sqliteStatement: SQLiteStatement, index: Int32, file: StaticString = #file, line: UInt = #line) -> Never {
let row = Row(sqliteStatement: sqliteStatement)
fatalConversionError(
to: T.self,
@@ -146,11 +149,29 @@ func fatalConversionError<T>(to: T.Type, sqliteStatement: SQLiteStatement, index
conversionContext: ValueConversionContext(row).atColumn(Int(index)))
}
@usableFromInline
func fatalConversionError<T>(to: T.Type, from dbValue: DatabaseValue?, sqliteStatement: SQLiteStatement, index: Int32, file: StaticString = #file, line: UInt = #line) -> Never {
let row = Row(sqliteStatement: sqliteStatement)
fatalConversionError(
to: T.self,
from: dbValue,
conversionContext: ValueConversionContext(row).atColumn(Int(index)))
}
// MARK: - DatabaseValueConvertible
/// Lossless conversions from database values and rows
extension DatabaseValueConvertible {
@inline(__always)
@usableFromInline
static func decode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self {
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
if let value = fromDatabaseValue(dbValue) {
return value
} else {
fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index)
}
}
static func decode(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self {
if let value = fromDatabaseValue(dbValue) {
return value
@@ -159,14 +180,25 @@ extension DatabaseValueConvertible {
}
}
@inline(__always)
@usableFromInline
static func decode(from row: Row, atUncheckedIndex index: Int) -> Self {
return decode(
from: row.impl.databaseValue(atUncheckedIndex: index),
conversionContext: ValueConversionContext(row).atColumn(index))
}
@inline(__always)
@usableFromInline
static func decodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? {
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
if let value = fromDatabaseValue(dbValue) {
return value
} else if dbValue.isNull {
return nil
} else {
fatalConversionError(to: Self.self, from: dbValue, sqliteStatement: sqliteStatement, index: index)
}
}
static func decodeIfPresent(from dbValue: DatabaseValue, conversionContext: @autoclosure () -> ValueConversionContext?) -> Self? {
// Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
if let value = fromDatabaseValue(dbValue) {
@@ -178,7 +210,7 @@ extension DatabaseValueConvertible {
}
}
@inline(__always)
@usableFromInline
static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
return decodeIfPresent(
from: row.impl.databaseValue(atUncheckedIndex: index),
@@ -190,26 +222,23 @@ extension DatabaseValueConvertible {
/// Lossless conversions from database values and rows
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@inline(__always)
static func fastDecode(from sqliteStatement: SQLiteStatement, index: Int32) -> Self {
@inlinable
static func fastDecode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
fatalConversionError(
to: Self.self,
from: .null,
conversionContext: ValueConversionContext(Row(sqliteStatement: sqliteStatement)).atColumn(Int(index)))
fatalConversionError(to: Self.self, sqliteStatement: sqliteStatement, index: index)
}
return self.init(sqliteStatement: sqliteStatement, index: index)
}
@inline(__always)
@inlinable
static func fastDecode(from row: Row, atUncheckedIndex index: Int) -> Self {
if let sqliteStatement = row.sqliteStatement {
return fastDecode(from: sqliteStatement, index: Int32(index))
return fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
}
return row.impl.fastDecode(Self.self, atUncheckedIndex: index)
return row.fastDecode(Self.self, atUncheckedIndex: index)
}
@inline(__always)
@inlinable
static func fastDecodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
@@ -217,11 +246,24 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
return self.init(sqliteStatement: sqliteStatement, index: index)
}
@inline(__always)
@inlinable
static func fastDecodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
if let sqliteStatement = row.sqliteStatement {
return fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: Int32(index))
}
return row.impl.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
return row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
}
}
// Support for @inlinable decoding
extension Row {
@usableFromInline
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ type: Value.Type, atUncheckedIndex index: Int) -> Value {
return impl.fastDecode(type, atUncheckedIndex: index)
}
@usableFromInline
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ type: Value.Type, atUncheckedIndex index: Int) -> Value? {
return impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
}
}
+83 -95
View File
@@ -1,5 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -12,11 +14,11 @@
/// The protocol comes with built-in methods that allow to fetch cursors,
/// arrays, or single values:
///
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
/// try String.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
/// try String.fetchAll(statement, arguments:...) // [String]
/// try String.fetchOne(statement, arguments:...) // String?
@@ -42,58 +44,51 @@ extension DatabaseValueConvertible {
/// For example:
///
/// try dbQueue.read { db in
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, "SELECT url FROM link")
/// let urls: DatabaseValueCursor<URL> = try URL.fetchCursor(db, sql: "SELECT url FROM link")
/// while let url = urls.next() { // URL
/// print(url)
/// }
/// }
public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
private let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let columnIndex: Int32
private var done = false
@usableFromInline let _statement: SelectStatement
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline let _columnIndex: Int32
@usableFromInline var _done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
_statement = statement
_sqliteStatement = statement.sqliteStatement
if let adapter = adapter {
// adapter may redefine the index of the leftmost column
self.columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
_columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
} else {
self.columnIndex = 0
_columnIndex = 0
}
statement.reset(withArguments: arguments)
_statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? statement.reset()
try? _statement.reset()
}
/// :nodoc:
@inlinable
public func next() throws -> Value? {
if done {
if _done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
switch sqlite3_step(_sqliteStatement) {
case SQLITE_DONE:
done = true
_done = true
return nil
case SQLITE_ROW:
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
return Value.decode(
from: dbValue,
conversionContext: ValueConversionContext(statement).atColumn(Int(columnIndex)))
return Value.decode(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(
resultCode: code,
message: statement.database.lastErrorMessage,
sql: statement.sql,
arguments: statement.arguments)
try _statement.didFail(withResultCode: code)
}
}
}
@@ -102,58 +97,51 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor
/// For example:
///
/// try dbQueue.read { db in
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, "SELECT url FROM link")
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, sql: "SELECT url FROM link")
/// while let url = urls.next() { // URL?
/// print(url)
/// }
/// }
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible> : Cursor {
private let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let columnIndex: Int32
private var done = false
@usableFromInline let _statement: SelectStatement
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline let _columnIndex: Int32
@usableFromInline var _done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
_statement = statement
_sqliteStatement = statement.sqliteStatement
if let adapter = adapter {
// adapter may redefine the index of the leftmost column
self.columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
_columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
} else {
self.columnIndex = 0
_columnIndex = 0
}
statement.reset(withArguments: arguments)
_statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? statement.reset()
try? _statement.reset()
}
/// :nodoc:
@inlinable
public func next() throws -> Value?? {
if done {
if _done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
switch sqlite3_step(_sqliteStatement) {
case SQLITE_DONE:
done = true
_done = true
return nil
case SQLITE_ROW:
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: columnIndex)
return Value.decodeIfPresent(
from: dbValue,
conversionContext: ValueConversionContext(statement).atColumn(Int(columnIndex)))
return Value.decodeIfPresent(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(
resultCode: code,
message: statement.database.lastErrorMessage,
sql: statement.sql,
arguments: statement.arguments)
try _statement.didFail(withResultCode: code)
}
}
}
@@ -161,11 +149,11 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>
/// DatabaseValueConvertible comes with built-in methods that allow to fetch
/// cursors, arrays, or single values:
///
/// try String.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String
/// try String.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, "SELECT name FROM ...", arguments:...) // String?
/// try String.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
/// try String.fetchAll(statement, arguments:...) // [String]
/// try String.fetchOne(statement, arguments:...) // String
@@ -177,7 +165,7 @@ extension DatabaseValueConvertible {
/// Returns a cursor over values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try String.fetchCursor(statement) // Cursor of String
/// while let name = try names.next() { // String
/// ...
@@ -200,7 +188,7 @@ extension DatabaseValueConvertible {
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try String.fetchAll(statement) // [String]
///
/// - parameters:
@@ -218,7 +206,7 @@ extension DatabaseValueConvertible {
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let name = try String.fetchOne(statement) // String?
///
/// - parameters:
@@ -240,7 +228,7 @@ extension DatabaseValueConvertible {
/// Returns a cursor over values fetched from an SQL query.
///
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
/// let names = try String.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String
/// while let name = try name.next() { // String
/// ...
/// }
@@ -253,27 +241,27 @@ extension DatabaseValueConvertible {
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from an SQL query.
@@ -281,17 +269,17 @@ extension DatabaseValueConvertible {
/// The result is nil if the query returns no row, or if no value can be
/// extracted from the first row.
///
/// let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
/// let name = try String.fetchOne(db, sql: "SELECT name FROM ...") // String?
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -318,7 +306,7 @@ extension DatabaseValueConvertible {
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> DatabaseValueCursor<Self> {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
return try fetchCursor(statement, adapter: adapter)
}
@@ -333,7 +321,7 @@ extension DatabaseValueConvertible {
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Self] {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
return try fetchAll(statement, adapter: adapter)
}
@@ -351,7 +339,7 @@ extension DatabaseValueConvertible {
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> Self? {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: true)
return try fetchOne(statement, adapter: adapter)
}
}
@@ -362,7 +350,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// A cursor over fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let request: ... // Some FetchRequest that fetches String
/// let strings = try request.fetchCursor(db) // Cursor of String
/// while let string = try strings.next() { // String
/// ...
@@ -382,7 +370,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// An array of fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let request: ... // Some FetchRequest that fetches String
/// let strings = try request.fetchAll(db) // [String]
///
/// - parameter db: A database connection.
@@ -397,7 +385,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// The result is nil if the request returns no row, or if no value can be
/// extracted from the first row.
///
/// let request: ... // Some TypedRequest that fetches String
/// let request: ... // Some FetchRequest that fetches String
/// let string = try request.fetchOne(db) // String?
///
/// - parameter db: A database connection.
@@ -411,10 +399,10 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
/// Swift's Optional comes with built-in methods that allow to fetch cursors
/// and arrays of optional DatabaseValueConvertible:
///
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
/// try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?]
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
///
@@ -425,7 +413,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns a cursor over optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
@@ -448,7 +436,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns an array of optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try Optional<String>.fetchAll(statement) // [String?]
///
/// - parameters:
@@ -468,7 +456,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns a cursor over optional values fetched from an SQL query.
///
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
/// let names = try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
@@ -481,27 +469,27 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of optional values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String?]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - parameter arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -528,7 +516,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> NullableDatabaseValueCursor<Wrapped> {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
return try fetchCursor(statement, adapter: adapter)
}
@@ -543,7 +531,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Wrapped?] {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
return try fetchAll(statement, adapter: adapter)
}
}
@@ -554,7 +542,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
/// A cursor over fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let request: ... // Some FetchRequest that fetches Optional<String>
/// let strings = try request.fetchCursor(db) // Cursor of String?
/// while let string = try strings.next() { // String?
/// ...
@@ -574,7 +562,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
/// An array of fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let request: ... // Some FetchRequest that fetches Optional<String>
/// let strings = try request.fetchAll(db) // [String?]
///
/// - parameter db: A database connection.
+35 -54
View File
@@ -62,31 +62,6 @@ public protocol DatabaseWriter : DatabaseReader {
// MARK: - Reading from Database
/// This method is deprecated. Use concurrentRead instead.
///
/// Synchronously or asynchronously executes a read-only block that takes a
/// database connection.
///
/// This method must be called from a writing dispatch queue, outside of any
/// transaction. You'll get a fatal error otherwise.
///
/// The *block* argument is guaranteed to see the database in the last
/// committed state at the moment this method is called. Eventual concurrent
/// database updates are *not visible* inside the block.
///
/// For example:
///
/// try writer.writeWithoutTransaction { db in
/// try db.execute("DELETE FROM player")
/// try writer.readFromCurrentState { db in
/// // Guaranteed to be zero
/// try Int.fetchOne(db, "SELECT COUNT(*) FROM player")!
/// }
/// try db.execute("INSERT INTO player ...")
/// }
@available(*, deprecated, message: "Use concurrentRead instead")
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
/// Concurrently executes a read-only block that takes a
/// database connection.
///
@@ -119,7 +94,7 @@ public protocol DatabaseWriter : DatabaseReader {
/// // Guaranteed to be zero
/// let count = try future.wait()
/// }
func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T>
func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T>
}
extension DatabaseWriter {
@@ -157,30 +132,30 @@ extension DatabaseWriter {
// So we'll drop all database objects one after the other.
try writeWithoutTransaction { db in
// Prevent foreign keys from messing with drop table statements
let foreignKeysEnabled = try Bool.fetchOne(db, "PRAGMA foreign_keys")!
let foreignKeysEnabled = try Bool.fetchOne(db, sql: "PRAGMA foreign_keys")!
if foreignKeysEnabled {
try db.execute("PRAGMA foreign_keys = OFF")
try db.execute(sql: "PRAGMA foreign_keys = OFF")
}
// Remove all database objects, one after the other
do {
try db.inTransaction {
while let row = try Row.fetchOne(db, "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") {
while let row = try Row.fetchOne(db, sql: "SELECT type, name FROM sqlite_master WHERE name NOT LIKE 'sqlite_%'") {
let type: String = row["type"]
let name: String = row["name"]
try db.execute("DROP \(type) \(name.quotedDatabaseIdentifier)")
try db.execute(sql: "DROP \(type) \(name.quotedDatabaseIdentifier)")
}
return .commit
}
// Restore foreign keys if needed
if foreignKeysEnabled {
try db.execute("PRAGMA foreign_keys = ON")
try db.execute(sql: "PRAGMA foreign_keys = ON")
}
} catch {
// Restore foreign keys if needed
if foreignKeysEnabled {
try? db.execute("PRAGMA foreign_keys = ON")
try? db.execute(sql: "PRAGMA foreign_keys = ON")
}
throw error
}
@@ -197,7 +172,7 @@ extension DatabaseWriter {
///
/// See https://www.sqlite.org/lang_vacuum.html for more information.
public func vacuum() throws {
try writeWithoutTransaction { try $0.execute("VACUUM") }
try writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
// MARK: - Value Observation
@@ -235,7 +210,7 @@ extension DatabaseWriter {
DispatchQueue.main.async { onChange(value) }
}
}
case let .onQueue(queue, startImmediately: startImmediately):
case let .async(onQueue: queue, startImmediately: startImmediately):
if startImmediately {
if let value = try reducer.initialValue(db, requiresWriteAccess: observation.requiresWriteAccess) {
queue.async { onChange(value) }
@@ -256,7 +231,7 @@ extension DatabaseWriter {
notificationQueue: observation.notificationQueue,
onError: onError,
onChange: onChange)
db.add(transactionObserver: valueObserver, extent: observation.extent)
db.add(transactionObserver: valueObserver, extent: .observerLifetime)
return valueObserver
}
@@ -281,13 +256,13 @@ extension ValueReducer {
extension ValueObservation where Reducer: ValueReducer {
/// Helper method for DatabaseWriter.add(observation:onError:onChange:)
fileprivate func fetchAfterChange(in writer: DatabaseWriter) -> (Database, Reducer) -> Future<Reducer.Fetched> {
fileprivate func fetchAfterChange(in writer: DatabaseWriter) -> (Database, Reducer) -> DatabaseFuture<Reducer.Fetched> {
// The technique to return a future value after database has changed
// depends on the requiresWriteAccess flag:
if requiresWriteAccess {
// Synchronous fetch
return { (db, reducer) in
Future(Result {
DatabaseFuture(Result {
var fetchedValue: Reducer.Fetched!
try db.inTransaction {
fetchedValue = try reducer.fetch(db)
@@ -305,8 +280,20 @@ extension ValueObservation where Reducer: ValueReducer {
}
}
/// A future value.
public class Future<Value> {
/// A future database value, returned by the DatabaseWriter.concurrentRead(_:)
/// method.
///
/// let futureCount: Future<Int> = try writer.writeWithoutTransaction { db in
/// try Player(...).insert()
///
/// // Count players concurrently
/// return writer.concurrentRead { db in
/// return try Player.fetchCount()
/// }
/// }
///
/// let count: Int = try futureCount.wait()
public class DatabaseFuture<Value> {
private var consumed = false
private let _wait: () throws -> Value
@@ -315,7 +302,7 @@ public class Future<Value> {
}
init(_ result: Result<Value>) {
_wait = { try result.unwrap() }
_wait = result.get
}
/// Blocks the current thread until the value is available, and returns it.
@@ -326,7 +313,7 @@ public class Future<Value> {
public func wait() throws -> Value {
// Not thread-safe and quick and dirty.
// Goal is that users learn not to call this method twice.
GRDBPrecondition(consumed == false, "Future.wait() must be called only once")
GRDBPrecondition(consumed == false, "DatabaseFuture.wait() must be called only once")
consumed = true
return try _wait()
}
@@ -345,35 +332,29 @@ public final class AnyDatabaseWriter : DatabaseWriter {
}
// MARK: - Reading from Database
/// :nodoc:
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
}
/// :nodoc:
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeRead(block)
}
/// :nodoc:
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeReentrantRead(block)
}
/// :nodoc:
@available(*, deprecated, message: "Use concurrentRead instead")
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws {
try base.readFromCurrentState(block)
}
/// :nodoc:
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T> {
public func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> DatabaseFuture<T> {
return base.concurrentRead(block)
}
// MARK: - Writing in Database
/// :nodoc:
public func write<T>(_ block: (Database) throws -> T) throws -> T {
return try base.write(block)
@@ -383,7 +364,7 @@ public final class AnyDatabaseWriter : DatabaseWriter {
public func writeWithoutTransaction<T>(_ block: (Database) throws -> T) rethrows -> T {
return try base.writeWithoutTransaction(block)
}
/// :nodoc:
public func unsafeReentrantWrite<T>(_ block: (Database) throws -> T) rethrows -> T {
return try base.unsafeReentrantWrite(block)
+20 -111
View File
@@ -11,13 +11,16 @@
public protocol FetchRequest: DatabaseRegionConvertible {
/// The type that tells how fetched database rows should be interpreted.
associatedtype RowDecoder
/// Returns a tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
/// - parameter singleResult: A hint that the query should return a single
/// result. Implementations can optionally use
/// this to optimize the prepared statement.
/// - returns: A prepared statement and an eventual row adapter.
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
/// Returns the number of rows fetched by the request.
///
@@ -33,6 +36,7 @@ public protocol FetchRequest: DatabaseRegionConvertible {
}
extension FetchRequest {
/// Returns an adapted request.
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
return AdaptedFetchRequest(self, adapter)
@@ -45,9 +49,9 @@ extension FetchRequest {
///
/// - parameter db: A database connection.
public func fetchCount(_ db: Database) throws -> Int {
let (statement, _) = try prepare(db)
let (statement, _) = try prepare(db, forSingleResult: false)
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
return try Int.fetchOne(db, sql: sql, arguments: statement.arguments)!
}
/// Returns the database region that the request looks into.
@@ -57,7 +61,7 @@ extension FetchRequest {
///
/// - parameter db: A database connection.
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
let (statement, _) = try prepare(db)
let (statement, _) = try prepare(db, forSingleResult: false)
return statement.databaseRegion
}
}
@@ -79,8 +83,8 @@ public struct AdaptedFetchRequest<Base: FetchRequest> : FetchRequest {
}
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let (statement, baseAdapter) = try base.prepare(db)
public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) {
let (statement, baseAdapter) = try base.prepare(db, forSingleResult: singleResult)
if let baseAdapter = baseAdapter {
return try (statement, ChainedAdapter(first: baseAdapter, second: adapter(db)))
} else {
@@ -108,7 +112,7 @@ public struct AdaptedFetchRequest<Base: FetchRequest> : FetchRequest {
public struct AnyFetchRequest<T> : FetchRequest {
public typealias RowDecoder = T
private let _prepare: (Database) throws -> (SelectStatement, RowAdapter?)
private let _prepare: (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
private let _fetchCount: (Database) throws -> Int
private let _databaseRegion: (Database) throws -> DatabaseRegion
@@ -121,26 +125,26 @@ public struct AnyFetchRequest<T> : FetchRequest {
/// Creates a request whose `prepare()` method wraps and forwards
/// operations the argument closure.
public init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?)) {
_prepare = { db in
try prepare(db)
public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?)) {
_prepare = { db, singleResult in
try prepare(db, singleResult)
}
_fetchCount = { db in
let (statement, _) = try prepare(db)
let (statement, _) = try prepare(db, false)
let sql = "SELECT COUNT(*) FROM (\(statement.sql))"
return try Int.fetchOne(db, sql, arguments: statement.arguments)!
return try Int.fetchOne(db, sql: sql, arguments: statement.arguments)!
}
_databaseRegion = { db in
let (statement, _) = try prepare(db)
let (statement, _) = try prepare(db, false)
return statement.databaseRegion
}
}
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db)
public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) {
return try _prepare(db, singleResult)
}
/// :nodoc:
@@ -153,98 +157,3 @@ public struct AnyFetchRequest<T> : FetchRequest {
return try _databaseRegion(db)
}
}
// MARK: - SQLRequest
/// A FetchRequest built from raw SQL.
public struct SQLRequest<T> : FetchRequest {
public typealias RowDecoder = T
public var sql: String
public var arguments: StatementArguments?
public var adapter: RowAdapter?
private let cache: Cache?
/// Creates a request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest("SELECT * FROM player")
/// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: A SQLRequest
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(sql, arguments: arguments, adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates an SQL request from any other fetch request.
///
/// - parameters:
/// - db: A database connection.
/// - request: A request.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: An SQLRequest
public init<Request: FetchRequest>(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder {
let (statement, adapter) = try request.prepare(db)
self.init(statement.sql, arguments: statement.arguments, adapter: adapter, cached: cached)
}
/// Creates an SQL request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest("SELECT * FROM player")
/// let request = SQLRequest("SELECT * FROM player WHERE id = ?", arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - adapter: Optional RowAdapter.
/// - statementCacheName: Optional statement cache name.
/// - returns: A SQLRequest
init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
self.sql = sql
self.arguments = arguments
self.adapter = adapter
self.cache = cache
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
///
/// :nodoc:
public func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
let statement: SelectStatement
switch cache {
case .none:
statement = try db.makeSelectStatement(sql)
case .public?:
statement = try db.cachedSelectStatement(sql)
case .internal?:
statement = try db.internalCachedSelectStatement(sql)
}
if let arguments = arguments {
try statement.setArgumentsWithValidation(arguments)
}
return (statement, adapter)
}
/// There are two statement caches: one for statements generated by the
/// user, and one 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`
}
}
+416 -104
View File
@@ -1,6 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -14,22 +16,37 @@ public final class Row : Equatable, Hashable, RandomAccessCollection, Expressibl
/// Unless we are producing a row array, we use a single row when iterating
/// a statement:
///
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// let players = try Player.fetchAll(db, "SELECT ...")
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
/// let players = try Player.fetchAll(db, sql: "SELECT ...")
///
/// This row keeps an unmanaged reference to the statement, and a handle to
/// the sqlite statement, so that we avoid many retain/release invocations.
///
/// The statementRef is released in deinit.
let statementRef: Unmanaged<SelectStatement>?
let sqliteStatement: SQLiteStatement?
@usableFromInline let sqliteStatement: SQLiteStatement?
var statement: SelectStatement? {
return statementRef?.takeUnretainedValue()
}
/// The number of columns in the row.
public let count: Int
/// A view on the prefetched associated rows.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// print(row)
/// // Prints [id:1 name:"Herman Melville"]
///
/// let bookRows = row.prefetchedRows["books"]
/// print(bookRows[0])
/// // Prints [id:42 title:"Moby-Dick"]
public internal(set) var prefetchedRows: PrefetchedRowsView = PrefetchedRowsView()
// MARK: - Building rows
/// Creates an empty row.
@@ -140,7 +157,7 @@ extension Row {
return index(ofColumn: columnName) != nil
}
@inline(__always)
@usableFromInline
func index(ofColumn name: String) -> Int? {
return impl.index(ofColumn: name)
}
@@ -151,8 +168,8 @@ extension Row {
// MARK: - Extracting Values
/// Fatal errors if index is out of bounds
@inline(__always)
private func checkIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) {
@inlinable
func _checkIndex(_ index: Int, file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(index >= 0 && index < count, "row index out of range", file: file, line: line)
}
@@ -162,10 +179,10 @@ extension Row {
///
/// For example:
///
/// let row = try Row.fetchOne(db, "SELECT 'foo', 1")!
/// let row = try Row.fetchOne(db, sql: "SELECT 'foo', 1")!
/// row.containsNonNullValue // true
///
/// let row = try Row.fetchOne(db, "SELECT NULL, NULL")!
/// let row = try Row.fetchOne(db, sql: "SELECT NULL, NULL")!
/// row.containsNonNullValue // false
public var containsNonNullValue: Bool {
for i in (0..<count) where !impl.hasNull(atUncheckedIndex: i) {
@@ -188,7 +205,7 @@ extension Row {
/// in performance-critical code because it can avoid decoding database
/// values.
public func hasNull(atIndex index: Int) -> Bool {
checkIndex(index)
_checkIndex(index)
return impl.hasNull(atUncheckedIndex: index)
}
@@ -198,7 +215,7 @@ extension Row {
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
/// righmost column.
public subscript(_ index: Int) -> DatabaseValueConvertible? {
checkIndex(index)
_checkIndex(index)
return impl.databaseValue(atUncheckedIndex: index).storage.value
}
@@ -210,8 +227,9 @@ extension Row {
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
/// value is converted to the requested type `Value`. Should this conversion
/// fail, a fatal error is raised.
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value? {
checkIndex(index)
_checkIndex(index)
return Value.decodeIfPresent(from: self, atUncheckedIndex: index)
}
@@ -227,8 +245,9 @@ extension Row {
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value? {
checkIndex(index)
_checkIndex(index)
return Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index)
}
@@ -239,8 +258,9 @@ extension Row {
///
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value {
checkIndex(index)
_checkIndex(index)
return Value.decode(from: self, atUncheckedIndex: index)
}
@@ -255,8 +275,9 @@ extension Row {
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
checkIndex(index)
_checkIndex(index)
return Value.fastDecode(from: self, atUncheckedIndex: index)
}
@@ -289,6 +310,7 @@ extension Row {
/// If the column is missing or if the SQLite value is NULL, the result is
/// nil. Otherwise the SQLite value is converted to the requested type
/// `Value`. Should this conversion fail, a fatal error is raised.
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value? {
guard let index = index(ofColumn: columnName) else {
return nil
@@ -308,6 +330,7 @@ extension Row {
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value? {
guard let index = index(ofColumn: columnName) else {
return nil
@@ -324,13 +347,11 @@ extension Row {
///
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
@inlinable
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
guard let index = index(ofColumn: columnName) else {
// No such column
fatalConversionError(
to: Value.self,
from: nil,
conversionContext: ValueConversionContext(self).atColumn(columnName))
fatalConversionError(to: Value.self, from: nil, in: self, atColumn: columnName)
}
return Value.decode(from: self, atUncheckedIndex: index)
}
@@ -348,13 +369,11 @@ extension Row {
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
guard let index = index(ofColumn: columnName) else {
// No such column
fatalConversionError(
to: Value.self,
from: nil,
conversionContext: ValueConversionContext(self).atColumn(columnName))
fatalConversionError(to: Value.self, from: nil, in: self, atColumn: columnName)
}
return Value.fastDecode(from: self, atUncheckedIndex: index)
}
@@ -366,7 +385,8 @@ extension Row {
/// the same name, the leftmost column is considered.
///
/// The result is nil if the row does not contain the column.
public subscript(_ column: ColumnExpression) -> DatabaseValueConvertible? {
@inlinable
public subscript<Column: ColumnExpression>(_ column: Column) -> DatabaseValueConvertible? {
return self[column.name]
}
@@ -378,7 +398,8 @@ extension Row {
/// If the column is missing or if the SQLite value is NULL, the result is
/// nil. Otherwise the SQLite value is converted to the requested type
/// `Value`. Should this conversion fail, a fatal error is raised.
public subscript<Value: DatabaseValueConvertible>(_ column: ColumnExpression) -> Value? {
@inlinable
public subscript<Value: DatabaseValueConvertible, Column: ColumnExpression>(_ column: Column) -> Value? {
return self[column.name]
}
@@ -394,7 +415,8 @@ extension Row {
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: ColumnExpression) -> Value? {
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible, Column: ColumnExpression>(_ column: Column) -> Value? {
return self[column.name]
}
@@ -407,7 +429,8 @@ extension Row {
///
/// This method crashes if the fetched SQLite value is NULL, or if the
/// SQLite value can not be converted to `Value`.
public subscript<Value: DatabaseValueConvertible>(_ column: ColumnExpression) -> Value {
@inlinable
public subscript<Value: DatabaseValueConvertible, Column: ColumnExpression>(_ column: Column) -> Value {
return self[column.name]
}
@@ -424,7 +447,8 @@ extension Row {
/// This method exists as an optimization opportunity for types that adopt
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
/// (see https://www.sqlite.org/datatype3.html).
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ column: ColumnExpression) -> Value {
@inlinable
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible, Column: ColumnExpression>(_ column: Column) -> Value {
return self[column.name]
}
@@ -439,7 +463,7 @@ extension Row {
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
public func dataNoCopy(atIndex index: Int) -> Data? {
checkIndex(index)
_checkIndex(index)
return impl.dataNoCopy(atUncheckedIndex: index)
}
@@ -472,7 +496,7 @@ extension Row {
///
/// The returned data does not owns its bytes: it must not be used longer
/// than the row's lifetime.
public func dataNoCopy(_ column: ColumnExpression) -> Data? {
public func dataNoCopy<Column: ColumnExpression>(_ column: Column) -> Data? {
return dataNoCopy(named: column.name)
}
}
@@ -494,26 +518,82 @@ extension Row {
// MARK: - Extracting Records
/// Returns the record encoded in the given scope.
/// Returns the record associated with the given scope.
///
/// A fatal error is raised in the row was not fetched with a row adapter
/// that defines this scope.
/// For example:
///
/// let request = Book.including(required: Book.author)
/// let row = try Row.fetchOne(db, request)!
///
/// print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let author: Author = row["author"]
/// print(author.name)
/// // Prints "Herman Melville"
///
/// Associated records stored in nested associations are available, too:
///
/// let request = Book.including(required: Book.author.including(required: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let country: Country = row["country"]
/// print(country.name)
/// // Prints "United States"
///
/// A fatal error is raised if the scope is not available, or contains only
/// null values.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
/// for more information.
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
guard let scopedRow = scopesTree[scope] else {
// Programmer error
fatalError("no such scope: \(scope)")
let names = scopesTree.names
if names.isEmpty {
fatalError("missing scope `\(scope)` (row: \(self))")
} else {
fatalError("missing scope `\(scope)` (row: \(self), available scopes: \(names.sorted()))")
}
}
guard scopedRow.containsNonNullValue else {
// Programmer error
fatalError("scope `\(scope)` only contains null values (row: \(self))")
}
return Record(row: scopedRow)
}
/// Returns the record encoded in the given scope, if and only if the scope
/// has been defined by a row adapter, and the scoped row contains a
/// non-null value. Otherwise, return nil.
/// Returns the eventual record associated with the given scope.
///
/// This subscript is designed to handle left joined records.
/// For example:
///
/// let request = Book.including(optional: Book.author)
/// let row = try Row.fetchOne(db, request)!
///
/// print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let author: Author? = row["author"]
/// print(author.name)
/// // Prints "Herman Melville"
///
/// Associated records stored in nested associations are available, too:
///
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let country: Country? = row["country"]
/// print(country.name)
/// // Prints "United States"
///
/// Nil is returned if the scope is not available, or contains only
/// null values.
///
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
/// for more information.
@@ -523,6 +603,72 @@ extension Row {
}
return Record(row: scopedRow)
}
/// Returns the records encoded in the given prefetched rows.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// print(Author(row: row).name)
/// // Prints "Herman Melville"
///
/// let books: [Book] = row["books"]
/// print(books[0].title)
/// // Prints "Moby-Dick"
public subscript<Collection>(_ key: String)
-> Collection
where
Collection: RangeReplaceableCollection,
Collection.Element: FetchableRecord
{
guard let rows = prefetchedRows[key] else {
// Programmer error
let keys = prefetchedRows.keys
if keys.isEmpty {
fatalError("missing key for prefetched rows `\(key)` (row: \(self))")
} else {
fatalError("missing key for prefetched rows `\(key)` (row: \(self), available keys: \(keys.sorted()))")
}
}
var collection = Collection()
collection.reserveCapacity(rows.count)
for row in rows {
collection.append(Collection.Element(row: row))
}
return collection
}
/// Returns the set of records encoded in the given prefetched rows.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// print(Author(row: row).name)
/// // Prints "Herman Melville"
///
/// let books: Set<Book> = row["books"]
/// print(books.first!.title)
/// // Prints "Moby-Dick"
public subscript<Record: FetchableRecord & Hashable>(_ key: String) -> Set<Record> {
guard let rows = prefetchedRows[key] else {
// Programmer error
let keys = prefetchedRows.keys
if keys.isEmpty {
fatalError("missing key for prefetched rows `\(key)` (row: \(self))")
} else {
fatalError("missing key for prefetched rows `\(key)` (row: \(self), available keys: \(keys.sorted()))")
}
}
var set = Set<Record>(minimumCapacity: rows.count)
for row in rows {
set.insert(Record(row: row))
}
return set
}
}
extension Row {
@@ -541,7 +687,7 @@ extension Row {
///
/// // Fetch
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
///
/// row.scopes.count // 2
/// row.scopes.names // ["foo", "bar"]
@@ -550,7 +696,7 @@ extension Row {
/// row.scopes["bar"] // [bar:2]
/// row.scopes["baz"] // nil
public var scopes: ScopesView {
return impl.scopes
return impl.scopes(prefetchedRows: prefetchedRows)
}
/// Returns a view on the scopes tree defined by row adapters.
@@ -565,7 +711,7 @@ extension Row {
///
/// // Fetch
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
///
/// row.scopesTree.names // ["foo", "bar", "baz"]
///
@@ -587,7 +733,16 @@ extension Row {
/// // Success:
/// XCTAssertEqual(row.unscoped, ["id": 1, "name": "foo"])
public var unscoped: Row {
return impl.unscopedRow(self)
var row = impl.unscopedRow(self)
// Remove prefetchedRows
if row.prefetchedRows.isEmpty == false {
// Make sure we build another Row instance
row = Row(impl: row.copy().impl)
assert(row !== self)
assert(row.prefetchedRows.isEmpty)
}
return row
}
/// Return the raw row fetched from the database.
@@ -599,21 +754,23 @@ extension Row {
}
}
// MARK: - RowCursor
/// A cursor of database rows. For example:
///
/// try dbQueue.read { db in
/// let rows: RowCursor = try Row.fetchCursor(db, "SELECT * FROM player")
/// let rows: RowCursor = try Row.fetchCursor(db, sql: "SELECT * FROM player")
/// }
public final class RowCursor : Cursor {
public let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let row: Row // Reused for performance
private var done = false
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline let _row: Row // Reused for performance
@usableFromInline var _done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
self.row = try Row(statement: statement).adapted(with: adapter, layout: statement)
self.sqliteStatement = statement.sqliteStatement
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
self._sqliteStatement = statement.sqliteStatement
statement.reset(withArguments: arguments)
}
@@ -624,21 +781,21 @@ public final class RowCursor : Cursor {
}
/// :nodoc:
@inlinable
public func next() throws -> Row? {
if done {
if _done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
switch sqlite3_step(_sqliteStatement) {
case SQLITE_DONE:
done = true
_done = true
return nil
case SQLITE_ROW:
return row
return _row
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
try statement.didFail(withResultCode: code)
}
}
}
@@ -649,7 +806,7 @@ extension Row {
/// Returns a cursor over rows fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT ...")
/// let rows = try Row.fetchCursor(statement) // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row[0]
@@ -682,7 +839,7 @@ extension Row {
/// Returns an array of rows fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT ...")
/// let rows = try Row.fetchAll(statement)
///
/// - parameters:
@@ -698,7 +855,7 @@ extension Row {
/// Returns a single row fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT ...")
/// let row = try Row.fetchOne(statement)
///
/// - parameters:
@@ -722,7 +879,7 @@ extension Row {
/// Returns a cursor over rows fetched from an SQL query.
///
/// let rows = try Row.fetchCursor(db, "SELECT id, name FROM player") // RowCursor
/// let rows = try Row.fetchCursor(db, sql: "SELECT id, name FROM player") // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row[0]
/// let name: String = row[1]
@@ -744,42 +901,50 @@ extension Row {
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of rows fetched from an SQL query.
///
/// let rows = try Row.fetchAll(db, "SELECT ...")
/// let rows = try Row.fetchAll(db, sql: "SELECT id, name FROM player") // [Row]
/// for row in rows {
/// let id: Int64 = row[0]
/// let name: String = row[1]
/// }
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] {
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single row fetched from an SQL query.
///
/// let row = try Row.fetchOne(db, "SELECT ...")
/// let row = try Row.fetchOne(db, sql: "SELECT id, name FROM player") // Row?
/// if let row = row {
/// let id: Int64 = row[0]
/// let name: String = row[1]
/// }
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional row.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? {
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row? {
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -815,7 +980,7 @@ extension Row {
/// - returns: A cursor over fetched rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> RowCursor {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
return try fetchCursor(statement, adapter: adapter)
}
@@ -830,7 +995,7 @@ extension Row {
/// - returns: An array of rows.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Row] {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
return try fetchAll(statement, adapter: adapter)
}
@@ -845,18 +1010,18 @@ extension Row {
/// - returns: An optional row.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> Row? {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: true)
return try fetchOne(statement, adapter: adapter)
}
}
extension FetchRequest where RowDecoder: Row {
extension FetchRequest where RowDecoder == Row {
// MARK: Fetching Rows
/// A cursor over fetched rows.
///
/// let request: ... // Some TypedRequest that fetches Row
/// let request: ... // Some FetchRequest that fetches Row
/// let rows = try request.fetchCursor(db) // RowCursor
/// while let row = try rows.next() { // Row
/// let id: Int64 = row[0]
@@ -885,7 +1050,7 @@ extension FetchRequest where RowDecoder: Row {
/// An array of fetched rows.
///
/// let request: ... // Some TypedRequest that fetches Row
/// let request: ... // Some FetchRequest that fetches Row
/// let rows = try request.fetchAll(db)
///
/// - parameter db: A database connection.
@@ -897,11 +1062,11 @@ extension FetchRequest where RowDecoder: Row {
/// The first fetched row.
///
/// let request: ... // Some TypedRequest that fetches Row
/// let request: ... // Some FetchRequest that fetches Row
/// let row = try request.fetchOne(db)
///
/// - parameter db: A database connection.
/// - returns: A,n optional rows.
/// - returns: An optional row.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> Row? {
return try Row.fetchOne(db, self)
@@ -943,7 +1108,7 @@ extension Row {
/// Accesses the (ColumnName, DatabaseValue) pair at given index.
public subscript(position: RowIndex) -> (String, DatabaseValue) {
let index = position.index
checkIndex(index)
_checkIndex(index)
return (
impl.columnName(atUncheckedIndex: index),
impl.databaseValue(atUncheckedIndex: index))
@@ -988,13 +1153,16 @@ extension Row {
}
}
guard lhs.prefetchedRows == rhs.prefetchedRows else {
return false
}
return true
}
}
// Hashable
extension Row {
#if swift(>=4.2)
/// :nodoc:
public func hash(into hasher: inout Hasher) {
hasher.combine(count)
@@ -1003,13 +1171,6 @@ extension Row {
hasher.combine(dbValue)
}
}
#else
/// :nodoc:
public var hashValue: Int {
return columnNames.reduce(0) { (acc, column) in acc ^ column.hashValue } ^
databaseValues.reduce(0) { (acc, dbValue) in acc ^ dbValue.hashValue }
}
#endif
}
// CustomStringConvertible & CustomDebugStringConvertible
@@ -1027,7 +1188,7 @@ extension Row {
}
private func debugDescription(level: Int) -> String {
if level == 0 && self == self.unadapted {
if level == 0 && self == self.unadapted && prefetchedRows.prefetches.isEmpty {
return description
}
let prefix = repeatElement(" ", count: level + 1).joined(separator: "")
@@ -1044,6 +1205,19 @@ extension Row {
for (name, scopedRow) in scopes.sorted(by: { $0.name < $1.name }) {
str += "\n" + prefix + "- " + name + ": " + scopedRow.debugDescription(level: level + 1)
}
for key in prefetchedRows.keys.sorted() {
let rows = prefetchedRows[key]!
let prefetchedRowsDescription: String
switch rows.count {
case 0:
prefetchedRowsDescription = "0 row"
case 1:
prefetchedRowsDescription = "1 row"
case let count:
prefetchedRowsDescription = "\(count) rows"
}
str += "\n" + prefix + "+ " + key + ": \(prefetchedRowsDescription)"
}
return str
}
@@ -1101,7 +1275,7 @@ extension Row {
///
/// // Fetch
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
///
/// row.scopes.count // 2
/// row.scopes.names // ["foo", "bar"]
@@ -1113,6 +1287,7 @@ extension Row {
public typealias Index = Dictionary<String, LayoutedRowAdapter>.Index
private let row: Row
private let scopes: [String: LayoutedRowAdapter]
private let prefetchedRows: Row.PrefetchedRowsView
/// The scopes defined on this row.
public var names: Dictionary<String, LayoutedRowAdapter>.Keys {
@@ -1120,12 +1295,13 @@ extension Row {
}
init() {
self.init(row: Row(), scopes: [:])
self.init(row: Row(), scopes: [:], prefetchedRows: Row.PrefetchedRowsView())
}
init(row: Row, scopes: [String: LayoutedRowAdapter]) {
init(row: Row, scopes: [String: LayoutedRowAdapter], prefetchedRows: Row.PrefetchedRowsView) {
self.row = row
self.scopes = scopes
self.prefetchedRows = prefetchedRows
}
/// :nodoc:
@@ -1146,16 +1322,24 @@ extension Row {
/// :nodoc:
public subscript(position: Index) -> (name: String, row: Row) {
let (name, adapter) = scopes[position]
return (name: name, row: Row(base: row, adapter: adapter))
let adaptedRow = Row(base: row, adapter: adapter)
if let prefetch = prefetchedRows.prefetches[name] {
// Let the adapted row access its own prefetched rows.
// Use case:
//
// let request = A.including(required: A.b.including(all: B.c))
// let row = try Row.fetchOne(db, request)!
// row.prefetchedRows["cs"] // Some array
// row.scopes["b"]!.prefetchedRows["cs"] // The same array
adaptedRow.prefetchedRows = Row.PrefetchedRowsView(prefetches: prefetch.prefetches)
}
return (name: name, row: adaptedRow)
}
/// Returns the row associated with the given scope, or nil if the
/// scope is not defined.
public subscript(_ name: String) -> Row? {
guard let adapter = scopes[name] else {
return nil
}
return Row(base: row, adapter: adapter)
return scopes.index(forKey: name).map { self[$0].row }
}
}
}
@@ -1176,7 +1360,7 @@ extension Row {
///
/// // Fetch
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
///
/// row.scopesTree.names // ["foo", "bar", "baz"]
///
@@ -1196,9 +1380,33 @@ extension Row {
return names
}
/// Returns the row associated with the given scope, by performing a
/// breadth-first search in this row's scopes and the scopes of its
/// scoped rows, recursively.
/// Returns the row associated with the given scope.
///
/// For example:
///
/// let request = Book.including(required: Book.author)
/// let row = try Row.fetchOne(db, request)!
///
/// print(row)
/// // Prints [id:42 title:"Moby-Dick"]
///
/// let authorRow = row.scopesTree["author"]
/// print(authorRow)
/// // Prints [id:1 name:"Herman Melville"]
///
/// Associated rows stored in nested associations are available, too:
///
/// let request = Book.including(required: Book.author.including(required: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// print(row)
/// // Prints [id:42 title:"Moby-Dick"]
///
/// let countryRow = row.scopesTree["country"]
/// print(countryRow)
/// // Prints [code:"US" name:"United States"]
///
/// Nil is returned if the scope is not available.
public subscript(_ name: String) -> Row? {
var fifo = Array(scopes)
while !fifo.isEmpty {
@@ -1213,13 +1421,117 @@ extension Row {
}
}
// MARK: - Row.PrefetchedRowsView
extension Row {
fileprivate struct Prefetch: Equatable {
// Nil for intermediate associations
var rows: [Row]?
// OrderedDictionary so that breadth-first search gives a consistent result
// (we preserve the ordering of associations in the request)
var prefetches: OrderedDictionary<String, Prefetch>
}
/// A view on the prefetched associated rows.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// print(row)
/// // Prints [id:1 name:"Herman Melville"]
///
/// let bookRows = row.prefetchedRows["books"]
/// print(bookRows[0])
/// // Prints [id:42 title:"Moby-Dick"]
public struct PrefetchedRowsView: Equatable {
// OrderedDictionary so that breadth-first search gives a consistent result
// (we preserve the ordering of associations in the request)
fileprivate var prefetches: OrderedDictionary<String, Prefetch> = [:]
/// True if there is no prefetched associated rows.
public var isEmpty: Bool {
return prefetches.isEmpty
}
/// The keys for available prefetched rows
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// print(row.prefetchedRows.keys)
/// // Prints ["books"]
public var keys: Set<String> {
var result: Set<String> = []
var fifo = Array(prefetches)
while !fifo.isEmpty {
let (prefetchKey, prefetch) = fifo.removeFirst()
if prefetch.rows != nil {
result.insert(prefetchKey)
}
fifo.append(contentsOf: prefetch.prefetches)
}
return result
}
/// Returns the prefetched rows associated with the given key.
///
/// For example:
///
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// print(row)
/// // Prints [id:1 name:"Herman Melville"]
///
/// let bookRows = row.prefetchedRows["books"]
/// print(bookRows[0])
/// // Prints [id:42 title:"Moby-Dick"]
///
/// Prefetched rows stored in nested "to-one" associations are
/// available, too.
///
/// Nil is returned if the key is not available.
public subscript(_ key: String) -> [Row]? {
var fifo = Array(prefetches)
while !fifo.isEmpty {
let (prefetchKey, prefetch) = fifo.removeFirst()
if prefetchKey == key {
return prefetch.rows
}
fifo.append(contentsOf: prefetch.prefetches)
}
return nil
}
mutating func setRows(_ rows: [Row], forKeyPath keyPath: [String]) {
prefetches.setRows(rows, forKeyPath: keyPath)
}
}
}
extension OrderedDictionary where Key == String, Value == Row.Prefetch {
fileprivate mutating func setRows(_ rows: [Row], forKeyPath keyPath: [String]) {
var keyPath = keyPath
let key = keyPath.removeFirst()
if keyPath.isEmpty {
self[key, default: Row.Prefetch(rows: nil, prefetches: [:])].rows = rows
} else {
self[key, default: Row.Prefetch(rows: nil, prefetches: [:])].prefetches.setRows(rows, forKeyPath: keyPath)
}
}
}
// MARK: - RowImpl
// The protocol for Row underlying implementation
protocol RowImpl {
var count: Int { get }
var isFetched: Bool { get }
var scopes: Row.ScopesView { get }
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView
func columnName(atUncheckedIndex index: Int) -> String
func hasNull(atUncheckedIndex index:Int) -> Bool
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue
@@ -1252,7 +1564,7 @@ extension RowImpl {
return row
}
var scopes: Row.ScopesView {
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView {
// unless customized, assume unuscoped row (see AdaptedRowImpl for customization)
return Row.ScopesView()
}
@@ -1317,7 +1629,7 @@ private struct ArrayRowImpl : RowImpl {
func index(ofColumn name: String) -> Int? {
let lowercaseName = name.lowercased()
return columns.index { (column, _) in column.lowercased() == lowercaseName }
return columns.firstIndex { (column, _) in column.lowercased() == lowercaseName }
}
func copiedRow(_ row: Row) -> Row {
@@ -1356,7 +1668,7 @@ private struct StatementCopyRowImpl : RowImpl {
func index(ofColumn name: String) -> Int? {
let lowercaseName = name.lowercased()
return columnNames.index { $0.lowercased() == lowercaseName }
return columnNames.firstIndex { $0.lowercased() == lowercaseName }
}
func copiedRow(_ row: Row) -> Row {
@@ -1415,7 +1727,7 @@ private struct StatementRowImpl : RowImpl {
_ type: Value.Type,
atUncheckedIndex index: Int) -> Value
{
return Value.fastDecode(from: sqliteStatement, index: Int32(index))
return Value.fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
}
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
+12 -12
View File
@@ -13,7 +13,7 @@ import Foundation
/// "b": adapters[1],
/// "c": adapters[2],
/// "d": adapters[3]])
/// let row = try Row.fetchOne(db, sql, adapter: adapter)
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)
/// row.scopes["a"] // [1]
/// row.scopes["b"] // [2, 3, 4]
/// row.scopes["c"] // [5, 6]
@@ -78,7 +78,7 @@ public struct LayoutedColumnMapping {
/// }
///
/// // [foo:"foo" bar: "bar"]
/// try Row.fetchOne(db, "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
/// try Row.fetchOne(db, sql: "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
public init<S: Sequence>(layoutColumns: S) where S.Iterator.Element == (Int, String) {
self.layoutColumns = Array(layoutColumns)
self.lowercaseColumnIndexes = Dictionary(
@@ -201,7 +201,7 @@ extension SelectStatement : RowLayout {
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
///
/// // [baz:3]
/// try Row.fetchOne(db, sql, adapter: adapter)
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public protocol RowAdapter {
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
@@ -224,7 +224,7 @@ public protocol RowAdapter {
/// }
///
/// // [foo:1]
/// try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
/// try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
func layoutedAdapter(from layout: RowLayout) throws -> LayoutedRowAdapter
}
@@ -269,7 +269,7 @@ public struct EmptyRowAdapter: RowAdapter {
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar, 'baz' AS baz"
///
/// // [foo:"bar"]
/// try Row.fetchOne(db, sql, adapter: adapter)
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public struct ColumnMapping : RowAdapter {
/// A dictionary from mapped column names to column names in a base row.
let mapping: [String: String]
@@ -303,7 +303,7 @@ public struct ColumnMapping : RowAdapter {
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
///
/// // [baz:3]
/// try Row.fetchOne(db, sql, adapter: adapter)
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public struct SuffixRowAdapter : RowAdapter {
/// The suffix index
let index: Int
@@ -330,7 +330,7 @@ public struct SuffixRowAdapter : RowAdapter {
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz, 4 as qux"
///
/// // [bar:2 baz:3]
/// try Row.fetchOne(db, sql, adapter: adapter)
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
public struct RangeRowAdapter : RowAdapter {
/// The range
let range: CountableRange<Int>
@@ -367,7 +367,7 @@ public struct RangeRowAdapter : RowAdapter {
///
/// // Fetch
/// let sql = "SELECT 'foo' AS foo, 'bar' AS bar"
/// let row = try Row.fetchOne(db, sql, adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)!
///
/// // Scoped rows:
/// if let fooRow = row.scopes["foo"] {
@@ -389,7 +389,7 @@ public struct ScopeAdapter : RowAdapter {
/// For example:
///
/// let adapter = ScopeAdapter(["suffix": SuffixRowAdapter(fromIndex: 1)])
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: adapter)!
/// row // [1, 2, 3]
/// row.scopes["suffix"] // [2, 3]
///
@@ -406,7 +406,7 @@ public struct ScopeAdapter : RowAdapter {
///
/// let baseAdapter = RangeRowAdapter(0..<1)
/// let adapter = ScopeAdapter(base: baseAdapter, scopes: ["suffix": SuffixRowAdapter(fromIndex: 1)])
/// let row = try Row.fetchOne(db, "SELECT 1, 2, 3", adapter: adapter)!
/// let row = try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: adapter)!
/// row // [1]
/// row.scopes["initial"] // [2, 3]
///
@@ -487,8 +487,8 @@ struct AdaptedRowImpl : RowImpl {
return base.isFetched
}
var scopes: Row.ScopesView {
return Row.ScopesView(row: base, scopes: adapter.scopes)
func scopes(prefetchedRows: Row.PrefetchedRowsView) -> Row.ScopesView {
return Row.ScopesView(row: base, scopes: adapter.scopes, prefetchedRows: prefetchedRows)
}
func hasNull(atUncheckedIndex index: Int) -> Bool {
+33
View File
@@ -0,0 +1,33 @@
#if swift(>=5.0)
/// :nodoc:
public struct SQLInterpolation: StringInterpolationProtocol {
var context = SQLGenerationContext.literalGenerationContext(withArguments: true)
var sql: String
var arguments: StatementArguments {
get { return context.arguments! }
set { context.arguments = newValue }
}
public init(literalCapacity: Int, interpolationCount: Int) {
sql = ""
sql.reserveCapacity(literalCapacity + interpolationCount)
}
/// "SELECT * FROM player"
public mutating func appendLiteral(_ sql: String) {
self.sql += sql
}
/// "SELECT * FROM \(sql: "player")"
public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) {
self.sql += sql
self.arguments += arguments
}
/// "SELECT * FROM player WHERE \(literal: condition)"
public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) {
sql += sqlLiteral.sql
arguments += sqlLiteral.arguments
}
}
#endif
+145
View File
@@ -0,0 +1,145 @@
/// SQLLiteral is a type which support [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
///
/// For example:
///
/// try dbQueue.write { db in
/// let name: String = ...
/// let id: Int64 = ...
/// let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
/// try db.execute(literal: query)
/// }
public struct SQLLiteral {
private(set) public var sql: String
private(set) public var arguments: StatementArguments
/// Creates an SQLLiteral from a plain SQL string, and eventual arguments.
///
/// For example:
///
/// let query = SQLLiteral(
/// sql: "UPDATE player SET name = ? WHERE id = ?",
/// arguments: [name, id])
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
self.sql = sql
self.arguments = arguments
}
/// Returns a literal whose SQL is transformed by the given closure.
public func mapSQL(_ transform: (String) throws -> String) rethrows -> SQLLiteral {
var result = self
result.sql = try transform(sql)
return result
}
}
extension SQLLiteral {
/// Returns the SQLLiteral produced by the concatenation of two literals.
///
/// let name = "O'Brien"
/// let selection: SQLLiteral = "SELECT * FROM player "
/// let condition: SQLLiteral = "WHERE name = \(name)"
/// let query = selection + condition
public static func + (lhs: SQLLiteral, rhs: SQLLiteral) -> SQLLiteral {
var result = lhs
result += rhs
return result
}
/// Appends an SQLLiteral to the receiver.
///
/// let name = "O'Brien"
/// var query: SQLLiteral = "SELECT * FROM player "
/// query += "WHERE name = \(name)"
public static func += (lhs: inout SQLLiteral, rhs: SQLLiteral) {
lhs.sql += rhs.sql
lhs.arguments += rhs.arguments
}
/// Appends an SQLLiteral to the receiver.
///
/// let name = "O'Brien"
/// var query: SQLLiteral = "SELECT * FROM player "
/// query.append(literal: "WHERE name = \(name)")
public mutating func append(literal sqlLiteral: SQLLiteral) {
self += sqlLiteral
}
/// Appends a plain SQL string to the receiver, and eventual arguments.
///
/// let name = "O'Brien"
/// var query: SQLLiteral = "SELECT * FROM player "
/// query.append(sql: "WHERE name = ?", arguments: [name])
public mutating func append(sql: String, arguments: StatementArguments = StatementArguments()) {
self += SQLLiteral(sql: sql, arguments: arguments)
}
}
extension Sequence where Element == SQLLiteral {
/// Returns the concatenated SQLLiteral of this sequence of literals,
/// inserting the given separator between each element.
///
/// let components: [SQLLiteral] = [
/// "UPDATE player",
/// "SET name = \(name)",
/// "WHERE id = \(id)"
/// ]
/// let query = components.joined(separator: " ")
public func joined(separator: String = "") -> SQLLiteral {
var sql = ""
var arguments = StatementArguments()
var first = true
for literal in self {
if first {
first = false
} else {
sql += separator
}
sql += literal.sql
arguments += literal.arguments
}
return SQLLiteral(sql: sql, arguments: arguments)
}
}
extension Collection where Element == SQLLiteral {
/// Returns the concatenated SQLLiteral of this collection of literals,
/// inserting the given separator between each element.
///
/// let components: [SQLLiteral] = [
/// "UPDATE player",
/// "SET name = \(name)",
/// "WHERE id = \(id)"
/// ]
/// let query = components.joined(separator: " ")
public func joined(separator: String = "") -> SQLLiteral {
let sql = map { $0.sql }.joined(separator: separator)
let arguments = reduce(into: StatementArguments()) { $0 += $1.arguments }
return SQLLiteral(sql: sql, arguments: arguments)
}
}
// MARK: - ExpressibleByStringInterpolation
#if swift(>=5.0)
extension SQLLiteral: ExpressibleByStringInterpolation {
/// :nodoc
public init(unicodeScalarLiteral: String) {
self.init(sql: unicodeScalarLiteral, arguments: [])
}
/// :nodoc:
public init(extendedGraphemeClusterLiteral: String) {
self.init(sql: extendedGraphemeClusterLiteral, arguments: [])
}
/// :nodoc:
public init(stringLiteral: String) {
self.init(sql: stringLiteral, arguments: [])
}
/// :nodoc:
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
self.init(sql: sqlInterpolation.sql, arguments: sqlInterpolation.arguments)
}
}
#endif
+168
View File
@@ -0,0 +1,168 @@
/// A FetchRequest built from raw SQL.
public struct SQLRequest<T> : FetchRequest {
/// 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`
}
public typealias RowDecoder = T
/// The raw SQL query
///
/// let id = 42
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
/// request.sql // "SELECT * FROM player WHERE id = ?"
public var sql: String { return sqlLiteral.sql }
/// The request argument
///
/// let id = 42
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
/// request.arguments // [42]
public var arguments: StatementArguments { return sqlLiteral.arguments }
/// The request adapter
public var adapter: RowAdapter?
private var sqlLiteral: SQLLiteral
private let cache: Cache?
/// Creates a request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest<String>(sql: """
/// SELECT name FROM player
/// """)
/// let request = SQLRequest<Player>(sql: """
/// SELECT * FROM player WHERE id = ?
/// """, arguments: [1])
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: A SQLRequest
public init(sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(literal: SQLLiteral(sql: sql, arguments: arguments), adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates a request from an SQLLiteral, and optional row adapter.
///
/// let request = SQLRequest<String>(literal: SQLLiteral(sql: """
/// SELECT name FROM player
/// """))
/// let request = SQLRequest<Player>(literal: SQLLiteral(sql: """
/// SELECT * FROM player WHERE name = ?
/// """, arguments: ["O'Brien"]))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// let request = SQLRequest<Player>(literal: """
/// SELECT * FROM player WHERE name = \("O'brien")
/// """)
///
/// - parameters:
/// - sqlLiteral: An SQLLiteral.
/// - adapter: Optional RowAdapter.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: A SQLRequest
public init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates an SQL request from any other fetch request.
///
/// - parameters:
/// - db: A database connection.
/// - request: A request.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - returns: An SQLRequest
public init<Request: FetchRequest>(_ db: Database, request: Request, cached: Bool = false) throws where Request.RowDecoder == RowDecoder {
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
self.init(literal: SQLLiteral(sql: statement.sql, arguments: statement.arguments), adapter: adapter, cached: cached)
}
/// Creates a request from an SQLLiteral, and optional row adapter.
///
/// let request = SQLRequest<String>(literal: SQLLiteral(sql: """
/// SELECT name FROM player
/// """))
/// let request = SQLRequest<Player>(literal: SQLLiteral(sql: """
/// SELECT * FROM player WHERE name = ?
/// """, arguments: ["O'Brien"]))
///
/// With Swift 5, you can safely embed raw values in your SQL queries,
/// without any risk of syntax errors or SQL injection:
///
/// let request = SQLRequest<Player>(literal: """
/// SELECT * FROM player WHERE name = \("O'brien")
/// """)
///
/// - parameters:
/// - sqlLiteral: An SQLLiteral.
/// - adapter: Optional RowAdapter.
/// - cache: The eventual cache
/// - returns: A SQLRequest
init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
self.sqlLiteral = sqlLiteral
self.adapter = adapter
self.cache = cache
}
/// A tuple that contains a prepared statement that is ready to be
/// executed, and an eventual row adapter.
///
/// - parameter db: A database connection.
/// - parameter singleResult: SQLRequest disregards this hint.
///
/// :nodoc:
public func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) {
let statement: SelectStatement
switch cache {
case .none:
statement = try db.makeSelectStatement(sql: sqlLiteral.sql)
case .public?:
statement = try db.cachedSelectStatement(sql: sqlLiteral.sql)
case .internal?:
statement = try db.internalCachedSelectStatement(sql: sqlLiteral.sql)
}
try statement.setArgumentsWithValidation(sqlLiteral.arguments)
return (statement, adapter)
}
}
#if swift(>=5.0)
extension SQLRequest: ExpressibleByStringInterpolation {
/// :nodoc
public init(unicodeScalarLiteral: String) {
self.init(sql: unicodeScalarLiteral)
}
/// :nodoc:
public init(extendedGraphemeClusterLiteral: String) {
self.init(sql: extendedGraphemeClusterLiteral)
}
/// :nodoc:
public init(stringLiteral: String) {
self.init(sql: stringLiteral)
}
/// :nodoc:
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
self.init(literal: SQLLiteral(stringInterpolation: sqlInterpolation))
}
}
#endif
+1 -1
View File
@@ -44,7 +44,7 @@ final class SchedulingWatchdog {
}
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(current?.allows(db) ?? false, message, file: file, line: line)
GRDBPrecondition(current?.allows(db) ?? false, message(), file: file, line: line)
}
static var current: SchedulingWatchdog? {
+8 -3
View File
@@ -42,7 +42,12 @@ final class SerializedDatabase {
self.queue = configuration.makeDispatchQueue(defaultLabel: defaultLabel, purpose: purpose)
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
try queue.sync {
try db.setup()
do {
try db.setup()
} catch {
db.close()
throw error
}
}
}
@@ -189,11 +194,11 @@ final class SerializedDatabase {
/// Fatal error if current dispatch queue is not valid.
func preconditionValidQueue(_ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
SchedulingWatchdog.preconditionValidQueue(db, message, file: file, line: line)
SchedulingWatchdog.preconditionValidQueue(db, message(), file: file, line: line)
}
/// Fatal error if a transaction has been left opened.
private func preconditionNoUnsafeTransactionLeft(_ db: Database, _ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access", file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message, file: file, line: line)
GRDBPrecondition(configuration.allowsUnsafeTransactions || !db.isInsideTransaction, message(), file: file, line: line)
}
}
+127 -135
View File
@@ -1,6 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -8,11 +10,9 @@ import Foundation
/// A raw SQLite statement, suitable for the SQLite C API.
public typealias SQLiteStatement = OpaquePointer
/// Statements are separated by semicolons and white spaces
let statementSeparatorCharacterSet = CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines)
/// An error emitted when one tries to compile an empty statement.
struct EmptyStatementError : Error {
extension CharacterSet {
/// Statements are separated by semicolons and white spaces
static let sqlStatementSeparators = CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines)
}
/// A statement represents an SQL query.
@@ -28,12 +28,13 @@ public class Statement {
public var sql: String {
// trim white space and semicolumn for homogeneous output
return String(cString: sqlite3_sql(sqliteStatement))
.trimmingCharacters(in: statementSeparatorCharacterSet)
.trimmingCharacters(in: .sqlStatementSeparators)
}
unowned let database: Database
/// Creates a prepared statement.
/// Creates a prepared statement. Returns nil if the compiled string is
/// blank or empty.
///
/// - parameter database: A database connection.
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
@@ -42,23 +43,27 @@ public class Statement {
/// statement in the C string.
/// - 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, and
/// EmptyStatementError if the compiled string is blank or empty.
init(
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32) throws
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
{
SchedulingWatchdog.preconditionValidQueue(database)
var sqliteStatement: SQLiteStatement? = nil
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd)
let code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd)
#else
// TODO: use sqlite3_prepare_v3 if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *)
let code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
let code: Int32
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
code = sqlite3_prepare_v3(database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags), &sqliteStatement, statementEnd)
} else {
code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
}
#endif
guard code == SQLITE_OK else {
@@ -66,13 +71,7 @@ public class Statement {
}
guard let statement = sqliteStatement else {
// I wish we could simply return nil, and make this initializer failable.
//
// Unfortunately, there is a Swift bug with failable+throwing initializers:
// https://bugs.swift.org/browse/SR-6067
//
// We thus use sentinel error for empty statements.
throw EmptyStatementError()
return nil
}
self.database = database
@@ -95,7 +94,7 @@ public class Statement {
// MARK: Arguments
var argumentsNeedValidation = true
var _arguments: StatementArguments = []
var _arguments = StatementArguments()
lazy var sqliteArgumentCount: Int = {
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
@@ -125,7 +124,7 @@ public class Statement {
/// statement arguments.
public func validate(arguments: StatementArguments) throws {
var arguments = arguments
_ = try arguments.consume(self, allowingRemainingValues: false)
_ = try arguments.extractBindings(forStatement: self, allowingRemainingValues: false)
}
/// Set arguments without any validation. Trades safety for performance.
@@ -152,7 +151,7 @@ public class Statement {
// Validate
_arguments = arguments
var arguments = arguments
let bindings = try arguments.consume(self, allowingRemainingValues: false)
let bindings = try arguments.extractBindings(forStatement: self, allowingRemainingValues: false)
argumentsNeedValidation = false
// Apply
@@ -176,9 +175,15 @@ public class Statement {
case .string(let string):
code = sqlite3_bind_text(sqliteStatement, index, string, -1, SQLITE_TRANSIENT)
case .blob(let data):
code = data.withUnsafeBytes { bytes in
sqlite3_bind_blob(sqliteStatement, index, bytes, Int32(data.count), SQLITE_TRANSIENT)
#if swift(>=5.0)
code = data.withUnsafeBytes {
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
}
#else
code = data.withUnsafeBytes {
sqlite3_bind_blob(sqliteStatement, index, $0, Int32(data.count), SQLITE_TRANSIENT)
}
#endif
}
// It looks like sqlite3_bind_xxx() functions do not access the file system.
@@ -210,48 +215,30 @@ public class Statement {
}
}
// MARK: - AuthorizedStatement
// MARK: - Statement Preparation
/// A common protocol for UpdateStatement and SelectStatement
protocol AuthorizedStatement {
// This initializer should be a required initializer of Statement.
//
// But Swift requires this required initializer to be public:
// https://bugs.swift.org/browse/SR-2347
//
// We work around SR-2347 with this internal protocol.
//
// TODO: hasn't this bug been fixed in Swift 4.2? https://github.com/apple/swift/blob/master/CHANGELOG.md#swift-42
init(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
}
extension AuthorizedStatement {
// Static function instead of an initializer because initializer doesn't
// compile due to the "capturing of an uninitialized self" in
// `sqlCodeUnits.withUnsafeBufferPointer`.
/// A common protocol for UpdateStatement and SelectStatement, only used as
/// support for SelectStatement.prepare(...) and UpdateStatement.prepare(...).
protocol StatementProtocol { }
extension Statement: StatementProtocol { }
extension StatementProtocol where Self: Statement {
// Static method instead of an initializer because initializer can't run
// inside `sqlCodeUnits.withUnsafeBufferPointer`.
static func prepare(sql: String, prepFlags: Int32, in database: Database) throws -> Self {
let authorizer = StatementCompilationAuthorizer()
database.authorizer = authorizer
defer { database.authorizer = nil }
let sqlCodeUnits = sql.utf8CString
return try sqlCodeUnits.withUnsafeBufferPointer { codeUnits in
let statementStart = UnsafePointer<Int8>(codeUnits.baseAddress)!
return try sql.utf8CString.withUnsafeBufferPointer { buffer in
let statementStart = buffer.baseAddress!
var statementEnd: UnsafePointer<Int8>? = nil
let statement: Self
do {
statement = try self.init(
database: database,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: authorizer)
} catch is EmptyStatementError {
guard let statement = try self.init(
database: database,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: authorizer) else
{
throw DatabaseError(
resultCode: .SQLITE_ERROR,
message: "empty statement",
@@ -259,18 +246,11 @@ extension AuthorizedStatement {
arguments: nil)
}
let remainingData = Data(
bytesNoCopy: UnsafeMutableRawPointer(mutating: statementEnd!),
count: statementStart + sqlCodeUnits.count - statementEnd! - 1,
deallocator: .none)
let remainingSQL = String(data: remainingData, encoding: .utf8)!
.trimmingCharacters(in: statementSeparatorCharacterSet)
let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators)
guard remainingSQL.isEmpty else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: "Multiple statements found. To execute multiple statements, use Database.execute() instead.",
message: "Multiple statements found. To execute multiple statements, use Database.execute(sql:) instead.",
sql: sql,
arguments: nil)
}
@@ -287,15 +267,16 @@ extension AuthorizedStatement {
/// You create SelectStatement with the Database.makeSelectStatement() method:
///
/// try dbQueue.read { db in
/// let statement = try db.makeSelectStatement("SELECT COUNT(*) FROM player WHERE score > ?")
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
/// }
public final class SelectStatement : Statement {
/// The database region that the statement looks into.
public private(set) var databaseRegion: DatabaseRegion
public private(set) var databaseRegion = DatabaseRegion()
/// Creates a prepared statement.
/// Creates a prepared statement. Returns nil if the compiled string is
/// blank or empty.
///
/// - parameter database: A database connection.
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
@@ -305,21 +286,20 @@ public final class SelectStatement : Statement {
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error, and
/// EmptyStatementError if the compiled string is blank or empty.
init(
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
{
self.databaseRegion = DatabaseRegion()
try super.init(
database: database,
statementStart: statementStart,
statementEnd: statementEnd,
prepFlags: prepFlags)
prepFlags: prepFlags,
authorizer: authorizer)
GRDBPrecondition(authorizer.invalidatesDatabaseSchemaCache == false, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
GRDBPrecondition(authorizer.transactionEffect == nil, "Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
@@ -351,9 +331,9 @@ public final class SelectStatement : Statement {
return columnIndexes[name.lowercased()]
}
/// Creates a cursor over the statement. This cursor does not produce any
/// value, and is only intended to give access to the sqlite3_step()
/// low-level function.
/// Creates a cursor over the statement which does not produce any
/// value. Each call to the next() cursor method calls the sqlite3_step()
/// C function.
func makeCursor(arguments: StatementArguments? = nil) -> StatementCursor {
return StatementCursor(statement: self, arguments: arguments)
}
@@ -363,53 +343,64 @@ public final class SelectStatement : Statement {
prepare(withArguments: arguments)
try! reset()
}
/// Utility function for cursors
@usableFromInline
func didFail(withResultCode resultCode: Int32) throws -> Never {
database.selectStatementDidFail(self)
throw DatabaseError(
resultCode: resultCode,
message: database.lastErrorMessage,
sql: sql,
arguments: arguments)
}
}
// Hide AuthorizedStatement from Jazzy
extension SelectStatement: AuthorizedStatement { }
// TODO: remove public qualifier, or expose SelectStatement.makeCursor()
/// A cursor that iterates a database statement without producing any value.
/// Each call to the next() cursor method calls the sqlite3_step() C function.
///
/// For example:
///
/// try dbQueue.read { db in
/// let statement = db.makeSelectStatement("SELECT * FROM player")
/// let cursor: StatementCursor = statement.makeCursor()
/// let statement = db.makeSelectStatement(sql: "SELECT performSideEffect()")
/// let cursor = statement.makeCursor()
/// try cursor.next()
/// }
public final class StatementCursor: Cursor {
public let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private var done = false
final class StatementCursor: Cursor {
let _statement: SelectStatement
let _sqliteStatement: SQLiteStatement
var _done = false
// Use SelectStatement.cursor() instead
fileprivate init(statement: SelectStatement, arguments: StatementArguments? = nil) {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
statement.reset(withArguments: arguments)
// Use SelectStatement.makeCursor() instead
init(statement: SelectStatement, arguments: StatementArguments? = nil) {
_statement = statement
_sqliteStatement = statement.sqliteStatement
_statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? statement.reset()
try? _statement.reset()
}
/// :nodoc:
public func next() throws -> Void? {
if done {
@inlinable
func next() throws -> Void? {
if _done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
switch sqlite3_step(_sqliteStatement) {
case SQLITE_DONE:
done = true
_done = true
return nil
case SQLITE_ROW:
return .some(())
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
try _statement.didFail(withResultCode: code)
}
}
}
@@ -422,7 +413,7 @@ public final class StatementCursor: Cursor {
/// You create UpdateStatement with the Database.makeUpdateStatement() method:
///
/// try dbQueue.inTransaction { db in
/// let statement = try db.makeUpdateStatement("INSERT INTO player (name) VALUES (?)")
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
/// return .commit
@@ -439,12 +430,13 @@ public final class UpdateStatement : Statement {
/// If true, the database schema cache gets invalidated after this statement
/// is executed.
private(set) var invalidatesDatabaseSchemaCache: Bool
private(set) var invalidatesDatabaseSchemaCache: Bool = false
private(set) var transactionEffect: TransactionEffect?
private(set) var databaseEventKinds: [DatabaseEventKind]
private(set) var databaseEventKinds: [DatabaseEventKind] = []
/// Creates a prepared statement.
/// Creates a prepared statement. Returns nil if the compiled string is
/// blank or empty.
///
/// - parameter database: A database connection.
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
@@ -454,22 +446,20 @@ public final class UpdateStatement : Statement {
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error, and
/// EmptyStatementError if the compiled string is blank or empty.
init(
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
{
self.invalidatesDatabaseSchemaCache = false
self.databaseEventKinds = []
try super.init(
database: database,
statementStart: statementStart,
statementEnd: statementEnd,
prepFlags: prepFlags)
prepFlags: prepFlags,
authorizer: authorizer)
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.transactionEffect = authorizer.transactionEffect
self.databaseEventKinds = authorizer.databaseEventKinds
@@ -477,7 +467,7 @@ public final class UpdateStatement : Statement {
/// Executes the SQL query.
///
/// - parameter arguments: Statement arguments.
/// - parameter arguments: Optional statement arguments.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(arguments: StatementArguments? = nil) throws {
SchedulingWatchdog.preconditionValidQueue(database)
@@ -491,17 +481,17 @@ public final class UpdateStatement : Statement {
// The statement did return a row, and the user ignores the
// content of this row:
//
// try db.execute("SELECT ...")
// try db.execute(sql: "SELECT ...")
//
// That's OK: maybe the selected rows perform side effects.
// For example:
//
// try db.execute("SELECT sqlcipher_export(...)")
// try db.execute(sql: "SELECT sqlcipher_export(...)")
//
// Or maybe the user doesn't know that the executed statement
// return rows (https://github.com/groue/GRDB.swift/issues/15);
//
// try db.execute("PRAGMA journal_mode=WAL")
// try db.execute(sql: "PRAGMA journal_mode=WAL")
//
// It is thus important that we consume *all* rows.
continue
@@ -518,10 +508,6 @@ public final class UpdateStatement : Statement {
}
}
// Hide AuthorizedStatement from Jazzy
extension UpdateStatement: AuthorizedStatement { }
// MARK: - StatementArguments
/// StatementArguments provide values to argument placeholders in raw
@@ -542,12 +528,12 @@ extension UpdateStatement: AuthorizedStatement { }
/// To fill question marks placeholders, feed StatementArguments with an array:
///
/// db.execute(
/// "INSERT ... (?, ?)",
/// sql: "INSERT ... (?, ?)",
/// arguments: StatementArguments(["Arthur", 41]))
///
/// // Array literals are automatically converted:
/// db.execute(
/// "INSERT ... (?, ?)",
/// sql: "INSERT ... (?, ?)",
/// arguments: ["Arthur", 41])
///
/// ## Named Arguments
@@ -555,12 +541,12 @@ extension UpdateStatement: AuthorizedStatement { }
/// To fill named arguments, feed StatementArguments with a dictionary:
///
/// db.execute(
/// "INSERT ... (:name, :score)",
/// sql: "INSERT ... (:name, :score)",
/// arguments: StatementArguments(["name": "Arthur", "score": 41]))
///
/// // Dictionary literals are automatically converted:
/// db.execute(
/// "INSERT ... (:name, :score)",
/// sql: "INSERT ... (:name, :score)",
/// arguments: ["name": "Arthur", "score": 41])
///
/// ## Concatenating Arguments
@@ -570,7 +556,7 @@ extension UpdateStatement: AuthorizedStatement { }
///
/// var arguments: StatementArguments = ["Arthur"]
/// arguments += [41]
/// db.execute("INSERT ... (?, ?)", arguments: arguments)
/// db.execute(sql: "INSERT ... (?, ?)", arguments: arguments)
///
/// `+` and `+=` operators consider that overriding named arguments is a
/// programmer error:
@@ -593,7 +579,7 @@ extension UpdateStatement: AuthorizedStatement { }
///
/// let sql = "SELECT ?2 AS two, :foo AS foo, ?1 AS one, :foo AS foo2, :bar AS bar"
/// var arguments: StatementArguments = [1, 2, "bar"] + ["foo": "foo"]
/// let row = try Row.fetchOne(db, sql, arguments: arguments)!
/// let row = try Row.fetchOne(db, sql: sql, arguments: arguments)!
/// print(row)
/// // Prints [two:2 foo:"foo" one:1 foo2:"foo" bar:"bar"]
///
@@ -615,7 +601,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
// MARK: Empty Arguments
/// Creates empty StatementArguments.
init() {
public init() {
}
// MARK: Positional Arguments
@@ -623,7 +609,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
/// Creates statement arguments from a sequence of optional values.
///
/// let values: [DatabaseValueConvertible?] = ["foo", 1, nil]
/// db.execute("INSERT ... (?,?,?)", arguments: StatementArguments(values))
/// db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
/// - returns: A StatementArguments.
@@ -634,7 +620,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
/// Creates statement arguments from a sequence of optional values.
///
/// let values: [String] = ["foo", "bar"]
/// db.execute("INSERT ... (?,?)", arguments: StatementArguments(values))
/// db.execute(sql: "INSERT ... (?,?)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
/// - returns: A StatementArguments.
@@ -665,7 +651,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
/// such as a dictionary.
///
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
/// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of (key, value) pairs
/// - returns: A StatementArguments.
@@ -677,7 +663,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
/// as a dictionary.
///
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
/// db.execute("INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
/// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
///
/// - parameter sequence: A sequence of (key, value) pairs
/// - returns: A StatementArguments.
@@ -863,7 +849,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
// MARK: Not Public
mutating func consume(_ statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] {
mutating func extractBindings(forStatement statement: Statement, allowingRemainingValues: Bool) throws -> [DatabaseValue] {
let initialValuesCount = values.count
let bindings = try statement.sqliteArgumentNames.map { argumentName -> DatabaseValue in
if let argumentName = argumentName {
@@ -893,7 +879,10 @@ public struct StatementArguments: CustomStringConvertible, Equatable, Expressibl
extension StatementArguments {
/// Returns a StatementArguments from an array literal:
///
/// db.selectRows("SELECT ...", arguments: ["Arthur", 41])
/// let arguments: StatementArguments = ["Arthur", 41]
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)"
/// arguments: arguments)
public init(arrayLiteral elements: DatabaseValueConvertible?...) {
self.init(elements)
}
@@ -903,7 +892,10 @@ extension StatementArguments {
extension StatementArguments {
/// Returns a StatementArguments from a dictionary literal:
///
/// db.selectRows("SELECT ...", arguments: ["name": "Arthur", "score": 41])
/// let arguments: StatementArguments = ["name": "Arthur", "score": 41]
/// try db.execute(
/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)"
/// arguments: arguments)
public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) {
self.init(elements)
}
+2
View File
@@ -3,6 +3,8 @@
#endif
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
+77 -81
View File
@@ -1,5 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -13,11 +15,11 @@
/// DatabaseValueConvertible. GRDB will then automatically apply the
/// optimization whenever direct access to SQLite is possible:
///
/// let rows = Row.fetchCursor(db, "SELECT ...")
/// let rows = Row.fetchCursor(db, sql: "SELECT ...")
/// while let row = try rows.next() {
/// let int: Int = row[0] // there
/// }
/// let ints = Int.fetchAll(db, "SELECT ...") // there
/// let ints = Int.fetchAll(db, sql: "SELECT ...") // there
/// struct Player {
/// init(row: Row) {
/// name = row["name"] // there
@@ -54,114 +56,108 @@ public protocol StatementColumnConvertible {
/// For example:
///
/// try dbQueue.read { db in
/// let names: ColumnCursor<String> = try String.fetchCursor(db, "SELECT name FROM player")
/// let names: ColumnCursor<String> = try String.fetchCursor(db, sql: "SELECT name FROM player")
/// while let name = names.next() { // String
/// print(name)
/// }
/// }
public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
private let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let columnIndex: Int32
private var done = false
@usableFromInline let _statement: SelectStatement
@usableFromInline let _columnIndex: Int32
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline var _done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
_statement = statement
_sqliteStatement = statement.sqliteStatement
if let adapter = adapter {
// adapter may redefine the index of the leftmost column
self.columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
_columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
} else {
self.columnIndex = 0
_columnIndex = 0
}
statement.reset(withArguments: arguments)
_statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? statement.reset()
try? _statement.reset()
}
/// :nodoc:
@inlinable
public func next() throws -> Value? {
if done {
if _done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
switch sqlite3_step(_sqliteStatement) {
case SQLITE_DONE:
done = true
_done = true
return nil
case SQLITE_ROW:
return Value.fastDecode(from: sqliteStatement, index: columnIndex)
return Value.fastDecode(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
try _statement.didFail(withResultCode: code)
}
}
}
@available(*, deprecated, renamed: "FastDatabaseValueCursor")
public typealias ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastDatabaseValueCursor<Value>
/// A cursor of optional database values extracted from a single column.
/// For example:
///
/// try dbQueue.read { db in
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, "SELECT email FROM player")
/// let emails: NullableColumnCursor<String> = try Optional<String>.fetchCursor(db, sql: "SELECT email FROM player")
/// while let email = emails.next() { // String?
/// print(email ?? "<NULL>")
/// }
/// }
public final class FastNullableDatabaseValueCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
private let statement: SelectStatement
private let sqliteStatement: SQLiteStatement
private let columnIndex: Int32
private var done = false
@usableFromInline let _statement: SelectStatement
@usableFromInline let _columnIndex: Int32
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline var _done = false
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
self.statement = statement
self.sqliteStatement = statement.sqliteStatement
_statement = statement
_sqliteStatement = statement.sqliteStatement
if let adapter = adapter {
// adapter may redefine the index of the leftmost column
self.columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
_columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
} else {
self.columnIndex = 0
_columnIndex = 0
}
statement.reset(withArguments: arguments)
_statement.reset(withArguments: arguments)
}
deinit {
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? statement.reset()
try? _statement.reset()
}
/// :nodoc:
@inlinable
public func next() throws -> Value?? {
if done {
if _done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
}
switch sqlite3_step(sqliteStatement) {
switch sqlite3_step(_sqliteStatement) {
case SQLITE_DONE:
done = true
_done = true
return nil
case SQLITE_ROW:
return Value.fastDecodeIfPresent(from: sqliteStatement, atUncheckedIndex: columnIndex)
return Value.fastDecodeIfPresent(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
case let code:
statement.database.selectStatementDidFail(statement)
throw DatabaseError(resultCode: code, message: statement.database.lastErrorMessage, sql: statement.sql, arguments: statement.arguments)
try _statement.didFail(withResultCode: code)
}
}
}
@available(*, deprecated, renamed: "FastNullableDatabaseValueCursor")
public typealias NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastNullableDatabaseValueCursor<Value>
/// Types that adopt both DatabaseValueConvertible and
/// StatementColumnConvertible can be efficiently initialized from
/// database values.
@@ -174,7 +170,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns a cursor over values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try String.fetchCursor(statement) // Cursor of String
/// while let name = try names.next() { // String
/// ...
@@ -197,7 +193,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try String.fetchAll(statement) // [String]
///
/// - parameters:
@@ -212,7 +208,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns a single value fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let name = try String.fetchOne(statement) // String?
///
/// - parameters:
@@ -234,7 +230,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns a cursor over values fetched from an SQL query.
///
/// let names = try String.fetchCursor(db, "SELECT name FROM ...") // Cursor of String
/// let names = try String.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String
/// while let name = try names.next() { // String
/// ...
/// }
@@ -247,42 +243,42 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String]
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns a single value fetched from an SQL query.
///
/// let name = try String.fetchOne(db, "SELECT name FROM ...") // String?
/// let name = try String.fetchOne(db, sql: "SELECT name FROM ...") // String?
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self? {
return try fetchOne(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -309,7 +305,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> FastDatabaseValueCursor<Self> {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
return try fetchCursor(statement, adapter: adapter)
}
@@ -324,7 +320,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An array of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Self] {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
return try fetchAll(statement, adapter: adapter)
}
@@ -339,7 +335,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> Self? {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: true)
return try fetchOne(statement, adapter: adapter)
}
}
@@ -350,7 +346,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// A cursor over fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let request: ... // Some FetchRequest that fetches String
/// let strings = try request.fetchCursor(db) // Cursor of String
/// while let string = try strings.next() { // String
/// ...
@@ -370,7 +366,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// An array of fetched values.
///
/// let request: ... // Some TypedRequest that fetches String
/// let request: ... // Some FetchRequest that fetches String
/// let strings = try request.fetchAll(db) // [String]
///
/// - parameter db: A database connection.
@@ -385,7 +381,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// The result is nil if the request returns no row, or if no value can be
/// extracted from the first row.
///
/// let request: ... // Some TypedRequest that fetches String
/// let request: ... // Some FetchRequest that fetches String
/// let string = try request.fetchOne(db) // String?
///
/// - parameter db: A database connection.
@@ -399,10 +395,10 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// Swift's Optional comes with built-in methods that allow to fetch cursors
/// and arrays of optional DatabaseValueConvertible:
///
/// try Optional<String>.fetchCursor(db, "SELECT name FROM ...", arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(db, "SELECT name FROM ...", arguments:...) // [String?]
/// try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?]
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
///
@@ -413,7 +409,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// Returns a cursor over optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
@@ -436,7 +432,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// Returns an array of optional values fetched from a prepared statement.
///
/// let statement = try db.makeSelectStatement("SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try Optional<String>.fetchAll(statement) // [String?]
///
/// - parameters:
@@ -456,7 +452,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// Returns a cursor over optional values fetched from an SQL query.
///
/// let names = try Optional<String>.fetchCursor(db, "SELECT name FROM ...") // Cursor of String?
/// let names = try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String?
/// while let name = try names.next() { // String?
/// ...
/// }
@@ -469,27 +465,27 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> {
return try fetchCursor(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> {
return try fetchCursor(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
/// Returns an array of optional values fetched from an SQL query.
///
/// let names = try String.fetchAll(db, "SELECT name FROM ...") // [String?]
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String?]
///
/// - parameters:
/// - db: A database connection.
/// - sql: An SQL query.
/// - parameter arguments: Optional statement arguments.
/// - arguments: Statement arguments.
/// - adapter: Optional RowAdapter
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest<Void>(sql, arguments: arguments, adapter: adapter))
public static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?] {
return try fetchAll(db, SQLRequest<Void>(sql: sql, arguments: arguments, adapter: adapter))
}
}
@@ -516,7 +512,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - returns: A cursor over fetched optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> FastNullableDatabaseValueCursor<Wrapped> {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
return try fetchCursor(statement, adapter: adapter)
}
@@ -531,7 +527,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - returns: An array of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Wrapped?] {
let (statement, adapter) = try request.prepare(db)
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
return try fetchAll(statement, adapter: adapter)
}
}
@@ -542,7 +538,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
/// A cursor over fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let request: ... // Some FetchRequest that fetches Optional<String>
/// let strings = try request.fetchCursor(db) // Cursor of String?
/// while let string = try strings.next() { // String?
/// ...
@@ -562,7 +558,7 @@ extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped:
/// An array of fetched optional values.
///
/// let request: ... // Some TypedRequest that fetches Optional<String>
/// let request: ... // Some FetchRequest that fetches Optional<String>
/// let strings = try request.fetchAll(db) // [String?]
///
/// - parameter db: A database connection.
+3
View File
@@ -1,12 +1,15 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// Data is convertible to and from DatabaseValue.
extension Data : DatabaseValueConvertible, StatementColumnConvertible {
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
@@ -1,6 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -26,14 +26,14 @@ extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.Refere
}
}
public extension DatabaseValueConvertible where Self: Decodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
extension DatabaseValueConvertible where Self: Decodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
// Preserve custom database decoding
return ReferenceType.fromDatabaseValue(databaseValue).flatMap { cast($0) }
}
}
public extension DatabaseValueConvertible where Self: Encodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
extension DatabaseValueConvertible where Self: Encodable & ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
// Preserve custom database encoding
return (self as! ReferenceType).databaseValue
+5 -1
View File
@@ -1,6 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -63,7 +65,8 @@ extension Date : DatabaseValueConvertible {
return nil
}
private init?(databaseDateComponents: DatabaseDateComponents) {
@usableFromInline
init?(databaseDateComponents: DatabaseDateComponents) {
guard databaseDateComponents.format.hasYMDComponents else {
// Refuse to turn hours without any date information into Date:
return nil
@@ -122,6 +125,7 @@ extension Date: StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER, SQLITE_FLOAT:
@@ -23,16 +23,20 @@ class SQLiteDateParser {
func components(cString: UnsafePointer<CChar>, length: Int) -> DatabaseDateComponents? {
assert(strlen(cString) == length)
// "HH:MM" is the shortest valid string
guard length >= 5 else { return nil }
if cString.advanced(by: 4).pointee == 45 /* '-' */ {
// "YYYY-..." -> datetime
if cString[4] == UInt8(ascii: "-") {
return datetimeComponents(cString: cString, length: length)
}
if cString.advanced(by: 2).pointee == 58 /* ':' */ {
// "HH-:..." -> time
if cString[2] == UInt8(ascii: ":") {
return timeComponents(cString: cString, length: length)
}
// Invalid
return nil
}
+19 -15
View File
@@ -1,6 +1,8 @@
import Foundation
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -19,19 +21,15 @@ extension NSUUID: DatabaseValueConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
switch dbValue.storage {
case .blob(let data) where data.count == 16:
// The code below works in debug configuration, but crashes in
// release configuration (Xcode 9.4.1)
// return data.withUnsafeBytes {
// self.init(uuidBytes: $0)
// }
// Workaround (involves a useless copy)
let buffer = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: 16)
_ = data.copyBytes(to: buffer)
let uuid = self.init(uuidBytes: UnsafePointer(buffer.baseAddress!))
buffer.deallocate()
return uuid
#if swift(>=5.0)
return data.withUnsafeBytes {
self.init(uuidBytes: $0.bindMemory(to: UInt8.self).baseAddress)
}
#else
return data.withUnsafeBytes {
self.init(uuidBytes: $0)
}
#endif
case .string(let string):
return self.init(uuidString: string)
default:
@@ -44,8 +42,7 @@ extension NSUUID: DatabaseValueConvertible {
/// UUID adopts DatabaseValueConvertible
extension UUID: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
var uuid_t = uuid
return withUnsafeBytes(of: &uuid_t) {
return withUnsafeBytes(of: uuid) {
Data(bytes: $0.baseAddress!, count: $0.count).databaseValue
}
}
@@ -53,9 +50,15 @@ extension UUID: DatabaseValueConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UUID? {
switch dbValue.storage {
case .blob(let data) where data.count == 16:
#if swift(>=5.0)
return data.withUnsafeBytes {
UUID(uuid: $0.bindMemory(to: uuid_t.self).first!)
}
#else
return data.withUnsafeBytes {
UUID(uuid: $0.pointee)
}
#endif
case .string(let string):
return UUID(uuidString: string)
default:
@@ -65,6 +68,7 @@ extension UUID: DatabaseValueConvertible {
}
extension UUID: StatementColumnConvertible {
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_TEXT:
@@ -178,13 +178,13 @@ private struct DatabaseValueDecoder: Decoder {
}
}
public extension DatabaseValueConvertible where Self: Decodable {
extension DatabaseValueConvertible where Self: Decodable {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
return try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
}
}
public extension DatabaseValueConvertible where Self: Decodable & RawRepresentable, Self.RawValue: DatabaseValueConvertible {
extension DatabaseValueConvertible where Self: Decodable & RawRepresentable, Self.RawValue: DatabaseValueConvertible {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
// Preserve custom database decoding
return RawValue.fromDatabaseValue(databaseValue).flatMap { self.init(rawValue: $0) }
@@ -89,7 +89,7 @@ private struct DatabaseValueEncoder : Encoder {
}
}
public extension DatabaseValueConvertible where Self: Encodable {
extension DatabaseValueConvertible where Self: Encodable {
public var databaseValue: DatabaseValue {
var dbValue: DatabaseValue! = nil
let encoder = DatabaseValueEncoder(encode: { dbValue = $0 })
@@ -98,7 +98,7 @@ public extension DatabaseValueConvertible where Self: Encodable {
}
}
public extension DatabaseValueConvertible where Self: Encodable & RawRepresentable, Self.RawValue: DatabaseValueConvertible {
extension DatabaseValueConvertible where Self: Encodable & RawRepresentable, Self.RawValue: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
// Preserve custom database encoding
return rawValue.databaseValue
@@ -1,5 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -14,6 +16,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
self = sqlite3_column_int64(sqliteStatement, index) != 0
}
@@ -100,6 +103,7 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = Int(exactly: int64) {
@@ -128,6 +132,7 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = Int8(exactly: int64) {
@@ -156,6 +161,7 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = Int16(exactly: int64) {
@@ -184,6 +190,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = Int32(exactly: int64) {
@@ -212,6 +219,7 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
self = sqlite3_column_int64(sqliteStatement, index)
}
@@ -244,6 +252,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt(exactly: int64) {
@@ -272,6 +281,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt8(exactly: int64) {
@@ -300,6 +310,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt16(exactly: int64) {
@@ -328,6 +339,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt32(exactly: int64) {
@@ -356,6 +368,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
if let v = UInt64(exactly: int64) {
@@ -384,6 +397,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
self = sqlite3_column_double(sqliteStatement, index)
}
@@ -414,6 +428,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
self = Float(sqlite3_column_double(sqliteStatement, index))
}
@@ -444,6 +459,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init(sqliteStatement: SQLiteStatement, index: Int32) {
self = String(cString: sqlite3_column_text(sqliteStatement, index)!)
}
@@ -543,7 +559,7 @@ extension DatabaseFunction {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedCapitalized)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
@available(OSX 10.11, watchOS 3.0, *)
public static let localizedCapitalize = DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
@@ -563,7 +579,7 @@ extension DatabaseFunction {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedLowercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
@available(OSX 10.11, watchOS 3.0, *)
public static let localizedLowercase = DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
@@ -583,7 +599,7 @@ extension DatabaseFunction {
/// let nameColumn = Column("name")
/// let request = Player.select(nameColumn.localizedUppercased)
/// let names = try String.fetchAll(dbQueue, request) // [String]
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
@available(OSX 10.11, watchOS 3.0, *)
public static let localizedUppercase = DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
guard let string = String.fromDatabaseValue(dbValues[0]) else {
return nil
@@ -616,11 +632,11 @@ extension DatabaseCollation {
/// You can use it when creating database tables:
///
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
/// dbQueue.execute(
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
/// dbQueue.execute(sql: """
/// CREATE TABLE players (
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let unicodeCompare = DatabaseCollation("swiftCompare") { (lhs, rhs) in
return (lhs < rhs) ? .orderedAscending : ((lhs == rhs) ? .orderedSame : .orderedDescending)
}
@@ -634,11 +650,11 @@ extension DatabaseCollation {
/// You can use it when creating database tables:
///
/// let collationName = DatabaseCollation.caseInsensitiveCompare.name
/// dbQueue.execute(
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
/// dbQueue.execute(sql: """
/// CREATE TABLE players (
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let caseInsensitiveCompare = DatabaseCollation("swiftCaseInsensitiveCompare") { (lhs, rhs) in
return lhs.caseInsensitiveCompare(rhs)
}
@@ -652,11 +668,11 @@ extension DatabaseCollation {
/// You can use it when creating database tables:
///
/// let collationName = DatabaseCollation.localizedCaseInsensitiveCompare.name
/// dbQueue.execute(
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
/// dbQueue.execute(sql: """
/// CREATE TABLE players (
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let localizedCaseInsensitiveCompare = DatabaseCollation("swiftLocalizedCaseInsensitiveCompare") { (lhs, rhs) in
return lhs.localizedCaseInsensitiveCompare(rhs)
}
@@ -670,11 +686,11 @@ extension DatabaseCollation {
/// You can use it when creating database tables:
///
/// let collationName = DatabaseCollation.localizedCompare.name
/// dbQueue.execute(
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
/// dbQueue.execute(sql: """
/// CREATE TABLE players (
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let localizedCompare = DatabaseCollation("swiftLocalizedCompare") { (lhs, rhs) in
return lhs.localizedCompare(rhs)
}
@@ -688,11 +704,11 @@ extension DatabaseCollation {
/// You can use it when creating database tables:
///
/// let collationName = DatabaseCollation.localizedStandardCompare.name
/// dbQueue.execute(
/// "CREATE TABLE players (" +
/// "name TEXT COLLATE \(collationName)" +
/// ")"
/// )
/// dbQueue.execute(sql: """
/// CREATE TABLE players (
/// name TEXT COLLATE \(collationName)
/// )
/// """)
public static let localizedStandardCompare = DatabaseCollation("swiftLocalizedStandardCompare") { (lhs, rhs) in
return lhs.localizedStandardCompare(rhs)
}
+11 -9
View File
@@ -1,5 +1,7 @@
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
@@ -95,11 +97,11 @@ extension Database {
/// let observer = MyObserver()
/// dbQueue.add(transactionObserver: observer)
/// dbQueue.inDatabase { db in
/// try db.execute("BEGIN TRANSACTION")
/// try db.execute(sql: "BEGIN TRANSACTION")
///
/// Then a statement is executed:
///
/// try db.execute("INSERT INTO document ...")
/// try db.execute(sql: "INSERT INTO document ...")
///
/// The observation process starts when the statement is *compiled*:
/// sqlite3_set_authorizer tells that the statement performs insertion into the
@@ -117,7 +119,7 @@ extension Database {
///
/// Now a savepoint is started:
///
/// try db.execute("SAVEPOINT foo")
/// try db.execute(sql: "SAVEPOINT foo")
///
/// Statement compilation has sqlite3_set_authorizer tell that this statement
/// begins a "foo" savepoint.
@@ -128,7 +130,7 @@ extension Database {
///
/// Then another statement is executed:
///
/// try db.execute("INSERT INTO document ...")
/// try db.execute(sql: "INSERT INTO document ...")
///
/// This time, when the statement is *executed* and SQLite tells that a row has
/// been inserted, the broker buffers the change event instead of immediately
@@ -138,7 +140,7 @@ extension Database {
///
/// The savepoint is released:
///
/// try db.execute("RELEASE SAVEPOINT foo")
/// try db.execute(sql: "RELEASE SAVEPOINT foo")
///
/// Statement compilation has sqlite3_set_authorizer tell that this statement
/// releases the "foo" savepoint.
@@ -149,7 +151,7 @@ extension Database {
///
/// Finally the transaction is committed:
///
/// try db.execute("COMMIT")
/// try db.execute(sql: "COMMIT")
///
/// During the statement *execution*, SQlite tells the broker that the
/// transaction is about to be committed through sqlite3_commit_hook. The broker
@@ -440,8 +442,8 @@ class DatabaseObservationBroker {
// SQLite, no transaction at all has started, and sqlite3_commit_hook
// was not triggered:
//
// try db.execute("BEGIN DEFERRED TRANSACTION")
// try db.execute("COMMIT") // <- no sqlite3_commit_hook callback invocation
// try db.execute(sql: "BEGIN DEFERRED TRANSACTION")
// try db.execute(sql: "COMMIT") // <- no sqlite3_commit_hook callback invocation
//
// Should we tell transaction observers of this transaction, or not?
// The code says that a transaction was open, but SQLite says the
@@ -517,7 +519,7 @@ class DatabaseObservationBroker {
//
// But we have to deal with a particular case:
//
// let journalMode = String.fetchOne(db, "PRAGMA journal_mode = wal")
// let journalMode = String.fetchOne(db, sql: "PRAGMA journal_mode = wal")
//
// It runs a SelectStatement, not an UpdateStatement. But this not why
// this case is particular. What is unexpected is that it triggers
+19
View File
@@ -5,6 +5,25 @@
/// t.column("content")
/// }
public struct FTS3 : VirtualTableModule {
/// Options for Latin script characters. Matches the raw "remove_diacritics"
/// tokenizer argument.
///
/// See https://www.sqlite.org/fts3.html
public enum Diacritics {
/// Do not remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=0" tokenizer argument.
case keep
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=1" tokenizer argument.
case removeLegacy
#if GRDBCUSTOMSQLITE
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=2" tokenizer argument,
/// available from SQLite 3.27.0
case remove
#endif
}
/// Creates a FTS3 module suitable for the Database
/// `create(virtualTable:using:)` method.
///
+5 -5
View File
@@ -19,8 +19,8 @@ public struct FTS3Pattern {
// that pattern.
do {
try DatabaseQueue().inDatabase { db in
try db.execute("CREATE VIRTUAL TABLE documents USING fts3()")
try db.execute("SELECT * FROM documents WHERE content MATCH ?", arguments: [rawPattern])
try db.execute(sql: "CREATE VIRTUAL TABLE documents USING fts3()")
try db.execute(sql: "SELECT * FROM documents WHERE content MATCH ?", arguments: [rawPattern])
}
} catch let error as DatabaseError {
// Remove private SQL & arguments from the thrown error
@@ -78,7 +78,7 @@ public struct FTS3Pattern {
/// FTS3Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(iOS 8.2, OSX 10.10, *)
@available(OSX 10.10, *)
public init?(matchingAnyTokenIn string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
@@ -92,7 +92,7 @@ public struct FTS3Pattern {
/// FTS3Pattern(matchingAllTokensIn: "foo bar") // foo bar
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(iOS 8.2, OSX 10.10, *)
@available(OSX 10.10, *)
public init?(matchingAllTokensIn string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
@@ -106,7 +106,7 @@ public struct FTS3Pattern {
/// FTS3Pattern(matchingPhrase: "foo bar") // "foo bar"
///
/// - parameter string: The string to turn into an FTS3 pattern
@available(iOS 8.2, OSX 10.10, *)
@available(OSX 10.10, *)
public init?(matchingPhrase string: String) {
let tokens = FTS3TokenizerDescriptor.simple.tokenize(string)
guard !tokens.isEmpty else { return nil }
+21 -14
View File
@@ -40,16 +40,16 @@ public struct FTS3TokenizerDescriptor {
/// }
///
/// - parameters:
/// - removeDiacritics: If true (the default), then SQLite will strip
/// diacritics from latin characters.
/// - diacritics: By default SQLite will strip diacritics from
/// latin characters.
/// - separators: Unless empty (the default), SQLite will consider these
/// characters as token separators.
/// - tokenCharacters: Unless empty (the default), SQLite will consider
/// these characters as token characters.
///
/// See https://www.sqlite.org/fts3.html#tokenizer
public static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
return _unicode61(removeDiacritics: removeDiacritics, separators: separators, tokenCharacters: tokenCharacters)
public static func unicode61(diacritics: FTS3.Diacritics = .removeLegacy, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters)
}
#else
/// The "unicode61" tokenizer.
@@ -59,26 +59,33 @@ public struct FTS3TokenizerDescriptor {
/// }
///
/// - parameters:
/// - removeDiacritics: If true (the default), then SQLite will strip
/// diacritics from latin characters.
/// - diacritics: By default SQLite will strip diacritics from
/// latin characters.
/// - separators: Unless empty (the default), SQLite will consider these
/// characters as token separators.
/// - tokenCharacters: Unless empty (the default), SQLite will consider
/// these characters as token characters.
///
/// See https://www.sqlite.org/fts3.html#tokenizer
@available(iOS 8.2, OSX 10.10, *)
public static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
@available(OSX 10.10, *)
public static func unicode61(diacritics: FTS3.Diacritics = .removeLegacy, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
// query_only pragma was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
return _unicode61(removeDiacritics: removeDiacritics, separators: separators, tokenCharacters: tokenCharacters)
return _unicode61(diacritics: diacritics, separators: separators, tokenCharacters: tokenCharacters)
}
#endif
private static func _unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
private static func _unicode61(diacritics: FTS3.Diacritics, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor {
var arguments: [String] = []
if !removeDiacritics {
switch diacritics {
case .removeLegacy:
break
case .keep:
arguments.append("remove_diacritics=0")
#if GRDBCUSTOMSQLITE
case .remove:
arguments.append("remove_diacritics=2")
#endif
}
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
@@ -96,7 +103,7 @@ public struct FTS3TokenizerDescriptor {
return _tokenize(string)
}
#else
@available(iOS 8.2, OSX 10.10, *)
@available(OSX 10.10, *)
func tokenize(_ string: String) -> [String] {
return _tokenize(string)
}
@@ -116,8 +123,8 @@ public struct FTS3TokenizerDescriptor {
}
let tokenizerSQL = tokenizerChunks.joined(separator: ", ")
// Assume fts3tokenize virtual table in an in-memory database always succeeds
try! db.execute("CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))")
return try! String.fetchAll(db, "SELECT token FROM tokens WHERE input = ? ORDER BY position", arguments: [string])
try! db.execute(sql: "CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))")
return try! String.fetchAll(db, sql: "SELECT token FROM tokens WHERE input = ? ORDER BY position", arguments: [string])
}
}
}
+4 -4
View File
@@ -110,7 +110,7 @@ public struct FTS4 : VirtualTableModule {
let oldRowID = "old.\(rowIDColumn.quotedDatabaseIdentifier)"
try db.execute("""
try db.execute(sql: """
CREATE TRIGGER \("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
END;
@@ -127,7 +127,7 @@ public struct FTS4 : VirtualTableModule {
// https://www.sqlite.org/fts3.html#*fts4rebuidcmd
try db.execute("INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')")
try db.execute(sql: "INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')")
}
}
}
@@ -288,7 +288,7 @@ public final class FTS4ColumnDefinition {
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
///
/// - returns: Self so that you can further refine the column definition.
@available(iOS 8.2, OSX 10.10, *)
@available(OSX 10.10, *)
@discardableResult
public func notIndexed() -> Self {
// notindexed FTS4 option was added in SQLite 3.8.0 http://www.sqlite.org/changes.html#version_3_8_0
@@ -318,7 +318,7 @@ public final class FTS4ColumnDefinition {
extension Database {
/// Deletes the synchronization triggers for a synchronized FTS4 table
public func dropFTS4SynchronizationTriggers(forTable tableName: String) throws {
try execute("""
try execute(sql: """
DROP TRIGGER IF EXISTS \("__\(tableName)_bu".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_bd".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier);
+368 -358
View File
@@ -1,5 +1,42 @@
#if SQLITE_ENABLE_FTS5
/// FTS5 lets you define "fts5" virtual tables.
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// FTS5 lets you define "fts5" virtual tables.
///
/// // CREATE VIRTUAL TABLE document USING fts5(content)
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content")
/// }
///
/// See https://www.sqlite.org/fts5.html
public struct FTS5 : VirtualTableModule {
/// Options for Latin script characters. Matches the raw "remove_diacritics"
/// tokenizer argument.
///
/// See https://www.sqlite.org/fts5.html
public enum Diacritics {
/// Do not remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=0" tokenizer argument.
case keep
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=1" tokenizer argument.
case removeLegacy
#if GRDBCUSTOMSQLITE
/// Remove diacritics from Latin script characters. This
/// option matches the raw "remove_diacritics=2" tokenizer argument,
/// available from SQLite 3.27.0
case remove
#endif
}
/// Creates a FTS5 module suitable for the Database
/// `create(virtualTable:using:)` method.
///
/// // CREATE VIRTUAL TABLE document USING fts5(content)
/// try db.create(virtualTable: "document", using: FTS5()) { t in
@@ -7,391 +44,364 @@
/// }
///
/// See https://www.sqlite.org/fts5.html
public struct FTS5 : VirtualTableModule {
public init() {
}
// MARK: - VirtualTableModule Adoption
/// The virtual table module name
public let moduleName = "fts5"
/// Don't use this method.
public func makeTableDefinition() -> FTS5TableDefinition {
return FTS5TableDefinition()
}
/// Don't use this method.
public func moduleArguments(for definition: FTS5TableDefinition, in db: Database) throws -> [String] {
var arguments: [String] = []
/// Creates a FTS5 module suitable for the Database
/// `create(virtualTable:using:)` method.
///
/// // CREATE VIRTUAL TABLE document USING fts5(content)
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content")
/// }
///
/// See https://www.sqlite.org/fts5.html
public init() {
if definition.columns.isEmpty {
// Programmer error
fatalError("FTS5 virtual table requires at least one column.")
}
// MARK: - VirtualTableModule Adoption
/// The virtual table module name
public let moduleName = "fts5"
/// Don't use this method.
public func makeTableDefinition() -> FTS5TableDefinition {
return FTS5TableDefinition()
}
/// Don't use this method.
public func moduleArguments(for definition: FTS5TableDefinition, in db: Database) throws -> [String] {
var arguments: [String] = []
if definition.columns.isEmpty {
// Programmer error
fatalError("FTS5 virtual table requires at least one column.")
}
for column in definition.columns {
if column.isIndexed {
arguments.append("\(column.name)")
} else {
arguments.append("\(column.name) UNINDEXED")
}
}
if let tokenizer = definition.tokenizer {
arguments.append("tokenize=\(tokenizer.components.joined(separator: " ").sqlExpression.sql)")
}
switch definition.contentMode {
case .raw(let content, let contentRowID):
if let content = content {
arguments.append("content=\(content.sqlExpression.sql)")
}
if let contentRowID = contentRowID {
arguments.append("content_rowid=\(contentRowID.sqlExpression.sql)")
}
case .synchronized(let contentTable):
arguments.append("content=\(contentTable.sqlExpression.sql)")
if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn {
arguments.append("content_rowid=\(rowIDColumn.sqlExpression.sql)")
}
}
if let prefixes = definition.prefixes {
arguments.append("prefix=\(prefixes.sorted().map { "\($0)" }.joined(separator: " ").sqlExpression.sql)")
}
if let columnSize = definition.columnSize {
arguments.append("columnSize=\(columnSize)")
}
if let detail = definition.detail {
arguments.append("detail=\(detail)")
}
return arguments
}
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws {
switch definition.contentMode {
case .raw:
break
case .synchronized(let contentTable):
// https://sqlite.org/fts5.html#external_content_tables
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
let indexedColumns = definition.columns.map { $0.name }
let ftsColumns = (["rowid"] + indexedColumns)
.map { $0.quotedDatabaseIdentifier }
.joined(separator: ", ")
let newContentColumns = ([rowIDColumn] + indexedColumns)
.map { "new.\($0.quotedDatabaseIdentifier)" }
.joined(separator: ", ")
let oldContentColumns = ([rowIDColumn] + indexedColumns)
.map { "old.\($0.quotedDatabaseIdentifier)" }
.joined(separator: ", ")
try db.execute("""
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
END;
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
""")
// https://sqlite.org/fts5.html#the_rebuild_command
try db.execute("INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')")
for column in definition.columns {
if column.isIndexed {
arguments.append("\(column.name)")
} else {
arguments.append("\(column.name) UNINDEXED")
}
}
static func api(_ db: Database) -> UnsafePointer<fts5_api> {
// Access to FTS5 is one of the rare SQLite api which was broken in
// SQLite 3.20.0+, for security reasons:
//
// Starting SQLite 3.20.0+, we need to use the new sqlite3_bind_pointer api.
// The previous way to access FTS5 does not work any longer.
//
// So let's see which SQLite version we are linked against:
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// GRDB is linked against SQLCipher or a custom SQLite build: SQLite 3.20.0 or more.
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
#else
// GRDB is linked against the system SQLite.
//
// Do we use SQLite 3.19.3 (iOS 11.4), or SQLite 3.24.0 (iOS 12.0)?
// We need to check for available(iOS 12.0, OSX 10.14, watchOS 5.0, *).
//
// This test requires the Swift 4.2 compiler.
//
// It does not need the Swift 4.2 language, though: the Swift 4.2
// compiler running in Swift 4.0 compatibility mode is OK.
//
// On top of that, we want to preserve compatibility with Xcode 9.3+.
//
// So let's check exactly which compiler version we are using.
//
// Fortunately, this horribly complex check has been solved
// by @hartbit: see https://forums.swift.org/t/compiler-version-directive/11952
// and https://github.com/hartbit/swift-evolution/blob/compiler-directive/proposals/XXXX-compiler-version-directive.md
#if swift(>=4.1.50) || (swift(>=3.4) && !swift(>=4.0))
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
// SQLite 3.24.0 or more
// setup: Xcode 10.0, SWIFT_VERSION = 4.0, iOS 12
// setup: Xcode 10.0, SWIFT_VERSION = 4.2, iOS 12
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
} else {
// SQLite 3.19.3 or less
// setup: Xcode 10.0, SWIFT_VERSION = 4.0, iOS 11
// setup: Xcode 10.0, SWIFT_VERSION = 4.2, iOS 11
return api_v1(db)
}
#else
// SQLite 3.19.3 or less
// setup: Xcode 9.4.1, iOS 11
return api_v1(db)
#endif
#endif
if let tokenizer = definition.tokenizer {
arguments.append("tokenize=\(tokenizer.components.joined(separator: " ").sqlExpression.quotedSQL())")
}
private static func api_v1(_ db: Database) -> UnsafePointer<fts5_api> {
guard let data = try! Data.fetchOne(db, "SELECT fts5()") else {
fatalError("FTS5 is not available")
switch definition.contentMode {
case .raw(let content, let contentRowID):
if let content = content {
arguments.append("content=\(content.sqlExpression.quotedSQL())")
}
if let contentRowID = contentRowID {
arguments.append("content_rowid=\(contentRowID.sqlExpression.quotedSQL())")
}
case .synchronized(let contentTable):
arguments.append("content=\(contentTable.sqlExpression.quotedSQL())")
if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn {
arguments.append("content_rowid=\(rowIDColumn.sqlExpression.quotedSQL())")
}
return data.withUnsafeBytes { $0.pointee }
}
// Technique given by Jordan Rose:
// https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4
private static func api_v2(
_ db: Database,
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, Int32, UInt32, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> Int32,
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32)
-> UnsafePointer<fts5_api>
{
let sqliteConnection = db.sqliteConnection
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
let type: StaticString = "fts5_api_ptr"
if let prefixes = definition.prefixes {
arguments.append("prefix=\(prefixes.sorted().map { "\($0)" }.joined(separator: " ").sqlExpression.quotedSQL())")
}
if let columnSize = definition.columnSize {
arguments.append("columnSize=\(columnSize)")
}
if let detail = definition.detail {
arguments.append("detail=\(detail)")
}
return arguments
}
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws {
switch definition.contentMode {
case .raw:
break
case .synchronized(let contentTable):
// https://sqlite.org/fts5.html#external_content_tables
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
guard code == SQLITE_OK else {
fatalError("FTS5 is not available")
}
defer { sqlite3_finalize(statement) }
type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
}
sqlite3_step(statement)
guard let result = api else {
fatalError("FTS5 is not available")
}
return result
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
let indexedColumns = definition.columns.map { $0.name }
let ftsColumns = (["rowid"] + indexedColumns)
.map { $0.quotedDatabaseIdentifier }
.joined(separator: ", ")
let newContentColumns = ([rowIDColumn] + indexedColumns)
.map { "new.\($0.quotedDatabaseIdentifier)" }
.joined(separator: ", ")
let oldContentColumns = ([rowIDColumn] + indexedColumns)
.map { "old.\($0.quotedDatabaseIdentifier)" }
.joined(separator: ", ")
try db.execute(sql: """
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
END;
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
""")
// https://sqlite.org/fts5.html#the_rebuild_command
try db.execute(sql: "INSERT INTO \(ftsTable)(\(ftsTable)) VALUES('rebuild')")
}
}
/// The FTS5TableDefinition class lets you define columns of a FTS5 virtual table.
static func api(_ db: Database) -> UnsafePointer<fts5_api> {
// Access to FTS5 is one of the rare SQLite api which was broken in
// SQLite 3.20.0+, for security reasons:
//
// Starting SQLite 3.20.0+, we need to use the new sqlite3_bind_pointer api.
// The previous way to access FTS5 does not work any longer.
//
// So let's see which SQLite version we are linked against:
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// GRDB is linked against SQLCipher or a custom SQLite build: SQLite 3.20.0 or more.
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
#else
// GRDB is linked against the system SQLite.
//
// Do we use SQLite 3.19.3 (iOS 11.4), or SQLite 3.24.0 (iOS 12.0)?
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
// SQLite 3.24.0 or more
return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer)
} else {
// SQLite 3.19.3 or less
return api_v1(db)
}
#endif
}
private static func api_v1(_ db: Database) -> UnsafePointer<fts5_api> {
guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else {
fatalError("FTS5 is not available")
}
#if swift(>=5.0)
return data.withUnsafeBytes {
$0.bindMemory(to: UnsafePointer<fts5_api>.self).first!
}
#else
return data.withUnsafeBytes {
$0.pointee
}
#endif
}
// Technique given by Jordan Rose:
// https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4
private static func api_v2(
_ db: Database,
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, Int32, UInt32, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> Int32,
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32)
-> UnsafePointer<fts5_api>
{
let sqliteConnection = db.sqliteConnection
var statement: SQLiteStatement? = nil
var api: UnsafePointer<fts5_api>? = nil
let type: StaticString = "fts5_api_ptr"
let code = sqlite3_prepare_v3(db.sqliteConnection, "SELECT fts5(?)", -1, 0, &statement, nil)
guard code == SQLITE_OK else {
fatalError("FTS5 is not available")
}
defer { sqlite3_finalize(statement) }
type.utf8Start.withMemoryRebound(to: Int8.self, capacity: type.utf8CodeUnitCount) { typePointer in
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
}
sqlite3_step(statement)
guard let result = api else {
fatalError("FTS5 is not available")
}
return result
}
}
/// The FTS5TableDefinition class lets you define columns of a FTS5 virtual table.
///
/// You don't create instances of this class. Instead, you use the Database
/// `create(virtualTable:using:)` method:
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
/// t.column("content")
/// }
///
/// See https://www.sqlite.org/fts5.html
public final class FTS5TableDefinition {
enum ContentMode {
case raw(content: String?, contentRowID: String?)
case synchronized(contentTable: String)
}
fileprivate var columns: [FTS5ColumnDefinition] = []
fileprivate var contentMode: ContentMode = .raw(content: nil, contentRowID: nil)
/// The virtual table tokenizer
///
/// You don't create instances of this class. Instead, you use the Database
/// `create(virtualTable:using:)` method:
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.tokenizer = .porter()
/// }
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
/// See https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization
public var tokenizer: FTS5TokenizerDescriptor?
/// The FTS5 `content` option
///
/// When you want the full-text table to be synchronized with the
/// content of an external table, prefer the `synchronize(withTable:)`
/// method.
///
/// Setting this property invalidates any synchronization previously
/// established with the `synchronize(withTable:)` method.
///
/// See https://www.sqlite.org/fts5.html#external_content_and_contentless_tables
public var content: String? {
get {
switch contentMode {
case .raw(let content, _):
return content
case .synchronized(let contentTable):
return contentTable
}
}
set {
switch contentMode {
case .raw(_, let contentRowID):
contentMode = .raw(content: newValue, contentRowID: contentRowID)
case .synchronized:
contentMode = .raw(content: newValue, contentRowID: nil)
}
}
}
/// The FTS5 `content_rowid` option
///
/// When you want the full-text table to be synchronized with the
/// content of an external table, prefer the `synchronize(withTable:)`
/// method.
///
/// Setting this property invalidates any synchronization previously
/// established with the `synchronize(withTable:)` method.
///
/// See https://sqlite.org/fts5.html#external_content_tables
public var contentRowID: String? {
get {
switch contentMode {
case .raw(_, let contentRowID):
return contentRowID
case .synchronized:
return nil
}
}
set {
switch contentMode {
case .raw(let content, _):
contentMode = .raw(content: content, contentRowID: newValue)
case .synchronized:
contentMode = .raw(content: nil, contentRowID: newValue)
}
}
}
/// Support for the FTS5 `prefix` option
///
/// See https://www.sqlite.org/fts5.html#prefix_indexes
public var prefixes: Set<Int>?
/// Support for the FTS5 `columnsize` option
///
/// https://www.sqlite.org/fts5.html#the_columnsize_option
public var columnSize: Int?
/// Support for the FTS5 `detail` option
///
/// https://www.sqlite.org/fts5.html#the_detail_option
public var detail: String?
/// Appends a table column.
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content")
/// }
///
/// See https://www.sqlite.org/fts5.html
public final class FTS5TableDefinition {
enum ContentMode {
case raw(content: String?, contentRowID: String?)
case synchronized(contentTable: String)
}
fileprivate var columns: [FTS5ColumnDefinition] = []
fileprivate var contentMode: ContentMode = .raw(content: nil, contentRowID: nil)
/// The virtual table tokenizer
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.tokenizer = .porter()
/// }
///
/// See https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization
public var tokenizer: FTS5TokenizerDescriptor?
/// The FTS5 `content` option
///
/// When you want the full-text table to be synchronized with the
/// content of an external table, prefer the `synchronize(withTable:)`
/// method.
///
/// Setting this property invalidates any synchronization previously
/// established with the `synchronize(withTable:)` method.
///
/// See https://www.sqlite.org/fts5.html#external_content_and_contentless_tables
public var content: String? {
get {
switch contentMode {
case .raw(let content, _):
return content
case .synchronized(let contentTable):
return contentTable
}
}
set {
switch contentMode {
case .raw(_, let contentRowID):
contentMode = .raw(content: newValue, contentRowID: contentRowID)
case .synchronized:
contentMode = .raw(content: newValue, contentRowID: nil)
}
}
}
/// The FTS5 `content_rowid` option
///
/// When you want the full-text table to be synchronized with the
/// content of an external table, prefer the `synchronize(withTable:)`
/// method.
///
/// Setting this property invalidates any synchronization previously
/// established with the `synchronize(withTable:)` method.
///
/// See https://sqlite.org/fts5.html#external_content_tables
public var contentRowID: String? {
get {
switch contentMode {
case .raw(_, let contentRowID):
return contentRowID
case .synchronized:
return nil
}
}
set {
switch contentMode {
case .raw(let content, _):
contentMode = .raw(content: content, contentRowID: newValue)
case .synchronized:
contentMode = .raw(content: nil, contentRowID: newValue)
}
}
}
/// Support for the FTS5 `prefix` option
///
/// See https://www.sqlite.org/fts5.html#prefix_indexes
public var prefixes: Set<Int>?
/// Support for the FTS5 `columnsize` option
///
/// https://www.sqlite.org/fts5.html#the_columnsize_option
public var columnSize: Int?
/// Support for the FTS5 `detail` option
///
/// https://www.sqlite.org/fts5.html#the_detail_option
public var detail: String?
/// Appends a table column.
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content")
/// }
///
/// - parameter name: the column name.
@discardableResult
public func column(_ name: String) -> FTS5ColumnDefinition {
let column = FTS5ColumnDefinition(name: name)
columns.append(column)
return column
}
/// Synchronizes the full-text table with the content of an external
/// table.
///
/// The full-text table is initially populated with the existing
/// content in the external table. SQL triggers make sure that the
/// full-text table is kept up to date with the external table.
///
/// See https://sqlite.org/fts5.html#external_content_tables
public func synchronize(withTable tableName: String) {
contentMode = .synchronized(contentTable: tableName)
}
/// - parameter name: the column name.
@discardableResult
public func column(_ name: String) -> FTS5ColumnDefinition {
let column = FTS5ColumnDefinition(name: name)
columns.append(column)
return column
}
/// The FTS5ColumnDefinition class lets you refine a column of an FTS5
/// virtual table.
/// Synchronizes the full-text table with the content of an external
/// table.
///
/// You get instances of this class when you create an FTS5 table:
/// The full-text table is initially populated with the existing
/// content in the external table. SQL triggers make sure that the
/// full-text table is kept up to date with the external table.
///
/// See https://sqlite.org/fts5.html#external_content_tables
public func synchronize(withTable tableName: String) {
contentMode = .synchronized(contentTable: tableName)
}
}
/// The FTS5ColumnDefinition class lets you refine a column of an FTS5
/// virtual table.
///
/// You get instances of this class when you create an FTS5 table:
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content") // FTS5ColumnDefinition
/// }
///
/// See https://www.sqlite.org/fts5.html
public final class FTS5ColumnDefinition {
fileprivate let name: String
fileprivate var isIndexed: Bool
init(name: String) {
self.name = name
self.isIndexed = true
}
/// Excludes the column from the full-text index.
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("content") // FTS5ColumnDefinition
/// t.column("a")
/// t.column("b").notIndexed()
/// }
///
/// See https://www.sqlite.org/fts5.html
public final class FTS5ColumnDefinition {
fileprivate let name: String
fileprivate var isIndexed: Bool
init(name: String) {
self.name = name
self.isIndexed = true
}
/// Excludes the column from the full-text index.
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in
/// t.column("a")
/// t.column("b").notIndexed()
/// }
///
/// See https://www.sqlite.org/fts5.html#the_unindexed_column_option
///
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func notIndexed() -> Self {
self.isIndexed = false
return self
}
}
extension Column {
/// The FTS5 rank column
public static let rank = Column("rank")
/// See https://www.sqlite.org/fts5.html#the_unindexed_column_option
///
/// - returns: Self so that you can further refine the column definition.
@discardableResult
public func notIndexed() -> Self {
self.isIndexed = false
return self
}
}
extension Database {
/// Deletes the synchronization triggers for a synchronized FTS5 table
public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws {
try execute("""
DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_ad".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier);
""")
}
extension Column {
/// The FTS5 rank column
public static let rank = Column("rank")
}
extension Database {
/// Deletes the synchronization triggers for a synchronized FTS5 table
public func dropFTS5SynchronizationTriggers(forTable tableName: String) throws {
try execute(sql: """
DROP TRIGGER IF EXISTS \("__\(tableName)_ai".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_ad".quotedDatabaseIdentifier);
DROP TRIGGER IF EXISTS \("__\(tableName)_au".quotedDatabaseIdentifier);
""")
}
}
#endif
+159 -151
View File
@@ -1,153 +1,161 @@
#if SQLITE_ENABLE_FTS5
/// The protocol for custom FTS5 tokenizers.
public protocol FTS5CustomTokenizer : FTS5Tokenizer {
/// The name of the tokenizer; should uniquely identify your custom
/// tokenizer.
static var name: String { get }
/// Creates a custom tokenizer.
///
/// The arguments parameter is an array of String built from the CREATE
/// VIRTUAL TABLE statement. In the example below, the arguments will
/// be `["arg1", "arg2"]`.
///
/// CREATE VIRTUAL TABLE document USING fts5(
/// tokenize='custom arg1 arg2'
/// )
///
/// - parameter db: A Database connection
/// - parameter arguments: An array of string arguments
init(db: Database, arguments: [String]) throws
}
extension FTS5CustomTokenizer {
/// Creates an FTS5 tokenizer descriptor.
///
/// class MyTokenizer : FTS5CustomTokenizer { ... }
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// let tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["unicode61", "remove_diacritics", "0"])
/// t.tokenizer = tokenizer
/// }
public static func tokenizerDescriptor(arguments: [String] = []) -> FTS5TokenizerDescriptor {
return FTS5TokenizerDescriptor(components: [name] + arguments)
}
}
extension Database {
// MARK: - FTS5
private class FTS5TokenizerConstructor {
let db: Database
let constructor: (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> Int32
init(db: Database, constructor: @escaping (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> Int32) {
self.db = db
self.constructor = constructor
}
}
/// Add a custom FTS5 tokenizer.
///
/// class MyTokenizer : FTS5CustomTokenizer { ... }
/// db.add(tokenizer: MyTokenizer.self)
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
let api = FTS5.api(self)
// Swift won't let the @convention(c) xCreate() function below create
// an instance of the generic Tokenizer type.
//
// We thus hide the generic Tokenizer type inside a neutral type:
// FTS5TokenizerConstructor
let constructor = FTS5TokenizerConstructor(
db: self,
constructor: { (db, arguments, tokenizerHandle) in
guard let tokenizerHandle = tokenizerHandle else {
return SQLITE_ERROR
}
do {
let tokenizer = try Tokenizer(db: db, arguments: arguments)
// Tokenizer must remain alive until xDeleteTokenizer()
// is called, as the xDelete member of xTokenizer
let tokenizerPointer = OpaquePointer(Unmanaged.passRetained(tokenizer).toOpaque())
tokenizerHandle.pointee = tokenizerPointer
return SQLITE_OK
} catch let error as DatabaseError {
return error.extendedResultCode.rawValue
} catch {
return SQLITE_ERROR
}
})
// Constructor must remain alive until deleteConstructor() is
// called, as the last argument of the xCreateTokenizer() function.
let constructorPointer = Unmanaged.passRetained(constructor).toOpaque()
func deleteConstructor(constructorPointer: UnsafeMutableRawPointer?) {
guard let constructorPointer = constructorPointer else { return }
Unmanaged<AnyObject>.fromOpaque(constructorPointer).release()
}
func xCreateTokenizer(constructorPointer: UnsafeMutableRawPointer?, azArg: UnsafeMutablePointer<UnsafePointer<Int8>?>?, nArg: Int32, tokenizerHandle: UnsafeMutablePointer<OpaquePointer?>?) -> Int32 {
guard let constructorPointer = constructorPointer else {
return SQLITE_ERROR
}
let constructor = Unmanaged<FTS5TokenizerConstructor>.fromOpaque(constructorPointer).takeUnretainedValue()
var arguments: [String] = []
if let azArg = azArg {
for i in 0..<Int(nArg) {
if let cstr = azArg[i] {
arguments.append(String(cString: cstr))
}
}
}
return constructor.constructor(constructor.db, arguments, tokenizerHandle)
}
func xDeleteTokenizer(tokenizerPointer: OpaquePointer?) {
guard let tokenizerPointer = tokenizerPointer else { return }
Unmanaged<AnyObject>.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).release()
}
func xTokenize(tokenizerPointer: OpaquePointer?, context: UnsafeMutableRawPointer?, flags: Int32, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer<Int8>?, Int32, Int32, Int32) -> Int32)?) -> Int32 {
guard let tokenizerPointer = tokenizerPointer else {
return SQLITE_ERROR
}
let object = Unmanaged<AnyObject>.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).takeUnretainedValue()
guard let tokenizer = object as? FTS5Tokenizer else {
return SQLITE_ERROR
}
return tokenizer.tokenize(context: context, tokenization: FTS5Tokenization(rawValue: flags), pText: pText, nText: nText, tokenCallback: tokenCallback!)
}
var xTokenizer = fts5_tokenizer(xCreate: xCreateTokenizer, xDelete: xDeleteTokenizer, xTokenize: xTokenize)
let code = withUnsafeMutablePointer(to: &xTokenizer) { xTokenizerPointer in
api.pointee.xCreateTokenizer(UnsafeMutablePointer(mutating: api), Tokenizer.name, constructorPointer, xTokenizerPointer, deleteConstructor)
}
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
}
}
}
extension DatabaseQueue {
// MARK: - Custom FTS5 Tokenizers
/// Add a custom FTS5 tokenizer.
///
/// class MyTokenizer : FTS5CustomTokenizer { ... }
/// dbQueue.add(tokenizer: MyTokenizer.self)
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
inDatabase { db in
db.add(tokenizer: Tokenizer.self)
}
}
}
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// The protocol for custom FTS5 tokenizers.
public protocol FTS5CustomTokenizer : FTS5Tokenizer {
/// The name of the tokenizer; should uniquely identify your custom
/// tokenizer.
static var name: String { get }
/// Creates a custom tokenizer.
///
/// The arguments parameter is an array of String built from the CREATE
/// VIRTUAL TABLE statement. In the example below, the arguments will
/// be `["arg1", "arg2"]`.
///
/// CREATE VIRTUAL TABLE document USING fts5(
/// tokenize='custom arg1 arg2'
/// )
///
/// - parameter db: A Database connection
/// - parameter arguments: An array of string arguments
init(db: Database, arguments: [String]) throws
}
extension FTS5CustomTokenizer {
/// Creates an FTS5 tokenizer descriptor.
///
/// class MyTokenizer : FTS5CustomTokenizer { ... }
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// let tokenizer = MyTokenizer.tokenizerDescriptor(arguments: ["unicode61", "remove_diacritics", "0"])
/// t.tokenizer = tokenizer
/// }
public static func tokenizerDescriptor(arguments: [String] = []) -> FTS5TokenizerDescriptor {
return FTS5TokenizerDescriptor(components: [name] + arguments)
}
}
extension Database {
// MARK: - FTS5
private class FTS5TokenizerConstructor {
let db: Database
let constructor: (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> Int32
init(db: Database, constructor: @escaping (Database, [String], UnsafeMutablePointer<OpaquePointer?>?) -> Int32) {
self.db = db
self.constructor = constructor
}
}
/// Add a custom FTS5 tokenizer.
///
/// class MyTokenizer : FTS5CustomTokenizer { ... }
/// db.add(tokenizer: MyTokenizer.self)
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
let api = FTS5.api(self)
// Swift won't let the @convention(c) xCreate() function below create
// an instance of the generic Tokenizer type.
//
// We thus hide the generic Tokenizer type inside a neutral type:
// FTS5TokenizerConstructor
let constructor = FTS5TokenizerConstructor(
db: self,
constructor: { (db, arguments, tokenizerHandle) in
guard let tokenizerHandle = tokenizerHandle else {
return SQLITE_ERROR
}
do {
let tokenizer = try Tokenizer(db: db, arguments: arguments)
// Tokenizer must remain alive until xDeleteTokenizer()
// is called, as the xDelete member of xTokenizer
let tokenizerPointer = OpaquePointer(Unmanaged.passRetained(tokenizer).toOpaque())
tokenizerHandle.pointee = tokenizerPointer
return SQLITE_OK
} catch let error as DatabaseError {
return error.extendedResultCode.rawValue
} catch {
return SQLITE_ERROR
}
})
// Constructor must remain alive until deleteConstructor() is
// called, as the last argument of the xCreateTokenizer() function.
let constructorPointer = Unmanaged.passRetained(constructor).toOpaque()
func deleteConstructor(constructorPointer: UnsafeMutableRawPointer?) {
guard let constructorPointer = constructorPointer else { return }
Unmanaged<AnyObject>.fromOpaque(constructorPointer).release()
}
func xCreateTokenizer(constructorPointer: UnsafeMutableRawPointer?, azArg: UnsafeMutablePointer<UnsafePointer<Int8>?>?, nArg: Int32, tokenizerHandle: UnsafeMutablePointer<OpaquePointer?>?) -> Int32 {
guard let constructorPointer = constructorPointer else {
return SQLITE_ERROR
}
let constructor = Unmanaged<FTS5TokenizerConstructor>.fromOpaque(constructorPointer).takeUnretainedValue()
var arguments: [String] = []
if let azArg = azArg {
for i in 0..<Int(nArg) {
if let cstr = azArg[i] {
arguments.append(String(cString: cstr))
}
}
}
return constructor.constructor(constructor.db, arguments, tokenizerHandle)
}
func xDeleteTokenizer(tokenizerPointer: OpaquePointer?) {
guard let tokenizerPointer = tokenizerPointer else { return }
Unmanaged<AnyObject>.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).release()
}
func xTokenize(tokenizerPointer: OpaquePointer?, context: UnsafeMutableRawPointer?, flags: Int32, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer<Int8>?, Int32, Int32, Int32) -> Int32)?) -> Int32 {
guard let tokenizerPointer = tokenizerPointer else {
return SQLITE_ERROR
}
let object = Unmanaged<AnyObject>.fromOpaque(UnsafeMutableRawPointer(tokenizerPointer)).takeUnretainedValue()
guard let tokenizer = object as? FTS5Tokenizer else {
return SQLITE_ERROR
}
return tokenizer.tokenize(context: context, tokenization: FTS5Tokenization(rawValue: flags), pText: pText, nText: nText, tokenCallback: tokenCallback!)
}
var xTokenizer = fts5_tokenizer(xCreate: xCreateTokenizer, xDelete: xDeleteTokenizer, xTokenize: xTokenize)
let code = withUnsafeMutablePointer(to: &xTokenizer) { xTokenizerPointer in
api.pointee.xCreateTokenizer(UnsafeMutablePointer(mutating: api), Tokenizer.name, constructorPointer, xTokenizerPointer, deleteConstructor)
}
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
}
}
}
extension DatabaseQueue {
// MARK: - Custom FTS5 Tokenizers
/// Add a custom FTS5 tokenizer.
///
/// class MyTokenizer : FTS5CustomTokenizer { ... }
/// dbQueue.add(tokenizer: MyTokenizer.self)
public func add<Tokenizer: FTS5CustomTokenizer>(tokenizer: Tokenizer.Type) {
inDatabase { db in
db.add(tokenizer: Tokenizer.self)
}
}
}
#endif
+109 -109
View File
@@ -1,121 +1,121 @@
#if SQLITE_ENABLE_FTS5
/// A full text pattern that can query FTS5 virtual tables.
public struct FTS5Pattern {
/// The raw pattern string. Guaranteed to be a valid FTS5 pattern.
public let rawPattern: String
/// Creates a pattern that matches any token found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS5Pattern(matchingAnyTokenIn: "") // nil
/// FTS5Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingAnyTokenIn string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " OR "))
}
/// Creates a pattern that matches all tokens found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS5Pattern(matchingAllTokensIn: "") // nil
/// FTS5Pattern(matchingAllTokensIn: "foo bar") // foo bar
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingAllTokensIn string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " "))
}
/// Creates a pattern that matches a contiguous string; returns nil if no
/// pattern could be built.
///
/// FTS5Pattern(matchingPhrase: "") // nil
/// FTS5Pattern(matchingPhrase: "foo bar") // "foo bar"
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingPhrase string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
/// Creates a pattern that matches a contiguous string prefix; returns
/// nil if no pattern could be built.
///
/// FTS5Pattern(matchingPrefixPhrase: "") // nil
/// FTS5Pattern(matchingPrefixPhrase: "foo bar") // ^"foo bar"
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingPrefixPhrase string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"")
}
init(rawPattern: String, allowedColumns: [String] = []) throws {
// Correctness above all: use SQLite to validate the pattern.
//
// Invalid patterns have SQLite return an error on the first
// call to sqlite3_step() on a statement that matches against
// that pattern.
do {
try DatabaseQueue().inDatabase { db in
try db.create(virtualTable: "document", using: FTS5()) { t in
if allowedColumns.isEmpty {
t.column("__grdb__")
} else {
for column in allowedColumns {
t.column(column)
}
/// A full text pattern that can query FTS5 virtual tables.
public struct FTS5Pattern {
/// The raw pattern string. Guaranteed to be a valid FTS5 pattern.
public let rawPattern: String
/// Creates a pattern that matches any token found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS5Pattern(matchingAnyTokenIn: "") // nil
/// FTS5Pattern(matchingAnyTokenIn: "foo bar") // foo OR bar
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingAnyTokenIn string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " OR "))
}
/// Creates a pattern that matches all tokens found in the input string;
/// returns nil if no pattern could be built.
///
/// FTS5Pattern(matchingAllTokensIn: "") // nil
/// FTS5Pattern(matchingAllTokensIn: "foo bar") // foo bar
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingAllTokensIn string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: tokens.joined(separator: " "))
}
/// Creates a pattern that matches a contiguous string; returns nil if no
/// pattern could be built.
///
/// FTS5Pattern(matchingPhrase: "") // nil
/// FTS5Pattern(matchingPhrase: "foo bar") // "foo bar"
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingPhrase string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
}
/// Creates a pattern that matches a contiguous string prefix; returns
/// nil if no pattern could be built.
///
/// FTS5Pattern(matchingPrefixPhrase: "") // nil
/// FTS5Pattern(matchingPrefixPhrase: "foo bar") // ^"foo bar"
///
/// - parameter string: The string to turn into an FTS5 pattern
public init?(matchingPrefixPhrase string: String) {
guard let tokens = try? DatabaseQueue().inDatabase({ db in try db.makeTokenizer(.ascii()).nonSynonymTokens(in: string, for: .query) }) else { return nil }
guard !tokens.isEmpty else { return nil }
try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"")
}
init(rawPattern: String, allowedColumns: [String] = []) throws {
// Correctness above all: use SQLite to validate the pattern.
//
// Invalid patterns have SQLite return an error on the first
// call to sqlite3_step() on a statement that matches against
// that pattern.
do {
try DatabaseQueue().inDatabase { db in
try db.create(virtualTable: "document", using: FTS5()) { t in
if allowedColumns.isEmpty {
t.column("__grdb__")
} else {
for column in allowedColumns {
t.column(column)
}
}
try db.makeSelectStatement("SELECT * FROM document WHERE document MATCH ?")
.makeCursor(arguments: [rawPattern])
.next() // error on next() for invalid patterns
}
} catch let error as DatabaseError {
// Remove private SQL & arguments from the thrown error
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil)
try db.makeSelectStatement(sql: "SELECT * FROM document WHERE document MATCH ?")
.makeCursor(arguments: [rawPattern])
.next() // error on next() for invalid patterns
}
// Pattern is valid
self.rawPattern = rawPattern
} catch let error as DatabaseError {
// Remove private SQL & arguments from the thrown error
throw DatabaseError(resultCode: error.extendedResultCode, message: error.message, sql: nil, arguments: nil)
}
// Pattern is valid
self.rawPattern = rawPattern
}
}
extension Database {
// MARK: - FTS5
/// Creates a pattern from a raw pattern string; throws DatabaseError on
/// invalid syntax.
///
/// The pattern syntax is documented at https://www.sqlite.org/fts5.html#full_text_query_syntax
///
/// try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK
/// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND]
public func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern {
return try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map { $0.name })
}
extension Database {
// MARK: - FTS5
/// Creates a pattern from a raw pattern string; throws DatabaseError on
/// invalid syntax.
///
/// The pattern syntax is documented at https://www.sqlite.org/fts5.html#full_text_query_syntax
///
/// try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK
/// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND]
public func makeFTS5Pattern(rawPattern: String, forTable table: String) throws -> FTS5Pattern {
return try FTS5Pattern(rawPattern: rawPattern, allowedColumns: columns(in: table).map { $0.name })
}
}
extension FTS5Pattern : DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return rawPattern.databaseValue
}
/// Returns an FTS5Pattern initialized from *dbValue*, if it
/// contains a suitable value.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS5Pattern? {
return String
.fromDatabaseValue(dbValue)
.flatMap { try? FTS5Pattern(rawPattern: $0) }
}
extension FTS5Pattern : DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
return rawPattern.databaseValue
}
/// Returns an FTS5Pattern initialized from *dbValue*, if it
/// contains a suitable value.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> FTS5Pattern? {
return String
.fromDatabaseValue(dbValue)
.flatMap { try? FTS5Pattern(rawPattern: $0) }
}
}
#endif
+204 -196
View File
@@ -1,214 +1,222 @@
#if SQLITE_ENABLE_FTS5
/// A low-level SQLite function that lets FTS5Tokenizer notify tokens.
///
/// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:)
public typealias FTS5TokenCallback = @convention(c) (_ context: UnsafeMutableRawPointer?, _ flags: Int32, _ pToken: UnsafePointer<Int8>?, _ nToken: Int32, _ iStart: Int32, _ iEnd: Int32) -> Int32
/// The reason why FTS5 is requesting tokenization.
///
/// See https://www.sqlite.org/fts5.html#custom_tokenizers
public struct FTS5Tokenization : OptionSet {
public let rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
/// FTS5_TOKENIZE_QUERY
public static let query = FTS5Tokenization(rawValue: FTS5_TOKENIZE_QUERY)
/// FTS5_TOKENIZE_PREFIX
public static let prefix = FTS5Tokenization(rawValue: FTS5_TOKENIZE_PREFIX)
/// FTS5_TOKENIZE_DOCUMENT
public static let document = FTS5Tokenization(rawValue: FTS5_TOKENIZE_DOCUMENT)
/// FTS5_TOKENIZE_AUX
public static let aux = FTS5Tokenization(rawValue: FTS5_TOKENIZE_AUX)
}
/// The protocol for FTS5 tokenizers
public protocol FTS5Tokenizer : class {
/// Tokenizes the text described by `pText` and `nText`, and
/// notifies found tokens to the `tokenCallback` function.
///
/// It matches the `xTokenize` function documented at https://www.sqlite.org/fts5.html#custom_tokenizers
///
/// - parameters:
/// - context: An opaque pointer that is the first argument to
/// the `tokenCallback` function
/// - tokenization: The reason why FTS5 is requesting tokenization.
/// - pText: The tokenized text bytes. May or may not be
/// nul-terminated.
/// - nText: The number of bytes in the tokenized text.
/// - tokenCallback: The function to call for each found token.
/// It matches the `xToken` callback at https://www.sqlite.org/fts5.html#custom_tokenizers
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32
}
private class TokenizeContext {
var tokens: [(String, FTS5TokenFlags)] = []
}
extension FTS5Tokenizer {
/// Tokenizes the string argument into an array of
/// (String, FTS5TokenFlags) pairs.
///
/// let tokenizer = try db.makeTokenizer(.ascii())
/// try tokenizer.tokenize("foo bar", for: .document) // [("foo", flags), ("bar", flags)]
///
/// - parameter string: The string to tokenize
/// - parameter tokenization: The reason why tokenization is requested:
/// - .document: Tokenize like a document being inserted into an FTS table.
/// - .query: Tokenize like the search pattern of the MATCH operator.
/// - parameter tokenizer: A FTS5TokenizerDescriptor such as .ascii()
func tokenize(_ string: String, for tokenization: FTS5Tokenization) throws -> [(String, FTS5TokenFlags)] {
return try ContiguousArray(string.utf8).withUnsafeBufferPointer { buffer -> [(String, FTS5TokenFlags)] in
guard let addr = buffer.baseAddress else {
return []
}
let pText = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self)
let nText = Int32(buffer.count)
var context = TokenizeContext()
try withUnsafeMutablePointer(to: &context) { contextPointer in
let code = tokenize(context: UnsafeMutableRawPointer(contextPointer), tokenization: tokenization, pText: pText, nText: nText, tokenCallback: { (contextPointer, flags, pToken, nToken, iStart, iEnd) -> Int32 in
guard let contextPointer = contextPointer else { return SQLITE_ERROR }
// Extract token
guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else {
return SQLITE_OK
}
let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee
context.tokens.append((token, FTS5TokenFlags(rawValue: flags)))
return SQLITE_OK
})
if (code != SQLITE_OK) {
throw DatabaseError(resultCode: code)
}
}
return context.tokens
}
}
func nonSynonymTokens(in string: String, for tokenization: FTS5Tokenization) throws -> [String] {
var tokens: [String] = []
for (token, flags) in try tokenize(string, for: tokenization) {
if !flags.contains(.colocated) {
tokens.append(token)
}
}
return tokens
}
}
extension Database {
// MARK: - FTS5
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// Private type that makes a pre-registered FTS5 tokenizer available
/// through the FTS5Tokenizer protocol.
private final class FTS5RegisteredTokenizer : FTS5Tokenizer {
let xTokenizer: fts5_tokenizer
let tokenizerPointer: OpaquePointer
/// A low-level SQLite function that lets FTS5Tokenizer notify tokens.
///
/// See FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:)
public typealias FTS5TokenCallback = @convention(c) (_ context: UnsafeMutableRawPointer?, _ flags: Int32, _ pToken: UnsafePointer<Int8>?, _ nToken: Int32, _ iStart: Int32, _ iEnd: Int32) -> Int32
/// The reason why FTS5 is requesting tokenization.
///
/// See https://www.sqlite.org/fts5.html#custom_tokenizers
public struct FTS5Tokenization : OptionSet {
public let rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
/// FTS5_TOKENIZE_QUERY
public static let query = FTS5Tokenization(rawValue: FTS5_TOKENIZE_QUERY)
/// FTS5_TOKENIZE_PREFIX
public static let prefix = FTS5Tokenization(rawValue: FTS5_TOKENIZE_PREFIX)
/// FTS5_TOKENIZE_DOCUMENT
public static let document = FTS5Tokenization(rawValue: FTS5_TOKENIZE_DOCUMENT)
/// FTS5_TOKENIZE_AUX
public static let aux = FTS5Tokenization(rawValue: FTS5_TOKENIZE_AUX)
}
/// The protocol for FTS5 tokenizers
public protocol FTS5Tokenizer : class {
/// Tokenizes the text described by `pText` and `nText`, and
/// notifies found tokens to the `tokenCallback` function.
///
/// It matches the `xTokenize` function documented at https://www.sqlite.org/fts5.html#custom_tokenizers
///
/// - parameters:
/// - context: An opaque pointer that is the first argument to
/// the `tokenCallback` function
/// - tokenization: The reason why FTS5 is requesting tokenization.
/// - pText: The tokenized text bytes. May or may not be
/// nul-terminated.
/// - nText: The number of bytes in the tokenized text.
/// - tokenCallback: The function to call for each found token.
/// It matches the `xToken` callback at https://www.sqlite.org/fts5.html#custom_tokenizers
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32
}
private class TokenizeContext {
var tokens: [(String, FTS5TokenFlags)] = []
}
extension FTS5Tokenizer {
/// Tokenizes the string argument into an array of
/// (String, FTS5TokenFlags) pairs.
///
/// let tokenizer = try db.makeTokenizer(.ascii())
/// try tokenizer.tokenize("foo bar", for: .document) // [("foo", flags), ("bar", flags)]
///
/// - parameter string: The string to tokenize
/// - parameter tokenization: The reason why tokenization is requested:
/// - .document: Tokenize like a document being inserted into an FTS table.
/// - .query: Tokenize like the search pattern of the MATCH operator.
/// - parameter tokenizer: A FTS5TokenizerDescriptor such as .ascii()
func tokenize(_ string: String, for tokenization: FTS5Tokenization) throws -> [(String, FTS5TokenFlags)] {
return try ContiguousArray(string.utf8).withUnsafeBufferPointer { buffer -> [(String, FTS5TokenFlags)] in
guard let addr = buffer.baseAddress else {
return []
}
let pText = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self)
let nText = Int32(buffer.count)
init(xTokenizer: fts5_tokenizer, contextPointer: UnsafeMutableRawPointer?, arguments: [String]) throws {
guard let xCreate = xTokenizer.xCreate else {
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate")
}
self.xTokenizer = xTokenizer
var tokenizerPointer: OpaquePointer? = nil
let code: Int32
if let argument = arguments.first {
// Turn [String] into ContiguousArray<UnsafePointer<Int8>>
// (for an alternative implementation see https://oleb.net/blog/2016/10/swift-array-of-c-strings/)
func convertArguments<Result>(_ array: inout ContiguousArray<UnsafePointer<Int8>>, _ car: String, _ cdr: [String], _ body: (ContiguousArray<UnsafePointer<Int8>>) -> Result) -> Result {
return car.withCString { cString in
if let car = cdr.first {
array.append(cString)
return convertArguments(&array, car, Array(cdr.suffix(from: 1)), body)
} else {
return body(array)
}
}
var context = TokenizeContext()
try withUnsafeMutablePointer(to: &context) { contextPointer in
let code = tokenize(context: UnsafeMutableRawPointer(contextPointer), tokenization: tokenization, pText: pText, nText: nText, tokenCallback: { (contextPointer, flags, pToken, nToken, iStart, iEnd) -> Int32 in
guard let contextPointer = contextPointer else { return SQLITE_ERROR }
// Extract token
guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else {
return SQLITE_OK
}
var cStrings = ContiguousArray<UnsafePointer<Int8>>()
code = convertArguments(&cStrings, argument, Array(arguments.suffix(from: 1))) { cStrings in
cStrings.withUnsafeBufferPointer { azArg in
xCreate(contextPointer, UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), Int32(cStrings.count), &tokenizerPointer)
}
}
} else {
code = xCreate(contextPointer, nil, 0, &tokenizerPointer)
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: "failed fts5_tokenizer.xCreate")
}
if let tokenizerPointer = tokenizerPointer {
self.tokenizerPointer = tokenizerPointer
} else {
throw DatabaseError(resultCode: code, message: "nil tokenizer")
let context = contextPointer.assumingMemoryBound(to: TokenizeContext.self).pointee
context.tokens.append((token, FTS5TokenFlags(rawValue: flags)))
return SQLITE_OK
})
if (code != SQLITE_OK) {
throw DatabaseError(resultCode: code)
}
}
deinit {
if let delete = xTokenizer.xDelete {
delete(tokenizerPointer)
}
}
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 {
guard let xTokenize = xTokenizer.xTokenize else {
return SQLITE_ERROR
}
return xTokenize(tokenizerPointer, context, tokenization.rawValue, pText, nText, tokenCallback)
return context.tokens
}
}
func nonSynonymTokens(in string: String, for tokenization: FTS5Tokenization) throws -> [String] {
var tokens: [String] = []
for (token, flags) in try tokenize(string, for: tokenization) {
if !flags.contains(.colocated) {
tokens.append(token)
}
}
return tokens
}
}
extension Database {
// MARK: - FTS5
/// Private type that makes a pre-registered FTS5 tokenizer available
/// through the FTS5Tokenizer protocol.
private final class FTS5RegisteredTokenizer : FTS5Tokenizer {
let xTokenizer: fts5_tokenizer
let tokenizerPointer: OpaquePointer
/// Creates an FTS5 tokenizer, given its descriptor.
///
/// let unicode61 = try db.makeTokenizer(.unicode61())
///
/// It is a programmer error to use the tokenizer outside of a protected
/// database queue, or after the database has been closed.
///
/// Use this method when you implement a custom wrapper tokenizer:
///
/// final class MyTokenizer : FTS5WrapperTokenizer {
/// var wrappedTokenizer: FTS5Tokenizer
///
/// init(db: Database, arguments: [String]) throws {
/// wrappedTokenizer = try db.makeTokenizer(.unicode61())
/// }
/// }
public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> FTS5Tokenizer {
let api = FTS5.api(self)
init(xTokenizer: fts5_tokenizer, contextPointer: UnsafeMutableRawPointer?, arguments: [String]) throws {
guard let xCreate = xTokenizer.xCreate else {
throw DatabaseError(resultCode: .SQLITE_ERROR, message: "nil fts5_tokenizer.xCreate")
}
let xTokenizerPointer: UnsafeMutablePointer<fts5_tokenizer> = .allocate(capacity: 1)
defer { xTokenizerPointer.deallocate() }
self.xTokenizer = xTokenizer
let contextHandle: UnsafeMutablePointer<UnsafeMutableRawPointer?> = .allocate(capacity: 1)
defer { contextHandle.deallocate() }
let code = api.pointee.xFindTokenizer!(
UnsafeMutablePointer(mutating: api),
descriptor.name,
contextHandle,
xTokenizerPointer)
var tokenizerPointer: OpaquePointer? = nil
let code: Int32
if let argument = arguments.first {
// Turn [String] into ContiguousArray<UnsafePointer<Int8>>
// (for an alternative implementation see https://oleb.net/blog/2016/10/swift-array-of-c-strings/)
func convertArguments<Result>(_ array: inout ContiguousArray<UnsafePointer<Int8>>, _ car: String, _ cdr: [String], _ body: (ContiguousArray<UnsafePointer<Int8>>) -> Result) -> Result {
return car.withCString { cString in
if let car = cdr.first {
array.append(cString)
return convertArguments(&array, car, Array(cdr.suffix(from: 1)), body)
} else {
return body(array)
}
}
}
var cStrings = ContiguousArray<UnsafePointer<Int8>>()
code = convertArguments(&cStrings, argument, Array(arguments.suffix(from: 1))) { cStrings in
cStrings.withUnsafeBufferPointer { azArg in
xCreate(contextPointer, UnsafeMutablePointer(OpaquePointer(azArg.baseAddress!)), Int32(cStrings.count), &tokenizerPointer)
}
}
} else {
code = xCreate(contextPointer, nil, 0, &tokenizerPointer)
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code)
throw DatabaseError(resultCode: code, message: "failed fts5_tokenizer.xCreate")
}
let contextPointer = contextHandle.pointee
return try FTS5RegisteredTokenizer(xTokenizer: xTokenizerPointer.pointee, contextPointer: contextPointer, arguments: descriptor.arguments)
if let tokenizerPointer = tokenizerPointer {
self.tokenizerPointer = tokenizerPointer
} else {
throw DatabaseError(resultCode: code, message: "nil tokenizer")
}
}
deinit {
if let delete = xTokenizer.xDelete {
delete(tokenizerPointer)
}
}
func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 {
guard let xTokenize = xTokenizer.xTokenize else {
return SQLITE_ERROR
}
return xTokenize(tokenizerPointer, context, tokenization.rawValue, pText, nText, tokenCallback)
}
}
/// Creates an FTS5 tokenizer, given its descriptor.
///
/// let unicode61 = try db.makeTokenizer(.unicode61())
///
/// It is a programmer error to use the tokenizer outside of a protected
/// database queue, or after the database has been closed.
///
/// Use this method when you implement a custom wrapper tokenizer:
///
/// final class MyTokenizer : FTS5WrapperTokenizer {
/// var wrappedTokenizer: FTS5Tokenizer
///
/// init(db: Database, arguments: [String]) throws {
/// wrappedTokenizer = try db.makeTokenizer(.unicode61())
/// }
/// }
public func makeTokenizer(_ descriptor: FTS5TokenizerDescriptor) throws -> FTS5Tokenizer {
let api = FTS5.api(self)
let xTokenizerPointer: UnsafeMutablePointer<fts5_tokenizer> = .allocate(capacity: 1)
defer { xTokenizerPointer.deallocate() }
let contextHandle: UnsafeMutablePointer<UnsafeMutableRawPointer?> = .allocate(capacity: 1)
defer { contextHandle.deallocate() }
let code = api.pointee.xFindTokenizer!(
UnsafeMutablePointer(mutating: api),
descriptor.name,
contextHandle,
xTokenizerPointer)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code)
}
let contextPointer = contextHandle.pointee
return try FTS5RegisteredTokenizer(xTokenizer: xTokenizerPointer.pointee, contextPointer: contextPointer, arguments: descriptor.arguments)
}
}
#endif
+130 -109
View File
@@ -1,117 +1,138 @@
#if SQLITE_ENABLE_FTS5
/// An FTS5 tokenizer, suitable for FTS5 table definitions:
/// An FTS5 tokenizer, suitable for FTS5 table definitions:
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor
/// }
///
/// See https://www.sqlite.org/fts5.html#tokenizers
public struct FTS5TokenizerDescriptor {
/// The tokenizer components
///
/// // ["unicode61"]
/// FTS5TokenizerDescriptor.unicode61().components
///
/// // ["unicode61", "remove_diacritics", "0"]
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components
public let components: [String]
/// The tokenizer name
///
/// // "unicode61"
/// FTS5TokenizerDescriptor.unicode61().name
///
/// // "unicode61"
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).name
var name: String {
return components[0]
}
var arguments: [String] {
return Array(components.suffix(from: 1))
}
/// Creates an FTS5 tokenizer descriptor.
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor
/// let tokenizer = FTS5TokenizerDescriptor(components: ["porter", "unicode61", "remove_diacritics", "0"])
/// t.tokenizer = tokenizer
/// }
///
/// See https://www.sqlite.org/fts5.html#tokenizers
public struct FTS5TokenizerDescriptor {
/// The tokenizer components
///
/// // ["unicode61"]
/// FTS5TokenizerDescriptor.unicode61().components
///
/// // ["unicode61", "remove_diacritics", "0"]
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).components
public let components: [String]
/// The tokenizer name
///
/// // "unicode61"
/// FTS5TokenizerDescriptor.unicode61().name
///
/// // "unicode61"
/// FTS5TokenizerDescriptor.unicode61(removeDiacritics: false)).name
var name: String {
return components[0]
}
var arguments: [String] {
return Array(components.suffix(from: 1))
}
/// Creates an FTS5 tokenizer descriptor.
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// let tokenizer = FTS5TokenizerDescriptor(components: ["porter", "unicode61", "remove_diacritics", "0"])
/// t.tokenizer = tokenizer
/// }
///
/// - precondition: Components is not empty
public init(components: [String]) {
GRDBPrecondition(!components.isEmpty, "FTS5TokenizerDescriptor requires at least one component")
assert(!components.isEmpty)
self.components = components
}
/// The "ascii" tokenizer
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .ascii()
/// }
///
/// - parameters:
/// - separators: Unless empty (the default), SQLite will consider
/// these characters as token separators.
///
/// See https://www.sqlite.org/fts5.html#ascii_tokenizer
public static func ascii(separators: Set<Character> = []) -> FTS5TokenizerDescriptor {
if separators.isEmpty {
return FTS5TokenizerDescriptor(components: ["ascii"])
} else {
return FTS5TokenizerDescriptor(components: ["ascii", "separators", separators.map { String($0) }.joined(separator: "").sqlExpression.sql])
}
}
/// The "porter" tokenizer
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .porter()
/// }
///
/// - parameters:
/// - base: An eventual wrapping tokenizer which replaces the
// default unicode61() base tokenizer.
///
/// See https://www.sqlite.org/fts5.html#porter_tokenizer
public static func porter(wrapping base: FTS5TokenizerDescriptor? = nil) -> FTS5TokenizerDescriptor {
if let base = base {
return FTS5TokenizerDescriptor(components: ["porter"] + base.components)
} else {
return FTS5TokenizerDescriptor(components: ["porter"])
}
}
/// An "unicode61" tokenizer
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .unicode61()
/// }
///
/// - parameters:
/// - removeDiacritics: If true (the default), then SQLite will
/// strip diacritics from latin characters.
/// - separators: Unless empty (the default), SQLite will consider
/// these characters as token separators.
/// - tokenCharacters: Unless empty (the default), SQLite will
/// consider these characters as token characters.
///
/// See https://www.sqlite.org/fts5.html#unicode61_tokenizer
public static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS5TokenizerDescriptor {
var components: [String] = ["unicode61"]
if !removeDiacritics {
components.append(contentsOf: ["remove_diacritics", "0"])
}
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
components.append(contentsOf: ["separators", separators.sorted().map { String($0) }.joined(separator: "").sqlExpression.sql])
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
components.append(contentsOf: ["tokenchars", tokenCharacters.sorted().map { String($0) }.joined(separator: "").sqlExpression.sql])
}
return FTS5TokenizerDescriptor(components: components)
/// - precondition: Components is not empty
public init(components: [String]) {
GRDBPrecondition(!components.isEmpty, "FTS5TokenizerDescriptor requires at least one component")
assert(!components.isEmpty)
self.components = components
}
/// The "ascii" tokenizer
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .ascii()
/// }
///
/// - parameters:
/// - separators: Unless empty (the default), SQLite will consider
/// these characters as token separators.
///
/// See https://www.sqlite.org/fts5.html#ascii_tokenizer
public static func ascii(separators: Set<Character> = []) -> FTS5TokenizerDescriptor {
if separators.isEmpty {
return FTS5TokenizerDescriptor(components: ["ascii"])
} else {
return FTS5TokenizerDescriptor(components: ["ascii", "separators", separators.map { String($0) }.joined(separator: "").sqlExpression.quotedSQL()])
}
}
/// The "porter" tokenizer
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .porter()
/// }
///
/// - parameters:
/// - base: An eventual wrapping tokenizer which replaces the
// default unicode61() base tokenizer.
///
/// See https://www.sqlite.org/fts5.html#porter_tokenizer
public static func porter(wrapping base: FTS5TokenizerDescriptor? = nil) -> FTS5TokenizerDescriptor {
if let base = base {
return FTS5TokenizerDescriptor(components: ["porter"] + base.components)
} else {
return FTS5TokenizerDescriptor(components: ["porter"])
}
}
/// An "unicode61" tokenizer
///
/// db.create(virtualTable: "book", using: FTS5()) { t in
/// t.tokenizer = .unicode61()
/// }
///
/// - parameters:
/// - diacritics: By default SQLite will strip diacritics from
/// latin characters.
/// - separators: Unless empty (the default), SQLite will consider
/// these characters as token separators.
/// - tokenCharacters: Unless empty (the default), SQLite will
/// consider these characters as token characters.
///
/// See https://www.sqlite.org/fts5.html#unicode61_tokenizer
public static func unicode61(diacritics: FTS5.Diacritics = .removeLegacy, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS5TokenizerDescriptor {
var components: [String] = ["unicode61"]
switch diacritics {
case .removeLegacy:
break
case .keep:
components.append(contentsOf: ["remove_diacritics", "0"])
#if GRDBCUSTOMSQLITE
case .remove:
components.append(contentsOf: ["remove_diacritics", "2"])
#endif
}
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
components.append(contentsOf: [
"separators",
separators
.sorted()
.map { String($0) }
.joined(separator: "")
.sqlExpression
.quotedSQL()])
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with both FTS3Pattern(matchingAnyTokenIn:tokenizer:) and Database.create(virtualTable:using:)
components.append(contentsOf: [
"tokenchars",
tokenCharacters
.sorted()
.map { String($0) }
.joined(separator: "")
.sqlExpression
.quotedSQL()])
}
return FTS5TokenizerDescriptor(components: components)
}
}
#endif
+136 -128
View File
@@ -1,141 +1,149 @@
#if SQLITE_ENABLE_FTS5
/// Flags that tell SQLite how to register a token.
///
/// See https://www.sqlite.org/fts5.html#custom_tokenizers
public struct FTS5TokenFlags : OptionSet {
public let rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
/// FTS5_TOKEN_COLOCATED
public static let colocated = FTS5TokenFlags(rawValue: FTS5_TOKEN_COLOCATED)
#if SWIFT_PACKAGE
import CSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// Flags that tell SQLite how to register a token.
///
/// See https://www.sqlite.org/fts5.html#custom_tokenizers
public struct FTS5TokenFlags : OptionSet {
public let rawValue: Int32
public init(rawValue: Int32) {
self.rawValue = rawValue
}
/// A function that lets FTS5WrapperTokenizer notify tokens.
///
/// See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:)
public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> ()
/// FTS5_TOKEN_COLOCATED
public static let colocated = FTS5TokenFlags(rawValue: FTS5_TOKEN_COLOCATED)
}
/// A function that lets FTS5WrapperTokenizer notify tokens.
///
/// See FTS5WrapperTokenizer.accept(token:flags:tokenCallback:)
public typealias FTS5WrapperTokenCallback = (_ token: String, _ flags: FTS5TokenFlags) throws -> ()
/// The protocol for custom FTS5 tokenizers that wrap another tokenizer.
///
/// Types that adopt FTS5WrapperTokenizer don't have to implement the
/// low-level FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:).
///
/// Instead, they process regular Swift strings.
///
/// Here is the implementation for a trivial tokenizer that wraps the
/// built-in ascii tokenizer without any custom processing:
///
/// class TrivialAsciiTokenizer : FTS5WrapperTokenizer {
/// static let name = "trivial"
/// let wrappedTokenizer: FTS5Tokenizer
///
/// init(db: Database, arguments: [String]) throws {
/// wrappedTokenizer = try db.makeTokenizer(.ascii())
/// }
///
/// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
/// try tokenCallback(token, flags)
/// }
/// }
public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
/// The wrapped tokenizer
var wrappedTokenizer: FTS5Tokenizer { get }
/// The protocol for custom FTS5 tokenizers that wrap another tokenizer.
/// Given a token produced by the wrapped tokenizer, notifies customized
/// tokens to the `tokenCallback` function.
///
/// Types that adopt FTS5WrapperTokenizer don't have to implement the
/// low-level FTS5Tokenizer.tokenize(context:flags:pText:nText:tokenCallback:).
/// For example:
///
/// Instead, they process regular Swift strings.
///
/// Here is the implementation for a trivial tokenizer that wraps the
/// built-in ascii tokenizer without any custom processing:
///
/// class TrivialAsciiTokenizer : FTS5WrapperTokenizer {
/// static let name = "trivial"
/// let wrappedTokenizer: FTS5Tokenizer
///
/// init(db: Database, arguments: [String]) throws {
/// wrappedTokenizer = try db.makeTokenizer(.ascii())
/// }
///
/// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
/// try tokenCallback(token, flags)
/// }
/// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
/// // pass through:
/// try tokenCallback(token, flags)
/// }
public protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
/// The wrapped tokenizer
var wrappedTokenizer: FTS5Tokenizer { get }
/// Given a token produced by the wrapped tokenizer, notifies customized
/// tokens to the `tokenCallback` function.
///
/// For example:
///
/// func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws {
/// // pass through:
/// try tokenCallback(token, flags)
/// }
///
/// When implementing the accept method, there are a two rules
/// to observe:
///
/// 1. Errors thrown by the tokenCallback function must not be caught.
///
/// 2. The input `flags` should be given unmodified to the tokenCallback
/// function, unless you union it with the .colocated flag when the
/// tokenizer produces synonyms (see
/// https://www.sqlite.org/fts5.html#synonym_support).
///
/// - parameters:
/// - token: A token produced by the wrapped tokenizer
/// - flags: Flags that tell SQLite how to register a token.
/// - tokenization: The reason why FTS5 is requesting tokenization.
/// - tokenCallback: The function to call for each customized token.
func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws
}
private struct FTS5WrapperContext {
let tokenizer: FTS5WrapperTokenizer
let context: UnsafeMutableRawPointer?
let tokenization: FTS5Tokenization
let tokenCallback: FTS5TokenCallback
}
extension FTS5WrapperTokenizer {
/// Default implementation
public func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 {
// `tokenCallback` is @convention(c). This requires a little setup
// in order to transfer context.
var customContext = FTS5WrapperContext(
tokenizer: self,
context: context,
tokenization: tokenization,
tokenCallback: tokenCallback)
return withUnsafeMutablePointer(to: &customContext) { customContextPointer in
// Invoke wrappedTokenizer
return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in
// Extract token produced by wrapped tokenizer
guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else {
return 0 // SQLITE_OK
}
// Extract context
let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee
let tokenizer = customContext.tokenizer
let context = customContext.context
let tokenization = customContext.tokenization
let tokenCallback = customContext.tokenCallback
// Process token produced by wrapped tokenizer
do {
try tokenizer.accept(
token: token,
flags: FTS5TokenFlags(rawValue: tokenFlags),
for: tokenization,
tokenCallback: { (token, flags) in
// Turn token into bytes
return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in
guard let addr = buffer.baseAddress else {
return
}
let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self)
let nToken = Int32(buffer.count)
// Inject token bytes into SQLite
let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: "token callback failed")
}
///
/// When implementing the accept method, there are a two rules
/// to observe:
///
/// 1. Errors thrown by the tokenCallback function must not be caught.
///
/// 2. The input `flags` should be given unmodified to the tokenCallback
/// function, unless you union it with the .colocated flag when the
/// tokenizer produces synonyms (see
/// https://www.sqlite.org/fts5.html#synonym_support).
///
/// - parameters:
/// - token: A token produced by the wrapped tokenizer
/// - flags: Flags that tell SQLite how to register a token.
/// - tokenization: The reason why FTS5 is requesting tokenization.
/// - tokenCallback: The function to call for each customized token.
func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: FTS5WrapperTokenCallback) throws
}
private struct FTS5WrapperContext {
let tokenizer: FTS5WrapperTokenizer
let context: UnsafeMutableRawPointer?
let tokenization: FTS5Tokenization
let tokenCallback: FTS5TokenCallback
}
extension FTS5WrapperTokenizer {
/// Default implementation
public func tokenize(context: UnsafeMutableRawPointer?, tokenization: FTS5Tokenization, pText: UnsafePointer<Int8>?, nText: Int32, tokenCallback: @escaping FTS5TokenCallback) -> Int32 {
// `tokenCallback` is @convention(c). This requires a little setup
// in order to transfer context.
var customContext = FTS5WrapperContext(
tokenizer: self,
context: context,
tokenization: tokenization,
tokenCallback: tokenCallback)
return withUnsafeMutablePointer(to: &customContext) { customContextPointer in
// Invoke wrappedTokenizer
return wrappedTokenizer.tokenize(context: customContextPointer, tokenization: tokenization, pText: pText, nText: nText) { (customContextPointer, tokenFlags, pToken, nToken, iStart, iEnd) in
// Extract token produced by wrapped tokenizer
guard let token = pToken.flatMap({ String(data: Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0), count: Int(nToken), deallocator: .none), encoding: .utf8) }) else {
return 0 // SQLITE_OK
}
// Extract context
let customContext = customContextPointer!.assumingMemoryBound(to: FTS5WrapperContext.self).pointee
let tokenizer = customContext.tokenizer
let context = customContext.context
let tokenization = customContext.tokenization
let tokenCallback = customContext.tokenCallback
// Process token produced by wrapped tokenizer
do {
try tokenizer.accept(
token: token,
flags: FTS5TokenFlags(rawValue: tokenFlags),
for: tokenization,
tokenCallback: { (token, flags) in
// Turn token into bytes
return try ContiguousArray(token.utf8).withUnsafeBufferPointer { buffer in
guard let addr = buffer.baseAddress else {
return
}
})
return SQLITE_OK
} catch let error as DatabaseError {
return error.extendedResultCode.rawValue
} catch {
return SQLITE_ERROR
}
let pToken = UnsafeMutableRawPointer(mutating: addr).assumingMemoryBound(to: Int8.self)
let nToken = Int32(buffer.count)
// Inject token bytes into SQLite
let code = tokenCallback(context, flags.rawValue, pToken, nToken, iStart, iEnd)
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: code, message: "token callback failed")
}
}
})
return SQLITE_OK
} catch let error as DatabaseError {
return error.extendedResultCode.rawValue
} catch {
return SQLITE_ERROR
}
}
}
}
}
#endif
+157
View File
@@ -0,0 +1,157 @@
import Dispatch
// Fixits for changes introduced by GRDB 4.0.0
extension Cursor {
@available(*, unavailable, renamed: "compactMap")
public func flatMap<ElementOfResult>(_ transform: @escaping (Element) throws -> ElementOfResult?) -> MapCursor<FilterCursor<MapCursor<Self, ElementOfResult?>>, ElementOfResult> { preconditionFailure() }
}
extension DatabaseWriter {
@available(*, unavailable, message: "Use concurrentRead instead")
public func readFromCurrentState(_ block: @escaping (Database) -> Void) throws { preconditionFailure() }
}
extension ValueObservation {
@available(*, unavailable, message: "Provide the reducer in a (Database) -> Reducer closure")
public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation { preconditionFailure() }
@available(*, unavailable, message: "Use distinctUntilChanged() instead")
public static func tracking<Value>(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (Database) throws -> Value) -> ValueObservation<DistinctUntilChangedValueReducer<RawValueReducer<Value>>> where Value: Equatable { preconditionFailure() }
}
@available(*, unavailable, renamed: "FastDatabaseValueCursor")
public typealias ColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastDatabaseValueCursor<Value>
@available(*, unavailable, renamed: "FastNullableDatabaseValueCursor")
public typealias NullableColumnCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> = FastNullableDatabaseValueCursor<Value>
extension Database {
@available(*, unavailable, renamed: "execute(sql:arguments:)")
public func execute(_ sql: String, arguments: StatementArguments? = nil) throws { preconditionFailure() }
@available(*, unavailable, renamed: "makeSelectStatement(sql:)")
public func makeSelectStatement(_ sql: String) throws -> SelectStatement { preconditionFailure() }
@available(*, unavailable, renamed: "cachedSelectStatement(sql:)")
public func cachedSelectStatement(_ sql: String) throws -> SelectStatement { preconditionFailure() }
@available(*, unavailable, renamed: "makeUpdateStatement(sql:)")
public func makeUpdateStatement(_ sql: String) throws -> UpdateStatement { preconditionFailure() }
@available(*, unavailable, renamed: "cachedUpdateStatement(sql:)")
public func cachedUpdateStatement(_ sql: String) throws -> UpdateStatement { preconditionFailure() }
}
extension DatabaseValueConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self> { preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped> { preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?] { preconditionFailure() }
}
extension Row {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor { preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row] { preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row? { preconditionFailure() }
}
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastDatabaseValueCursor<Self> { preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> FastNullableDatabaseValueCursor<Wrapped> { preconditionFailure() }
}
extension FetchableRecord {
@available(*, unavailable, renamed: "fetchCursor(_:sql:arguments:adapter:)")
public static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self> { preconditionFailure() }
@available(*, unavailable, renamed: "fetchAll(_:sql:arguments:adapter:)")
public static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self] { preconditionFailure() }
@available(*, unavailable, renamed: "fetchOne(_:sql:arguments:adapter:)")
public static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self? { preconditionFailure() }
}
extension SQLRequest {
@available(*, unavailable, renamed: "init(sql:arguments:adapter:cached:)")
public init(_ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil, cached: Bool = false) { preconditionFailure() }
}
extension SQLExpressionLiteral {
@available(*, unavailable, renamed: "init(sql:arguments:)")
public init(_ sql: String, arguments: StatementArguments? = nil) { preconditionFailure() }
}
extension SQLExpression {
@available(*, unavailable, message: "Use sqlLiteral property instead")
public var literal: SQLExpressionLiteral { preconditionFailure() }
}
extension FTS3TokenizerDescriptor {
@available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)")
public static func unicode61(removeDiacritics: Bool, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS3TokenizerDescriptor { preconditionFailure() }
}
#if SQLITE_ENABLE_FTS5
extension FTS5TokenizerDescriptor {
@available(*, unavailable, renamed: "unicode61(diacritics:separators:tokenCharacters:)")
public static func unicode61(removeDiacritics: Bool = true, separators: Set<Character> = [], tokenCharacters: Set<Character> = []) -> FTS5TokenizerDescriptor { preconditionFailure() }
}
#endif
extension DatabaseValue {
@available(*, unavailable)
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T where T: DatabaseValueConvertible { preconditionFailure() }
@available(*, unavailable)
public func losslessConvert<T>(sql: String? = nil, arguments: StatementArguments? = nil) -> T? where T: DatabaseValueConvertible { preconditionFailure() }
}
extension ValueScheduling {
@available(*, unavailable, renamed: "async(onQueue:startImmediately:)")
public static func onQueue(_ queue: DispatchQueue, startImmediately: Bool) -> ValueScheduling { preconditionFailure() }
}
extension ValueObservation {
@available(*, unavailable, message: "Observation extent is controlled by the lifetime of observers returned by the start() method.")
public var extent: Database.TransactionObservationExtent {
get { preconditionFailure() }
set { preconditionFailure() }
}
}
extension Configuration {
@available(*, unavailable, message: "Run the PRAGMA cipher_page_size in Configuration.prepareDatabase instead.")
public var cipherPageSize: Int {
get { preconditionFailure() }
set { preconditionFailure() }
}
@available(*, unavailable, message: "Run the PRAGMA kdf_iter in Configuration.prepareDatabase instead.")
public var kdfIterations: Int {
get { preconditionFailure() }
set { preconditionFailure() }
}
}
-19
View File
@@ -1,19 +0,0 @@
import Foundation
@available(*, unavailable, renamed:"Database.ForeignKeyAction")
public typealias SQLForeignKeyAction = Database.ForeignKeyAction
@available(*, unavailable, renamed:"Database.ColumnType")
public typealias SQLColumnType = Database.ColumnType
@available(*, unavailable, renamed:"Database.ConflictResolution")
public typealias SQLConflictResolution = Database.ConflictResolution
@available(*, unavailable, renamed:"Database.CollationName")
public typealias SQLCollation = Database.CollationName
@available(*, unavailable, renamed:"SQLSpecificExpressible")
public typealias _SpecificSQLExpressible = SQLSpecificExpressible
@available(*, unavailable, renamed:"SQLExpression")
public typealias _SQLExpression = SQLExpression
-55
View File
@@ -1,55 +0,0 @@
extension Row {
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch<Request: FetchRequest>(_ db: Database, _ request: Request) -> Any { preconditionFailure() }
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
}
extension DatabaseValueConvertible {
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch<Request: FetchRequest>(_ db: Database, _ request: Request) -> Any { preconditionFailure() }
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
}
extension Optional where Wrapped: DatabaseValueConvertible {
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch<Request: FetchRequest>(_ db: Database, _ request: Request) -> Any { preconditionFailure() }
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
}
extension QueryInterfaceRequest {
@available(*, unavailable, renamed:"fetchCursor")
public func fetch(_ db: Database) -> Any { preconditionFailure() }
}
extension FetchableRecord {
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch<Request: FetchRequest>(_ db: Database, _ request: Request) -> Any { preconditionFailure() }
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) -> Any { preconditionFailure() }
}
extension FetchableRecord where Self: TableRecord {
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch(_ db: Database) -> Any { preconditionFailure() }
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) -> Any where Sequence.Iterator.Element: DatabaseValueConvertible { preconditionFailure() }
@available(*, unavailable, renamed:"fetchCursor")
public static func fetch(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) -> Any { preconditionFailure() }
}
@available(*, unavailable, message:"DatabaseSequence has been replaced by Cursor.")
public struct DatabaseSequence<T> { }
@available(*, unavailable, message:"DatabaseIterator has been replaced by Cursor.")
public struct DatabaseIterator<T> { }
-4
View File
@@ -1,4 +0,0 @@
extension DatabaseError {
@available(*, unavailable, renamed:"resultCode")
public var code: Int32 { return 0 }
}
-9
View File
@@ -1,9 +0,0 @@
extension Database {
@available(*, unavailable, renamed:"inTransaction")
public func writeInTransaction(_ kind: Database.TransactionKind? = nil, _ block: (Database) throws -> Database.TransactionCompletion) throws { }
}
extension DatabaseValue {
@available(*, unavailable, message:"DatabaseSequence has been replaced by Cursor.")
public func value() -> Any { preconditionFailure() }
}
-4
View File
@@ -1,4 +0,0 @@
extension FetchRequest {
@available(*, unavailable, message:"Use QueryInterfaceRequest.asRequest(of:), or AnyFetchRequest")
public func bound<T>(to type: T.Type) -> AnyFetchRequest<T> { preconditionFailure() }
}
-28
View File
@@ -1,28 +0,0 @@
extension Row {
@available(*, unavailable, message:"use subscript instead: row[index]")
public func value(atIndex index: Int) -> DatabaseValueConvertible? { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[index]")
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value? { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[index]")
public func value<Value: DatabaseValueConvertible>(atIndex index: Int) -> Value { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[column]")
public func value(named name: String) -> DatabaseValueConvertible? { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[column]")
public func value<Value: DatabaseValueConvertible>(named name: String) -> Value? { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[column]")
public func value<Value: DatabaseValueConvertible>(named name: String) -> Value { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[column]")
public func value(_ column: Column) -> DatabaseValueConvertible? { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[column]")
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value? { preconditionFailure() }
@available(*, unavailable, message:"use subscript instead: row[column]")
public func value<Value: DatabaseValueConvertible>(_ column: Column) -> Value { preconditionFailure() }
}
-85
View File
@@ -1,85 +0,0 @@
/// :nodoc:
@available(*, unavailable, renamed:"FetchRequest")
public typealias Request = FetchRequest
/// :nodoc:
@available(*, unavailable, renamed:"FetchableRecord")
public typealias RowConvertible = FetchableRecord
/// :nodoc:
@available(*, unavailable, renamed:"TableRecord")
public typealias TableMapping = TableRecord
/// :nodoc:
@available(*, unavailable, renamed:"MutablePersistableRecord")
public typealias MutablePersistable = MutablePersistableRecord
/// :nodoc:
@available(*, unavailable, renamed:"PersistableRecord")
public typealias Persistable = PersistableRecord
/// :nodoc:
@available(*, unavailable, renamed:"TableAlias")
public typealias SQLTableQualifier = TableAlias
extension Database {
/// :nodoc:
@available(*, unavailable, message: "Use db.columns(in: tableName).count instead")
public func columnCount(in tableName: String) throws -> Int { preconditionFailure() }
}
extension SelectStatement {
/// :nodoc:
@available(*, unavailable, renamed:"DatabaseRegion")
public typealias SelectionInfo = DatabaseRegion
/// :nodoc:
@available(*, unavailable, renamed:"databaseRegion")
public var selectionInfo: DatabaseRegion { preconditionFailure() }
/// :nodoc:
@available(*, unavailable, renamed:"databaseRegion")
public var fetchedRegion: DatabaseRegion { preconditionFailure() }
}
extension DatabaseEventKind {
/// :nodoc:
@available(*, unavailable, message: "Use DatabaseRegion.isModified(byEventsOfKind:) instead")
public func impacts(_ region: DatabaseRegion) -> Bool { preconditionFailure() }
}
extension Record {
/// :nodoc:
@available(*, unavailable, renamed: "hasDatabaseChanges")
public var hasPersistentChangedValues: Bool { preconditionFailure() }
/// :nodoc:
@available(*, unavailable, renamed: "databaseChanges")
public var persistentChangedValues: [String: DatabaseValue?] { preconditionFailure() }
}
@available(*, unavailable, message: "Use changes methods defined on the MutablePersistableRecord protocol: databaseEquals(_:), databaseChanges(from:), updateChanges(from:)")
public final class RecordBox<T: FetchableRecord & MutablePersistableRecord>: Record { }
extension MutablePersistableRecord {
/// :nodoc:
@available(*, unavailable, renamed: "databaseEquals")
public func databaseEqual(_ record: Self) -> Bool { preconditionFailure() }
}
extension Row {
/// :nodoc:
@available(*, unavailable, message: "Use row.scopes.names instead")
var scopeNames: Set<String> { preconditionFailure() }
/// :nodoc:
@available(*, unavailable, message: "Use row.scopes[name] instead")
public func scoped(on name: String) -> Row? { preconditionFailure() }
}
extension FetchRequest {
/// :nodoc:
@available(*, unavailable, renamed:"databaseRegion(_:)")
public func fetchedRegion(_ db: Database) throws -> DatabaseRegion { preconditionFailure() }
}
-210
View File
@@ -1,210 +0,0 @@
//
// Fixits-Swift2.swift
// GRDB
//
// Created by Swiftlyfalling.
//
// Provides automatic renaming Fix-Its for many of the Swift 2.x -> Swift 3 GRDB API changes.
// Consult the CHANGELOG.md and documentation for details on all of the changes.
//
import Foundation
#if os(iOS)
import UIKit
#endif
// Database Connections
@available(*, unavailable, renamed:"Database.BusyMode")
public typealias BusyMode = Database.BusyMode
@available(*, unavailable, renamed:"Database.CheckpointMode")
public typealias CheckpointMode = Database.CheckpointMode
@available(*, unavailable, renamed:"Database.TransactionKind")
public typealias TransactionKind = Database.TransactionKind
@available(*, unavailable, renamed:"Database.TransactionCompletion")
public typealias TransactionCompletion = Database.TransactionCompletion
@available(*, unavailable, renamed:"Database.BusyCallback")
public typealias BusyCallback = Database.BusyCallback
extension DatabasePool {
#if os(iOS)
@available(*, unavailable, renamed:"setupMemoryManagement(in:)")
public func setupMemoryManagement(application: UIApplication) { }
#endif
#if SQLITE_HAS_CODEC
@available(*, unavailable, renamed:"change(passphrase:)")
public func changePassphrase(_ passphrase: String) throws { }
#endif
}
extension DatabaseQueue {
#if os(iOS)
@available(*, unavailable, renamed:"setupMemoryManagement(in:)")
public func setupMemoryManagement(application: UIApplication) { }
#endif
#if SQLITE_HAS_CODEC
@available(*, unavailable, renamed:"change(passphrase:)")
public func changePassphrase(_ passphrase: String) throws { }
#endif
}
// SQL Functions
extension Database {
@available(*, unavailable, renamed:"add(function:)")
public func addFunction(_ function: DatabaseFunction) { }
@available(*, unavailable, renamed:"remove(function:)")
public func removeFunction(_ function: DatabaseFunction) { }
}
extension DatabasePool {
@available(*, unavailable, renamed:"add(function:)")
public func addFunction(_ function: DatabaseFunction) { }
@available(*, unavailable, renamed:"remove(function:)")
public func removeFunction(_ function: DatabaseFunction) { }
}
extension DatabaseQueue {
@available(*, unavailable, renamed:"add(function:)")
public func addFunction(_ function: DatabaseFunction) { }
@available(*, unavailable, renamed:"remove(function:)")
public func removeFunction(_ function: DatabaseFunction) { }
}
extension DatabaseReader {
@available(*, unavailable, renamed:"add(function:)")
public func addFunction(_ function: DatabaseFunction) { }
@available(*, unavailable, renamed:"remove(function:)")
public func removeFunction(_ function: DatabaseFunction) { }
}
extension DatabaseFunction {
@available(*, unavailable, renamed:"capitalize")
public static let capitalizedString = capitalize
@available(*, unavailable, renamed:"lowercase")
public static let lowercaseString = lowercase
@available(*, unavailable, renamed:"uppercase")
public static let uppercaseString = uppercase
}
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
extension DatabaseFunction {
@available(*, unavailable, renamed:"localizedCapitalize")
public static let localizedCapitalizedString = localizedCapitalize
@available(*, unavailable, renamed:"localizedLowercase")
public static let localizedLowercaseString = localizedLowercase
@available(*, unavailable, renamed:"localizedUppercase")
public static let localizedUppercaseString = localizedUppercase
}
// SQL Collations
extension Database {
@available(*, unavailable, renamed:"add(collation:)")
public func addCollation(_ collation: DatabaseCollation) { }
@available(*, unavailable, renamed:"remove(collation:)")
public func removeCollation(_ collation: DatabaseCollation) { }
}
extension DatabasePool {
@available(*, unavailable, renamed:"add(collation:)")
public func addCollation(_ collation: DatabaseCollation) { }
@available(*, unavailable, renamed:"remove(collation:)")
public func removeCollation(_ collation: DatabaseCollation) { }
}
extension DatabaseQueue {
@available(*, unavailable, renamed:"add(collation:)")
public func addCollation(_ collation: DatabaseCollation) { }
@available(*, unavailable, renamed:"remove(collation:)")
public func removeCollation(_ collation: DatabaseCollation) { }
}
extension DatabaseReader {
@available(*, unavailable, renamed:"add(collation:)")
public func addCollation(_ collation: DatabaseCollation) { }
@available(*, unavailable, renamed:"remove(collation:)")
public func removeCollation(_ collation: DatabaseCollation) { }
}
// Prepared Statements
extension Database {
@available(*, unavailable, renamed:"makeSelectStatement(_:)")
func selectStatement(_ sql: String) throws -> SelectStatement { preconditionFailure() }
@available(*, unavailable, renamed:"makeUpdateStatement(_:)")
func updateStatement(_ sql: String) throws -> UpdateStatement { preconditionFailure() }
}
extension Statement {
@available(*, unavailable, renamed:"validate(arguments:)")
public func validateArguments(_ arguments: StatementArguments) throws { }
}
// Transaction Observers
extension Database {
@available(*, unavailable, message:"Use add(transactionObserver:) instead. Database events filtering is now performed by transaction observers themselves.")
public func addTransactionObserver(_ transactionObserver: TransactionObserver, forDatabaseEvents filter: ((DatabaseEventKind) -> Bool)? = nil) { }
@available(*, unavailable, renamed:"remove(transactionObserver:)")
public func removeTransactionObserver(_ transactionObserver: TransactionObserver) { }
}
extension DatabaseWriter {
@available(*, unavailable, message:"Use add(transactionObserver:) instead. Database events filtering is now performed by transaction observers themselves.")
public func addTransactionObserver(_ transactionObserver: TransactionObserver, forDatabaseEvents filter: ((DatabaseEventKind) -> Bool)? = nil) { }
@available(*, unavailable, renamed:"remove(transactionObserver:)")
public func removeTransactionObserver(_ transactionObserver: TransactionObserver) { }
}
@available(*, unavailable, renamed:"TransactionObserver")
public typealias TransactionObserverType = TransactionObserver
// Query Interface
@available(*, unavailable, renamed:"Column")
public typealias SQLColumn = Column
/// :nodoc:
extension SQLSpecificExpressible {
@available(*, unavailable, renamed:"capitalized")
public var capitalizedString: SQLExpression { get { return capitalized } }
@available(*, unavailable, renamed:"lowercased")
public var lowercaseString: SQLExpression { get { return lowercased } }
@available(*, unavailable, renamed:"uppercased")
public var uppercaseString: SQLExpression { get { return uppercased } }
}
/// :nodoc:
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
extension SQLSpecificExpressible {
@available(*, unavailable, renamed:"localizedCapitalized")
public var localizedCapitalizedString: SQLExpression { get { return localizedCapitalized } }
@available(*, unavailable, renamed:"localizedLowercased")
public var localizedLowercaseString: SQLExpression { get { return localizedLowercased } }
@available(*, unavailable, renamed:"localizedUppercased")
public var localizedUppercaseString: SQLExpression { get { return localizedUppercased } }
}
+5 -5
View File
@@ -100,7 +100,7 @@ public struct DatabaseMigrator {
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// }
/// try db.execute("INSERT INTO new_player SELECT * FROM player")
/// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
/// try db.drop(table: "player")
/// try db.rename(table: "new_player", to: "player")
/// }
@@ -119,7 +119,7 @@ public struct DatabaseMigrator {
registerMigration(Migration(identifier: identifier, disabledForeignKeyChecks: true, migrate: migrate))
}
#else
@available(iOS 8.2, OSX 10.10, *)
@available(OSX 10.10, *)
/// Registers an advanced migration, as described at https://www.sqlite.org/lang_altertable.html#otheralter
///
/// // Add a NOT NULL constraint on players.name:
@@ -128,7 +128,7 @@ public struct DatabaseMigrator {
/// t.autoIncrementedPrimaryKey("id")
/// t.column("name", .text).notNull()
/// }
/// try db.execute("INSERT INTO new_player SELECT * FROM player")
/// try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
/// try db.drop(table: "player")
/// try db.rename(table: "new_player", to: "player")
/// }
@@ -237,11 +237,11 @@ public struct DatabaseMigrator {
}
private func setupMigrations(_ db: Database) throws {
try db.execute("CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)")
}
private func appliedIdentifiers(_ db: Database) throws -> Set<String> {
return try Set(String.fetchAll(db, "SELECT identifier FROM grdb_migrations"))
return try Set(String.fetchAll(db, sql: "SELECT identifier FROM grdb_migrations"))
}
private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws {
+6 -6
View File
@@ -17,7 +17,7 @@ struct Migration {
self.migrate = migrate
}
@available(iOS 8.2, OSX 10.10, *)
@available(OSX 10.10, *)
// PRAGMA foreign_key_check was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16
// It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) {
@@ -28,7 +28,7 @@ struct Migration {
#endif
func run(_ db: Database) throws {
if try disabledForeignKeyChecks && (Bool.fetchOne(db, "PRAGMA foreign_keys") ?? false) {
if try disabledForeignKeyChecks && (Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false) {
try runWithDisabledForeignKeys(db)
} else {
try runWithoutDisabledForeignKeys(db)
@@ -50,7 +50,7 @@ struct Migration {
//
// > 1. If foreign key constraints are enabled, disable them using
// > PRAGMA foreign_keys=OFF.
try db.execute("PRAGMA foreign_keys = OFF")
try db.execute(sql: "PRAGMA foreign_keys = OFF")
// > 2. Start a transaction.
try db.inTransaction(.immediate) {
@@ -60,7 +60,7 @@ struct Migration {
// > 10. If foreign key constraints were originally enabled then run PRAGMA
// > foreign_key_check to verify that the schema change did not break any foreign key
// > constraints.
if try Row.fetchOne(db, "PRAGMA foreign_key_check") != nil {
if try Row.fetchOne(db, sql: "PRAGMA foreign_key_check") != nil {
// https://www.sqlite.org/pragma.html#pragma_foreign_key_check
//
// PRAGMA foreign_key_check does not return an error,
@@ -76,10 +76,10 @@ struct Migration {
}
// > 12. If foreign keys constraints were originally enabled, reenable them now.
try db.execute("PRAGMA foreign_keys = ON")
try db.execute(sql: "PRAGMA foreign_keys = ON")
}
private func insertAppliedIdentifier(_ db: Database) throws {
try db.execute("INSERT INTO grdb_migrations (identifier) VALUES (?)", arguments: [identifier])
try db.execute(sql: "INSERT INTO grdb_migrations (identifier) VALUES (?)", arguments: [identifier])
}
}
@@ -1,408 +0,0 @@
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The base protocol for all associations that define a connection between two
/// record types.
public protocol Association: DerivableRequest {
// OriginRowDecoder and RowDecoder provide type safety:
//
// Book.including(required: Book.author) // compiles
// Fruit.including(required: Book.author) // does not compile
/// The record type at the origin of the association.
///
/// In the `belongsTo` association below, it is Book:
///
/// struct Book: TableRecord {
/// // BelongsToAssociation<Book, Author>
/// static let author = belongsTo(Author.self)
/// }
associatedtype OriginRowDecoder
/// The associated record type.
///
/// In the `belongsTo` association below, it is Author:
///
/// struct Book: TableRecord {
/// // BelongsToAssociation<Book, Author>
/// static let author = belongsTo(Author.self)
/// }
associatedtype RowDecoder
// Association is a protocol, not a struct.
// This is because we want associations to be richly typed.
// Yet, we don't want to pollute user code with implementation details of
// associations. So let's hide all this stuff behind the _impl property:
/// :nodoc:
associatedtype Impl: AssociationImpl
/// :nodoc:
var _impl: Impl { get }
/// :nodoc:
init(_impl: Impl)
}
extension Association {
private func mapImpl(_ transform: (Impl) throws -> Impl) rethrows -> Self {
return try Self.init(_impl: transform(_impl))
}
private func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self {
return mapImpl { $0.mapRelation(transform) }
}
}
extension Association {
/// The association key defines how rows fetched from this association
/// should be consumed.
///
/// For example:
///
/// struct Player: TableRecord {
/// // The default key of this association is the name of the
/// // database table for teams, let's say "team":
/// static let team = belongsTo(Team.self)
/// }
/// print(Player.team.key) // Prints "team"
///
/// // Consume rows:
/// let request = Player.including(required: Player.team)
/// for row in Row.fetchAll(db, request) {
/// let team: Team = row["team"] // the association key
/// }
///
/// The key can be redefined with the `forKey` method:
///
/// let request = Player.including(required: Player.team.forKey("custom"))
/// for row in Row.fetchAll(db, request) {
/// let team: Team = row["custom"]
/// }
var key: String {
return _impl.key
}
/// Creates an association which selects *selection*.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.color
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// let association = Player.team.select([Column("color")])
/// var request = Player.including(required: association)
///
/// Any previous selection is replaced:
///
/// // SELECT player.*, team.color
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// let association = Player.team
/// .select([Column("id")])
/// .select([Column("color")])
/// var request = Player.including(required: association)
public func select(_ selection: [SQLSelectable]) -> Self {
return mapRelation { $0.select(selection) }
}
/// Creates an association with the provided *predicate promise* added to
/// the eventual set of already applied predicates.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // FROM player
/// // JOIN team ON team.id = player.teamId AND 1
/// let association = Player.team.filter { db in true }
/// var request = Player.including(required: association)
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
return mapRelation { $0.filter(predicate) }
}
/// Creates an association with the provided *orderings promise*.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// // ORDER BY team.name
/// let association = Player.team.order { _ in [Column("name")] }
/// var request = Player.including(required: association)
///
/// Any previous ordering is replaced:
///
/// // SELECT player.*, team.*
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// // ORDER BY team.name
/// let association = Player.team
/// .order{ _ in [Column("color")] }
/// .reversed()
/// .order{ _ in [Column("name")] }
/// var request = Player.including(required: association)
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
return mapRelation { $0.order(orderings) }
}
/// Creates an association that reverses applied orderings.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// // ORDER BY team.name DESC
/// let association = Player.team.order(Column("name")).reversed()
/// var request = Player.including(required: association)
///
/// If no ordering was applied, the returned association is identical.
///
/// // SELECT player.*, team.*
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// let association = Player.team.reversed()
/// var request = Player.including(required: association)
public func reversed() -> Self {
return mapRelation { $0.reversed() }
}
/// Creates an association with the given key.
///
/// This new key impacts how rows fetched from the resulting association
/// should be consumed:
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // Consume rows:
/// let request = Player.including(required: Player.team.forKey("custom"))
/// for row in Row.fetchAll(db, request) {
/// let team: Team = row["custom"]
/// }
public func forKey(_ key: String) -> Self {
return mapImpl { $0.forKey(key) }
}
/// Creates an association with the given key.
///
/// This new key helps Decodable records decode rows fetched from the
/// resulting association:
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// struct PlayerInfo: FetchableRecord, Decodable {
/// let player: Player
/// let team: Team
///
/// static func all() -> QueryInterfaceRequest<PlayerInfo> {
/// return Player
/// .including(required: Player.team.forKey(CodingKeys.team))
/// .asRequest(of: PlayerInfo.self)
/// }
/// }
///
/// let playerInfos = PlayerInfo.all().fetchAll(db)
/// print(playerInfos.first?.team)
public func forKey(_ codingKey: CodingKey) -> Self {
return forKey(codingKey.stringValue)
}
/// Creates an association that allows you to define expressions that target
/// a specific database table.
///
/// In the example below, the "team.color = 'red'" condition in the where
/// clause could be not achieved without table aliases.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // JOIN team ON ...
/// // WHERE team.color = 'red'
/// let teamAlias = TableAlias()
/// let request = Player
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(teamAlias[Column("color")] == "red")
///
/// When you give a name to a table alias, you can reliably inject sql
/// snippets in your requests:
///
/// // SELECT player.*, custom.*
/// // JOIN team custom ON ...
/// // WHERE custom.color = 'red'
/// let teamAlias = TableAlias(name: "custom")
/// let request = Player
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(sql: "custom.color = ?", arguments: ["red"])
public func aliased(_ alias: TableAlias) -> Self {
return mapRelation { $0.qualified(with: alias) }
}
}
extension Association {
/// Creates an association that includes another one. The columns of the
/// associated record are selected. The returned association does not
/// require that the associated database table contains a matching row.
public func including<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return mapRelation { association._impl.joinedRelation($0, joinOperator: .optional) }
}
/// Creates an association that includes another one. The columns of the
/// associated record are selected. The returned association requires
/// that the associated database table contains a matching row.
public func including<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return mapRelation { association._impl.joinedRelation($0, joinOperator: .required) }
}
/// Creates an association that joins another one. The columns of the
/// associated record are not selected. The returned association does not
/// require that the associated database table contains a matching row.
public func joining<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return mapRelation { association.select([])._impl.joinedRelation($0, joinOperator: .optional) }
}
/// Creates an association that joins another one. The columns of the
/// associated record are not selected. The returned association requires
/// that the associated database table contains a matching row.
public func joining<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return mapRelation { association.select([])._impl.joinedRelation($0, joinOperator: .required) }
}
}
extension Association where OriginRowDecoder: MutablePersistableRecord {
/// Support for MutablePersistableRecord.request(for:).
///
/// For example:
///
/// struct Team: {
/// static let players = hasMany(Player.self)
/// var players: QueryInterfaceRequest<Player> {
/// return request(for: Team.players)
/// }
/// }
///
/// let team: Team = ...
/// let players = try team.players.fetchAll(db) // [Player]
func request(from record: OriginRowDecoder) -> QueryInterfaceRequest<RowDecoder> {
// Goal: turn `JOIN association ON association.recordId = record.id`
// into a regular request `SELECT * FROM association WHERE association.recordId = 123`
// We need table aliases to build the joining condition
let associationAlias = TableAlias()
let recordAlias = TableAlias()
// Turn the association query into a query interface request:
// JOIN association -> SELECT FROM association
return QueryInterfaceRequest(query: SQLSelectQuery(relation: _impl.relation))
// Turn the JOIN condition into a regular WHERE condition
.filter { db in
// Build a join condition: `association.recordId = record.id`
// We still need to replace `record.id` with the actual record id.
let joinExpression = try self._impl.joinCondition.sqlExpression(db, leftAlias: recordAlias, rightAlias: associationAlias)
// Serialize record: ["id": 123, ...]
// We do it as late as possible, when request is about to be
// executed, in order to support long-lived reference types.
let container = PersistenceContainer(record)
// Replace `record.id` with 123
return joinExpression.resolvedExpression(inContext: [recordAlias: container])
}
// We just added a condition qualified with associationAlias. Don't
// risk introducing conflicting aliases that would prevent the user
// from setting a custom alias name: force the same alias for the
// whole request.
.aliased(associationAlias)
}
}
// MARK: - AssociationImpl
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The protocol for implementation details of associations.
///
/// :nodoc:
public /* TODO: internal */ protocol AssociationImpl {
/// The association key
var key: String { get }
/// Creates an association with the given key.
func forKey(_ key: String) -> Self
/// Returns an association whose relation is transformed by the
/// given closure.
///
/// This method provides fundamental support for association derivation:
///
/// // Invokes Book.author.mapRelation { $0.filter(...) }
/// Book.author.filter(...)
func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self
/// Returns a relation joined with self.
///
/// This method provides fundamental support for joining methods.
func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation
// TODO: remove relation & joinCondition properties.
//
// They assume that an association is implemented as a direct join to an
// associated table. This is limiting: has-one-through and has-many-through
// associations can't be implemented in such context.
//
// Their impact is limited yet. Those propertise are currently only used by
// Association.request(from:). When this method gets a new implementation
// that does not need a direct join to an associated table, we'll be able to
// remove those properties.
var relation: SQLRelation { get }
var joinCondition: JoinCondition { get }
}
// MARK: -
/// The AssociationImpl shared by BelongsTo, HasOne, and HasMany, which is
/// implemented as a simple join.
///
/// :nodoc:
public /* TODO: internal */ struct JoinAssociationImpl: AssociationImpl {
public var key: String
public /* TODO: internal */ let joinCondition: JoinCondition
public /* TODO: internal */ var relation: SQLRelation
public func forKey(_ key: String) -> JoinAssociationImpl {
var assoc = self
assoc.key = key
return assoc
}
public func mapRelation(_ transform: (SQLRelation) -> SQLRelation) -> JoinAssociationImpl {
var assoc = self
assoc.relation = transform(relation)
return assoc
}
public func joinedRelation(_ relation: SQLRelation, joinOperator: JoinOperator) -> SQLRelation {
let join = SQLJoin(
joinOperator: joinOperator,
joinCondition: joinCondition,
relation: self.relation)
return relation.appendingJoin(join, forKey: key)
}
}
@@ -1,161 +0,0 @@
/// 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 association this way:
///
/// struct Author: TableRecord { ... }
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
/// ...
/// }
///
/// A BelongsTo associations should be supported by an SQLite foreign key.
///
/// Foreign keys are the recommended way to declare relationships between
/// database tables because not only will SQLite guarantee the integrity of your
/// data, but GRDB will be able to use those foreign keys to automatically
/// configure your association.
///
/// You define the foreign key when you create database tables. For example:
///
/// try db.create(table: "author") { t in
/// t.autoIncrementedPrimaryKey("id") // (1)
/// t.column("name", .text)
/// }
/// try db.create(table: "book") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("authorId", .integer) // (2)
/// .notNull() // (3)
/// .indexed() // (4)
/// .references("author", onDelete: .cascade) // (5)
/// t.column("title", .text)
/// }
///
/// 1. The author table has a primary key.
/// 2. The book.authorId column is used to link a book to the author it
/// belongs to.
/// 3. Make the book.authorId column not null if you want SQLite to guarantee
/// that all books have an author.
/// 4. Create an index on the book.authorId column in order to ease the
/// selection of an author's books.
/// 5. Create a foreign key from book.authorId column to authors.id, so that
/// SQLite guarantees that no book refers to a missing author. The
/// `onDelete: .cascade` option has SQLite automatically delete all of an
/// author's books when that author is deleted.
/// See https://sqlite.org/foreignkeys.html#fk_actions for more information.
///
/// The example above uses auto-incremented primary keys. But generally
/// speaking, all primary keys are supported.
///
/// If the database schema does not define foreign keys between tables, you can
/// still use BelongsTo associations. But your help is needed to define the
/// missing foreign key:
///
/// struct Book: FetchableRecord, TableRecord {
/// static let author = belongsTo(Author.self, using: ForeignKey(...))
/// }
///
/// See ForeignKey for more information.
public struct BelongsToAssociation<Origin, Destination>: Association {
/// :nodoc:
public typealias OriginRowDecoder = Origin
/// :nodoc:
public typealias RowDecoder = Destination
/// :nodoc:
public var _impl: JoinAssociationImpl
/// :nodoc:
public init(_impl: JoinAssociationImpl) {
self._impl = _impl
}
}
// Allow BelongsToAssociation(...).filter(key: ...)
extension BelongsToAssociation: TableRequest where Destination: TableRecord {
/// :nodoc:
public var databaseTableName: String { return Destination.databaseTableName }
}
extension TableRecord {
/// Creates a "Belongs To" association between Self and the
/// destination type.
///
/// struct Author: TableRecord { ... }
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
/// }
///
/// The association will let you define requests that load both the source
/// and the destination type:
///
/// // A request for all books with their authors:
/// let request = Book.including(optional: Book.author)
///
/// To consume those requests, define a type that adopts both the
/// FetchableRecord and Decodable protocols:
///
/// struct BookInfo: FetchableRecord, Decodable {
/// var book: Book
/// var author: Author?
/// }
///
/// let bookInfos = try dbQueue.read { db in
/// return try BookInfo.fetchAll(db, request)
/// }
/// for bookInfo in bookInfos {
/// print("\(bookInfo.book.title) by \(bookInfo.author.name)")
/// }
///
/// It is recommended that you define, alongside the association, a property
/// with the same name:
///
/// struct Book: TableRecord {
/// static let author = belongsTo(Author.self)
/// var author: QueryInterfaceRequest<Author> {
/// return request(for: Book.author)
/// }
/// }
///
/// This property will let you navigate from the source type to the
/// destination type:
///
/// try dbQueue.read { db in
/// let book: Book = ...
/// let author = try book.author.fetchOne(db) // Author?
/// }
///
/// - parameters:
/// - destination: The record type at the other side of the association.
/// - key: An eventual decoding key for the association. By default, it
/// is `destination.databaseTableName`.
/// - foreignKey: An eventual foreign key. You need to provide an
/// explicit foreign key when GRDB can't infer one from the database
/// schema. This happens when the schema does not define any foreign
/// key to the destination table, or when the schema defines several
/// foreign keys to the destination table.
public static func belongsTo<Destination>(
_ destination: Destination.Type,
key: String? = nil,
using foreignKey: ForeignKey? = nil)
-> BelongsToAssociation<Self, Destination>
where Destination: TableRecord
{
let foreignKeyRequest = ForeignKeyRequest(
originTable: databaseTableName,
destinationTable: Destination.databaseTableName,
foreignKey: foreignKey)
let joinCondition = JoinCondition(
foreignKeyRequest: foreignKeyRequest,
originIsLeft: true)
return BelongsToAssociation(_impl: JoinAssociationImpl(
key: key ?? Destination.databaseTableName,
joinCondition: joinCondition,
relation: Destination.all().relation))
}
}
@@ -1,108 +0,0 @@
/// A ForeignKey helps building associations when GRDB can't infer a foreign
/// key from the database schema.
///
/// Sometimes the database schema does not define any foreign key between two
/// tables. And sometimes, there are several foreign keys from a table
/// to another:
///
/// | Table book | | Table person |
/// | ------------ | | ------------ |
/// | id | +-->• id |
/// | authorId •---+ | name |
/// | translatorId •---+
/// | title |
///
/// When this happens, associations can't be automatically inferred from the
/// database schema. GRDB will complain with a fatal error such as "Ambiguous
/// foreign key from book to person", or "Could not infer foreign key from book
/// to person".
///
/// Your help is needed. You have to instruct GRDB which foreign key to use:
///
/// struct Book: TableRecord {
/// // Define foreign keys
/// static let authorForeignKey = ForeignKey(["authorId"]))
/// static let translatorForeignKey = ForeignKey(["translatorId"]))
///
/// // Use foreign keys to define associations:
/// static let author = belongsTo(Person.self, using: authorForeignKey)
/// static let translator = belongsTo(Person.self, using: translatorForeignKey)
/// }
///
/// Foreign keys are always defined from the table that contains the columns at
/// the origin of the foreign key. Person's symmetric HasMany associations reuse
/// Book's foreign keys:
///
/// struct Person: TableRecord {
/// static let writtenBooks = hasMany(Book.self, using: Book.authorForeignKey)
/// static let translatedBooks = hasMany(Book.self, using: Book.translatorForeignKey)
/// }
///
/// Foreign keys can also be defined from query interface columns:
///
/// struct Book: TableRecord {
/// enum Columns: String, ColumnExpression {
/// case id, title, authorId, translatorId
/// }
///
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
/// }
///
/// When the destination table of a foreign key does not define any primary key,
/// you need to provide the full definition of a foreign key:
///
/// struct Book: TableRecord {
/// static let authorForeignKey = ForeignKey(["authorId"], to: ["id"]))
/// static let author = belongsTo(Person.self, using: authorForeignKey)
/// }
public struct ForeignKey {
var originColumns: [String]
var destinationColumns: [String]?
/// Creates a ForeignKey intended to define a record association.
///
/// struct Book: TableRecord {
/// // Define foreign keys
/// static let authorForeignKey = ForeignKey(["authorId"]))
/// static let translatorForeignKey = ForeignKey(["translatorId"]))
///
/// // Use foreign keys to define associations:
/// static let author = belongsTo(Person.self, using: authorForeignKey)
/// static let translator = belongsTo(Person.self, using: translatorForeignKey)
/// }
///
/// - parameter originColumns: The columns at the origin of the foreign key.
/// - parameter destinationColumns: The columns at the destination of the
/// foreign key. When nil (the default), GRDB automatically uses the
/// primary key.
public init(_ originColumns: [String], to destinationColumns: [String]? = nil) {
self.originColumns = originColumns
self.destinationColumns = destinationColumns
}
/// Creates a ForeignKey intended to define a record association.
///
/// struct Book: TableRecord {
/// // Define columns
/// enum Columns: String, ColumnExpression {
/// case id, title, authorId, translatorId
/// }
///
/// // Define foreign keys
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
///
/// // Use foreign keys to define associations:
/// static let author = belongsTo(Person.self, using: authorForeignKey)
/// static let translator = belongsTo(Person.self, using: translatorForeignKey)
/// }
///
/// - parameter originColumns: The columns at the origin of the foreign key.
/// - parameter destinationColumns: The columns at the destination of the
/// foreign key. When nil (the default), GRDB automatically uses the
/// primary key.
public init(_ originColumns: [ColumnExpression], to destinationColumns: [ColumnExpression]? = nil) {
self.init(originColumns.map { $0.name }, to: destinationColumns?.map { $0.name })
}
}
@@ -1,250 +0,0 @@
/// 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.
///
/// For example, if your application includes authors and books, and each author
/// is assigned zero or more books, you'd declare the association this way:
///
/// struct Book: TableRecord { ... }
/// struct Author: TableRecord {
/// static let books = hasMany(Book.self)
/// ...
/// }
///
/// HasMany associations should be supported by an SQLite foreign key.
///
/// Foreign keys are the recommended way to declare relationships between
/// database tables because not only will SQLite guarantee the integrity of your
/// data, but GRDB will be able to use those foreign keys to automatically
/// configure your association.
///
/// You define the foreign key when you create database tables. For example:
///
/// try db.create(table: "author") { t in
/// t.autoIncrementedPrimaryKey("id") // (1)
/// t.column("name", .text)
/// }
/// try db.create(table: "book") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("authorId", .integer) // (2)
/// .notNull() // (3)
/// .indexed() // (4)
/// .references("author", onDelete: .cascade) // (5)
/// t.column("title", .text)
/// }
///
/// 1. The author table has a primary key.
/// 2. The book.authorId column is used to link a book to the author it
/// belongs to.
/// 3. Make the book.authorId column not null if you want SQLite to guarantee
/// that all books have an author.
/// 4. Create an index on the book.authorId column in order to ease the
/// selection of an author's books.
/// 5. Create a foreign key from book.authorId column to authors.id, so that
/// SQLite guarantees that no book refers to a missing author. The
/// `onDelete: .cascade` option has SQLite automatically delete all of an
/// author's books when that author is deleted.
/// See https://sqlite.org/foreignkeys.html#fk_actions for more information.
///
/// The example above uses auto-incremented primary keys. But generally
/// speaking, all primary keys are supported.
///
/// If the database schema does not define foreign keys between tables, you can
/// still use HasMany associations. But your help is needed to define the
/// missing foreign key:
///
/// struct Author: TableRecord {
/// static let books = hasMany(Book.self, using: ForeignKey(...))
/// }
///
/// See ForeignKey for more information.
public struct HasManyAssociation<Origin, Destination>: Association {
/// :nodoc:
public typealias OriginRowDecoder = Origin
/// :nodoc:
public typealias RowDecoder = Destination
/// :nodoc:
public var _impl: JoinAssociationImpl
/// :nodoc:
public init(_impl: JoinAssociationImpl) {
self._impl = _impl
}
}
// Allow HasManyAssociation(...).filter(key: ...)
extension HasManyAssociation: TableRequest where Destination: TableRecord {
/// :nodoc:
public var databaseTableName: String { return Destination.databaseTableName }
}
extension HasManyAssociation where Origin: TableRecord, Destination: TableRecord {
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<Origin> {
return AssociationAggregate { request in
let tableAlias = TableAlias()
let request = request
.joining(optional: self.aliased(tableAlias))
.groupByPrimaryKey()
let expression = tableAlias[expression]
return (request: request, expression: expression)
}
}
/// The number of associated records.
///
/// For example:
///
/// Team.annotated(with: Team.players.count())
public var count: AssociationAggregate<Origin> {
return makeAggregate(SQLExpressionCountDistinct(Column.rowID)).aliased("\(key)Count")
}
/// An aggregate that is true if there exists no associated records.
///
/// For example:
///
/// Team.having(Team.players.isEmpty())
/// Team.having(!Team.players.isEmpty())
/// Team.having(Team.players.isEmpty() == false)
public var isEmpty: AssociationAggregate<Origin> {
return makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID)))
}
/// The average value of the given expression in associated records.
///
/// For example:
///
/// Team.annotated(with: Team.players.average(Column("score")))
public func average(_ expression: SQLExpressible) -> AssociationAggregate<Origin> {
let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression))
if let column = expression as? ColumnExpression {
return aggregate.aliased("average\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// The maximum value of the given expression in associated records.
///
/// For example:
///
/// Team.annotated(with: Team.players.max(Column("score")))
public func max(_ expression: SQLExpressible) -> AssociationAggregate<Origin> {
let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression))
if let column = expression as? ColumnExpression {
return aggregate.aliased("max\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// The minimum value of the given expression in associated records.
///
/// For example:
///
/// Team.annotated(with: Team.players.min(Column("score")))
public func min(_ expression: SQLExpressible) -> AssociationAggregate<Origin> {
let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression))
if let column = expression as? ColumnExpression {
return aggregate.aliased("min\(key.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// The sum of the given expression in associated records.
///
/// For example:
///
/// Team.annotated(with: Team.players.min(Column("score")))
public func sum(_ expression: SQLExpressible) -> AssociationAggregate<Origin> {
let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression))
if let column = expression as? ColumnExpression {
return aggregate.aliased("\(key)\(column.name.uppercasingFirstCharacter)Sum")
} else {
return aggregate
}
}
}
extension TableRecord {
/// Creates a "Has many" association between Self and the
/// destination type.
///
/// struct Book: TableRecord { ... }
/// struct Author: TableRecord {
/// static let books = hasMany(Book.self)
/// }
///
/// The association will let you define requests that load both the source
/// and the destination type:
///
/// // A request for all (author, book) pairs:
/// let request = Author.including(required: Author.books)
///
/// To consume those requests, define a type that adopts both the
/// FetchableRecord and Decodable protocols:
///
/// struct Authorship: FetchableRecord, Decodable {
/// var author: Author
/// var book: Book
/// }
///
/// let authorships = try dbQueue.read { db in
/// return try Authorship.fetchAll(db, request)
/// }
/// for authorship in authorships {
/// print("\(authorship.author.name) wrote \(authorship.book.title)")
/// }
///
/// It is recommended that you define, alongside the association, a property
/// with the same name:
///
/// struct Author: TableRecord {
/// static let books = hasMany(Book.self)
/// var books: QueryInterfaceRequest<Book> {
/// return request(for: Author.books)
/// }
/// }
///
/// This property will let you navigate from the source type to the
/// destination type:
///
/// try dbQueue.read { db in
/// let author: Author = ...
/// let books = try author.books.fetchAll(db) // [Book]
/// }
///
/// - parameters:
/// - destination: The record type at the other side of the association.
/// - key: An eventual decoding key for the association. By default, it
/// is `destination.databaseTableName`.
/// - foreignKey: An eventual foreign key. You need to provide an
/// explicit foreign key when GRDB can't infer one from the database
/// schema. This happens when the schema does not define any foreign
/// key from the destination table, or when the schema defines several
/// foreign keys from the destination table.
public static func hasMany<Destination>(
_ destination: Destination.Type,
key: String? = nil,
using foreignKey: ForeignKey? = nil)
-> HasManyAssociation<Self, Destination>
where Destination: TableRecord
{
let foreignKeyRequest = ForeignKeyRequest(
originTable: Destination.databaseTableName,
destinationTable: databaseTableName,
foreignKey: foreignKey)
let joinCondition = JoinCondition(
foreignKeyRequest: foreignKeyRequest,
originIsLeft: false)
return HasManyAssociation(_impl: JoinAssociationImpl(
key: key ?? Destination.databaseTableName,
joinCondition: joinCondition,
relation: Destination.all().relation))
}
}
@@ -1,163 +0,0 @@
/// The HasOne association indicates a one-to-one connection between two
/// record types, such as each instance of the declaring record "has one"
/// instances of the other record.
///
/// For example, if your application has one database table for countries, and
/// another for their demographic profiles, you'd declare the association
/// this way:
///
/// struct Demographics: TableRecord { ... }
/// struct Country: TableRecord {
/// static let demographics = hasOne(Demographics.self)
/// ...
/// }
///
/// HasOne associations should be supported by an SQLite foreign key.
///
/// Foreign keys are the recommended way to declare relationships between
/// database tables because not only will SQLite guarantee the integrity of your
/// data, but GRDB will be able to use those foreign keys to automatically
/// configure your association.
///
/// You define the foreign key when you create database tables. For example:
///
/// try db.create(table: "country") { t in
/// t.column("code", .text).primaryKey() // (1)
/// t.column("name", .text)
/// }
/// try db.create(table: "demographics") { t in
/// t.autoIncrementedPrimaryKey("id")
/// t.column("countryCode", .text) // (2)
/// .notNull() // (3)
/// .unique() // (4)
/// .references("country", onDelete: .cascade) // (5)
/// t.column("population", .integer)
/// t.column("density", .double)
/// }
///
/// 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.
/// 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 unicity of any country's profile.
/// 5. Create a foreign key 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 https://sqlite.org/foreignkeys.html#fk_actions for more information.
///
/// The example above uses a string primary for the country table. But generally
/// speaking, all primary keys are supported.
///
/// If the database schema does not follow this convention, and does not define
/// foreign keys between tables, you can still use HasOne associations. But
/// your help is needed to define the missing foreign key:
///
/// struct Country: FetchableRecord, TableRecord {
/// static let demographics = hasOne(Demographics.self, using: ForeignKey(...))
/// }
///
/// See ForeignKey for more information.
public struct HasOneAssociation<Origin, Destination>: Association {
/// :nodoc:
public typealias OriginRowDecoder = Origin
/// :nodoc:
public typealias RowDecoder = Destination
/// :nodoc:
public var _impl: JoinAssociationImpl
/// :nodoc:
public init(_impl: JoinAssociationImpl) {
self._impl = _impl
}
}
// Allow HasOneAssociation(...).filter(key: ...)
extension HasOneAssociation: TableRequest where Destination: TableRecord {
/// :nodoc:
public var databaseTableName: String { return Destination.databaseTableName }
}
extension TableRecord {
/// Creates a "Has one" association between Self and the
/// destination type.
///
/// struct Demographics: TableRecord { ... }
/// struct Country: TableRecord {
/// static let demographics = hasOne(Demographics.self)
/// }
///
/// The association will let you define requests that load both the source
/// and the destination type:
///
/// // A request for all countries with their demographic profile:
/// let request = Country.including(optional: Country.demographics)
///
/// To consume those requests, define a type that adopts both the
/// FetchableRecord and Decodable protocols:
///
/// struct CountryInfo: FetchableRecord, Decodable {
/// var country: Country
/// var demographics: Demographics?
/// }
///
/// let countryInfos = try dbQueue.read { db in
/// return try CountryInfo.fetchAll(db, request)
/// }
/// for countryInfo in countryInfos {
/// print("\(countryInfo.country.name) has \(countryInfo.demographics.population) citizens")
/// }
///
/// It is recommended that you define, alongside the association, a property
/// with the same name:
///
/// struct Country: TableRecord {
/// static let demographics = hasOne(Demographics.self)
/// var demographics: QueryInterfaceRequest<Demographics> {
/// return request(for: Country.demographics)
/// }
/// }
///
/// This property will let you navigate from the source type to the
/// destination type:
///
/// try dbQueue.read { db in
/// let country: Country = ...
/// let demographics = try country.demographics.fetchOne(db) // Demographics?
/// }
///
/// - parameters:
/// - destination: The record type at the other side of the association.
/// - key: An eventual decoding key for the association. By default, it
/// is `destination.databaseTableName`.
/// - foreignKey: An eventual foreign key. You need to provide an
/// explicit foreign key when GRDB can't infer one from the database
/// schema. This happens when the schema does not define any foreign
/// key from the destination table, or when the schema defines several
/// foreign keys from the destination table.
public static func hasOne<Destination>(
_ destination: Destination.Type,
key: String? = nil,
using foreignKey: ForeignKey? = nil)
-> HasOneAssociation<Self, Destination>
where Destination: TableRecord
{
let foreignKeyRequest = ForeignKeyRequest(
originTable: Destination.databaseTableName,
destinationTable: databaseTableName,
foreignKey: foreignKey)
let joinCondition = JoinCondition(
foreignKeyRequest: foreignKeyRequest,
originIsLeft: false)
return HasOneAssociation(_impl: JoinAssociationImpl(
key: key ?? Destination.databaseTableName,
joinCondition: joinCondition,
relation: Destination.all().relation))
}
}
@@ -0,0 +1,120 @@
extension QueryInterfaceRequest where RowDecoder: FetchableRecord {
/// A cursor over fetched records.
///
/// let request: QueryInterfaceRequest<Player> = ...
/// let players = try request.fetchCursor(db) // Cursor of Player
/// while let player = try players.next() { // Player
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameter db: A database connection.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder> {
return try RowDecoder.fetchCursor(db, self)
}
/// An array of fetched records.
///
/// let request: QueryInterfaceRequest<Player> = ...
/// let players = try request.fetchAll(db) // [Player]
///
/// - parameter db: A database connection.
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
return try RowDecoder.fetchAll(db, self)
}
/// The first fetched record.
///
/// let request: QueryInterfaceRequest<Player> = ...
/// let player = try request.fetchOne(db) // Player?
///
/// - parameter db: A database connection.
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public func fetchOne(_ db: Database) throws -> RowDecoder? {
return try RowDecoder.fetchOne(db, self)
}
}
extension FetchableRecord {
// MARK: Fetching From QueryInterfaceRequest
/// Returns a cursor over records fetched from a fetch request.
///
/// let request = try Player.all()
/// let players = try Player.fetchCursor(db, request) // Cursor of Player
/// while let player = try players.next() { // Player
/// ...
/// }
///
/// If the database is modified during the cursor iteration, the remaining
/// elements are undefined.
///
/// The cursor must be iterated in a protected dispath queue.
///
/// - parameters:
/// - db: A database connection.
/// - sql: a FetchRequest.
/// - returns: A cursor over fetched records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) throws -> RecordCursor<Self> {
precondition(request.prefetchedAssociations.isEmpty, "Not implemented: fetchCursor with prefetched associations")
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
return try fetchCursor(statement, adapter: adapter)
}
/// Returns an array of records fetched from a query interface request.
///
/// let request = try Player.all()
/// let players = try Player.fetchAll(db, request) // [Player]
///
/// - parameters:
/// - db: A database connection.
/// - sql: a FetchRequest.
/// - returns: An array of records.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) throws -> [Self] {
let (statement, adapter) = try request.prepare(db, forSingleResult: false)
let associations = request.prefetchedAssociations
if associations.isEmpty {
return try fetchAll(statement, adapter: adapter)
} else {
let rows = try Row.fetchAll(statement, adapter: adapter)
try Row.prefetch(db, associations: associations, in: rows)
return rows.map(Self.init(row:))
}
}
/// Returns a single record fetched from a query interface request.
///
/// let request = try Player.filter(key: 1)
/// let player = try Player.fetchOne(db, request) // Player?
///
/// - parameters:
/// - db: A database connection.
/// - sql: a FetchRequest.
/// - returns: An optional record.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne<T>(_ db: Database, _ request: QueryInterfaceRequest<T>) throws -> Self? {
let (statement, adapter) = try request.prepare(db, forSingleResult: true)
let associations = request.prefetchedAssociations
if associations.isEmpty {
return try fetchOne(statement, adapter: adapter)
} else {
guard let row = try Row.fetchOne(statement, adapter: adapter) else {
return nil
}
try Row.prefetch(db, associations: associations, in: [row])
return Self.init(row: row)
}
}
}
@@ -1,164 +0,0 @@
extension QueryInterfaceRequest where RowDecoder: TableRecord {
// MARK: - Associations
/// Creates a request that includes an association. The columns of the
/// associated record are selected. The returned association does not
/// require that the associated database table contains a matching row.
public func including<A: Association>(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder {
return mapQuery { $0.mapRelation { association._impl.joinedRelation($0, joinOperator: .optional) } }
}
/// Creates a request that includes an association. The columns of the
/// associated record are selected. The returned association requires
/// that the associated database table contains a matching row.
public func including<A: Association>(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder {
return mapQuery { $0.mapRelation { association._impl.joinedRelation($0, joinOperator: .required) } }
}
/// Creates a request that includes an association. The columns of the
/// associated record are not selected. The returned association does not
/// require that the associated database table contains a matching row.
public func joining<A: Association>(optional association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder {
return mapQuery { $0.mapRelation { association.select([])._impl.joinedRelation($0, joinOperator: .optional) } }
}
/// Creates a request that includes an association. The columns of the
/// associated record are not selected. The returned association requires
/// that the associated database table contains a matching row.
public func joining<A: Association>(required association: A) -> QueryInterfaceRequest where A.OriginRowDecoder == RowDecoder {
return mapQuery { $0.mapRelation { association.select([])._impl.joinedRelation($0, joinOperator: .required) } }
}
// MARK: - Association Aggregates
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
let (request, expression) = aggregate.prepare(self)
if let alias = aggregate.alias {
return request.annotated(with: [expression.aliased(alias)])
} else {
return request.annotated(with: [expression])
}
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: Player.books.count)
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> QueryInterfaceRequest {
return annotated(with: aggregates)
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: [Player.books.count])
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> QueryInterfaceRequest {
return aggregates.reduce(self) { request, aggregate in
request.annotated(with: aggregate)
}
}
/// Creates a request which appends the provided aggregate *predicate* to
/// the eventual set of already applied predicates.
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.rowid) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
let (request, expression) = predicate.prepare(self)
return request.having(expression)
}
}
extension MutablePersistableRecord {
/// Creates a request that fetches the associated record(s).
///
/// For example:
///
/// struct Team: {
/// static let players = hasMany(Player.self)
/// var players: QueryInterfaceRequest<Player> {
/// return request(for: Team.players)
/// }
/// }
///
/// let team: Team = ...
/// let players = try team.players.fetchAll(db) // [Player]
public func request<A: Association>(for association: A) -> QueryInterfaceRequest<A.RowDecoder> where A.OriginRowDecoder == Self {
return association.request(from: self)
}
}
extension TableRecord {
// MARK: - Associations
/// Creates a request that includes an association. The columns of the
/// associated record are selected. The returned association does not
/// require that the associated database table contains a matching row.
public static func including<A: Association>(optional association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
return all().including(optional: association)
}
/// Creates a request that includes an association. The columns of the
/// associated record are selected. The returned association requires
/// that the associated database table contains a matching row.
public static func including<A: Association>(required association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
return all().including(required: association)
}
/// Creates a request that includes an association. The columns of the
/// associated record are not selected. The returned association does not
/// require that the associated database table contains a matching row.
public static func joining<A: Association>(optional association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
return all().joining(optional: association)
}
/// Creates a request that includes an association. The columns of the
/// associated record are not selected. The returned association requires
/// that the associated database table contains a matching row.
public static func joining<A: Association>(required association: A) -> QueryInterfaceRequest<Self> where A.OriginRowDecoder == Self {
return all().joining(required: association)
}
// MARK: - Association Aggregates
/// Creates a request with *aggregates* appended to the selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.annotated(with: Player.books.count)
public static func annotated(with aggregates: AssociationAggregate<Self>...) -> QueryInterfaceRequest<Self> {
return all().annotated(with: aggregates)
}
/// Creates a request with *aggregates* appended to the selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.annotated(with: [Player.books.count])
public static func annotated(with aggregates: [AssociationAggregate<Self>]) -> QueryInterfaceRequest<Self> {
return all().annotated(with: aggregates)
}
/// Creates a request with the provided aggregate *predicate*.
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.rowid) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
///
/// The selection defaults to all columns. This default can be changed for
/// all requests by the `TableRecord.databaseSelection` property, or
/// for individual requests with the `TableRecord.select` method.
public static func having(_ predicate: AssociationAggregate<Self>) -> QueryInterfaceRequest<Self> {
return all().having(predicate)
}
}
@@ -0,0 +1,514 @@
import Foundation
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The base protocol for all associations that define a connection between two
/// record types.
public protocol Association: DerivableRequest {
// OriginRowDecoder and RowDecoder provide type safety:
//
// Book.including(required: Book.author) // compiles
// Fruit.including(required: Book.author) // does not compile
/// The record type at the origin of the association.
///
/// In the `belongsTo` association below, it is Book:
///
/// struct Book: TableRecord {
/// // BelongsToAssociation<Book, Author>
/// static let author = belongsTo(Author.self)
/// }
associatedtype OriginRowDecoder
/// The associated record type.
///
/// In the `belongsTo` association below, it is Author:
///
/// struct Book: TableRecord {
/// // BelongsToAssociation<Book, Author>
/// static let author = belongsTo(Author.self)
/// }
associatedtype RowDecoder
/// :nodoc:
var sqlAssociation: SQLAssociation { get }
/// Creates an association with the given key.
///
/// This new key impacts how rows fetched from the resulting association
/// should be consumed:
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // Consume rows:
/// let request = Player.including(required: Player.team.forKey("custom"))
/// for row in Row.fetchAll(db, request) {
/// let team: Team = row["custom"]
/// }
func forKey(_ key: String) -> Self
/// :nodoc:
init(sqlAssociation: SQLAssociation)
}
extension Association {
private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self {
return Self.init(sqlAssociation: sqlAssociation.mapDestinationRelation(transform))
}
}
extension Association {
/// The association key defines how rows fetched from this association
/// should be consumed.
///
/// For example:
///
/// struct Player: TableRecord {
/// // The default key of this association is the name of the
/// // database table for teams, let's say "team":
/// static let team = belongsTo(Team.self)
/// }
/// print(Player.team.key) // Prints "team"
///
/// // Consume rows:
/// let request = Player.including(required: Player.team)
/// for row in Row.fetchAll(db, request) {
/// let team: Team = row["team"] // the association key
/// }
///
/// The key can be redefined with the `forKey` method:
///
/// let request = Player.including(required: Player.team.forKey("custom"))
/// for row in Row.fetchAll(db, request) {
/// let team: Team = row["custom"]
/// }
var key: SQLAssociationKey {
return sqlAssociation.destination.key
}
/// Creates an association which selects *selection*.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.color
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// let association = Player.team.select([Column("color")])
/// var request = Player.including(required: association)
///
/// Any previous selection is replaced:
///
/// // SELECT player.*, team.color
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// let association = Player.team
/// .select([Column("id")])
/// .select([Column("color")])
/// var request = Player.including(required: association)
public func select(_ selection: [SQLSelectable]) -> Self {
return mapDestinationRelation { $0.select(selection) }
}
/// Creates an association which appends *selection*.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.color, team.name
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// let association = Player.team
/// .select([Column("color")])
/// .annotated(with: [Column("name")])
/// var request = Player.including(required: association)
public func annotated(with selection: [SQLSelectable]) -> Self {
return mapDestinationRelation { $0.annotated(with: selection) }
}
/// Creates an association with the provided *predicate promise* added to
/// the eventual set of already applied predicates.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // FROM player
/// // JOIN team ON team.id = player.teamId AND 1
/// let association = Player.team.filter { db in true }
/// var request = Player.including(required: association)
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
return mapDestinationRelation { $0.filter(predicate) }
}
/// Creates an association with the provided *orderings promise*.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// // ORDER BY team.name
/// let association = Player.team.order { _ in [Column("name")] }
/// var request = Player.including(required: association)
///
/// Any previous ordering is replaced:
///
/// // SELECT player.*, team.*
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// // ORDER BY team.name
/// let association = Player.team
/// .order{ _ in [Column("color")] }
/// .reversed()
/// .order{ _ in [Column("name")] }
/// var request = Player.including(required: association)
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
return mapDestinationRelation { $0.order(orderings) }
}
/// Creates an association that reverses applied orderings.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// // ORDER BY team.name DESC
/// let association = Player.team.order(Column("name")).reversed()
/// var request = Player.including(required: association)
///
/// If no ordering was applied, the returned association is identical.
///
/// // SELECT player.*, team.*
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// let association = Player.team.reversed()
/// var request = Player.including(required: association)
public func reversed() -> Self {
return mapDestinationRelation { $0.reversed() }
}
/// Creates an association without any ordering.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // FROM player
/// // JOIN team ON team.id = player.teamId
/// let association = Player.team.order(Column("name")).unordered()
/// var request = Player.including(required: association)
public func unordered() -> Self {
return mapDestinationRelation { $0.unordered() }
}
/// Creates an association with the given key.
///
/// This new key helps Decodable records decode rows fetched from the
/// resulting association:
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// struct PlayerInfo: FetchableRecord, Decodable {
/// let player: Player
/// let team: Team
///
/// static func all() -> QueryInterfaceRequest<PlayerInfo> {
/// return Player
/// .including(required: Player.team.forKey(CodingKeys.team))
/// .asRequest(of: PlayerInfo.self)
/// }
/// }
///
/// let playerInfos = PlayerInfo.all().fetchAll(db)
/// print(playerInfos.first?.team)
public func forKey(_ codingKey: CodingKey) -> Self {
return forKey(codingKey.stringValue)
}
/// Creates an association that allows you to define expressions that target
/// a specific database table.
///
/// In the example below, the "team.color = 'red'" condition in the where
/// clause could be not achieved without table aliases.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // JOIN team ON ...
/// // WHERE team.color = 'red'
/// let teamAlias = TableAlias()
/// let request = Player
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(teamAlias[Column("color")] == "red")
///
/// When you give a name to a table alias, you can reliably inject sql
/// snippets in your requests:
///
/// // SELECT player.*, custom.*
/// // JOIN team custom ON ...
/// // WHERE custom.color = 'red'
/// let teamAlias = TableAlias(name: "custom")
/// let request = Player
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(sql: "custom.color = ?", arguments: ["red"])
public func aliased(_ alias: TableAlias) -> Self {
return mapDestinationRelation { $0.qualified(with: alias) }
}
}
extension Association {
/// Creates an association that prefetches another one.
public func including<A: AssociationToMany>(all association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return mapDestinationRelation {
$0.including(all: association.sqlAssociation)
}
}
/// Creates an association that includes another one. The columns of the
/// associated record are selected. The returned association does not
/// require that the associated database table contains a matching row.
public func including<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return mapDestinationRelation {
$0.including(optional: association.sqlAssociation)
}
}
/// Creates an association that includes another one. The columns of the
/// associated record are selected. The returned association requires
/// that the associated database table contains a matching row.
public func including<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return mapDestinationRelation {
$0.including(required: association.sqlAssociation)
}
}
/// Creates an association that joins another one. The columns of the
/// associated record are not selected. The returned association does not
/// require that the associated database table contains a matching row.
public func joining<A: Association>(optional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return mapDestinationRelation {
$0.joining(optional: association.sqlAssociation)
}
}
/// Creates an association that joins another one. The columns of the
/// associated record are not selected. The returned association requires
/// that the associated database table contains a matching row.
public func joining<A: Association>(required association: A) -> Self where A.OriginRowDecoder == RowDecoder {
return mapDestinationRelation {
$0.joining(required: association.sqlAssociation)
}
}
}
// Allow association.filter(key: ...)
extension Association where Self: TableRequest, RowDecoder: TableRecord {
/// :nodoc:
public var databaseTableName: String { return RowDecoder.databaseTableName }
}
// MARK: - AssociationToOne
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The base protocol for all associations that define a one-to-one connection.
public protocol AssociationToOne: Association { }
extension AssociationToOne {
public func forKey(_ key: String) -> Self {
let associationKey = SQLAssociationKey.fixedSingular(key)
return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
}
}
// MARK: - AssociationToMany
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
///
/// The base protocol for all associations that define a one-to-many connection.
public protocol AssociationToMany: Association { }
extension AssociationToMany {
public func forKey(_ key: String) -> Self {
let associationKey = SQLAssociationKey.fixedPlural(key)
return Self.init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
}
}
extension AssociationToMany where OriginRowDecoder: TableRecord {
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<OriginRowDecoder> {
return AssociationAggregate { request in
let tableAlias = TableAlias()
let request = request
.joining(optional: self.aliased(tableAlias))
.groupByPrimaryKey()
let expression = tableAlias[expression]
return (request: request, expression: expression)
}
}
/// The number of associated records.
///
/// It has a default name, which is "[key]Count", where key is the key of
/// the association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var playerCount: Int
/// }
/// let request = Team.annotated(with: Team.players.count())
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
public var count: AssociationAggregate<OriginRowDecoder> {
return makeAggregate(SQLExpressionCountDistinct(Column.rowID))
.aliased("\(key.singularizedName)Count")
}
/// Creates an aggregate that is true if there exists no associated records.
///
/// It has a default name, which is "hasNo[Key]", where key is the key of
/// the association. For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var hasNoPlayer: Bool
/// }
/// let request = Team.annotated(with: Team.players.isEmpty())
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.isEmpty()).fetchAll(db)
/// let teams: [Team] = try Team.having(!Team.players.isEmpty())
/// let teams: [Team] = try Team.having(Team.players.isEmpty() == false)
public var isEmpty: AssociationAggregate<OriginRowDecoder> {
return makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID)))
.aliased("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
}
/// Creates an aggregate which evaluate to the average value of the given
/// expression in associated records.
///
/// When the averaged expression is a column, the aggregate has a default
/// name which is "average[Key][Column]", where key is the key of the
/// association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var averagePlayerScore: Double
/// }
/// let request = Team.annotated(with: Team.players.average(Column("score")))
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db)
public func average(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.aliased("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// Creates an aggregate which evaluate to the maximum value of the given
/// expression in associated records.
///
/// When the maximized expression is a column, the aggregate has a default
/// name which is "maximum[Key][Column]", where key is the key of the
/// association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var maxPlayerScore: Double
/// }
/// let request = Team.annotated(with: Team.players.max(Column("score")))
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db)
public func max(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.aliased("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// Creates an aggregate which evaluate to the minimum value of the given
/// expression in associated records.
///
/// When the minimized expression is a column, the aggregate has a default
/// name which is "minimum[Key][Column]", where key is the key of the
/// association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var minPlayerScore: Double
/// }
/// let request = Team.annotated(with: Team.players.min(Column("score")))
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db)
public func min(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.aliased("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
} else {
return aggregate
}
}
/// Creates an aggregate which evaluate to the sum of the given expression
/// in associated records.
///
/// When the summed expression is a column, the aggregate has a default
/// name which is "[key][Column]Sum", where key is the key of the
/// association. For example:
///
/// For example:
///
/// struct TeamInfo: FetchableRecord, Decodable {
/// var team: Team
/// var playerScoreSum: Double
/// }
/// let request = Team.annotated(with: Team.players.sum(Column("score")))
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
///
/// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db)
public func sum(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.aliased("\(name)\(column.name.uppercasingFirstCharacter)Sum")
} else {
return aggregate
}
}
}
@@ -108,7 +108,7 @@ extension AssociationAggregate {
///
/// For example:
///
/// let request = Author.having(!Author.books.isEmpty)
/// Author.having(!Author.books.isEmpty)
public prefix func ! <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = aggregate.prepare(request)
@@ -120,7 +120,7 @@ public prefix func ! <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -
///
/// For example:
///
/// let request = Author.having(Author.books.isEmpty && Author.paintings.isEmpty)
/// Author.having(Author.books.isEmpty && Author.paintings.isEmpty)
public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -129,7 +129,7 @@ public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
}
}
// TODO: test & document
// TODO: test
/// :nodoc:
public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
@@ -138,7 +138,7 @@ public func && <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
}
}
// TODO: test & document
// TODO: test
/// :nodoc:
public func && <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
@@ -152,7 +152,7 @@ public func && <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDe
///
/// For example:
///
/// let request = Author.having(!Author.books.isEmpty || !Author.paintings.isEmpty)
/// Author.having(!Author.books.isEmpty || !Author.paintings.isEmpty)
public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -161,7 +161,7 @@ public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
}
}
// TODO: test & document
// TODO: test
/// :nodoc:
public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
@@ -170,7 +170,7 @@ public func || <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
}
}
// TODO: test & document
// TODO: test
/// :nodoc:
public func || <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
@@ -185,7 +185,7 @@ public func || <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDe
///
/// For example:
///
/// let request = Author.having(Author.books.count == Author.paintings.count)
/// Author.having(Author.books.count == Author.paintings.count)
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -198,7 +198,7 @@ public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
///
/// For example:
///
/// let request = Author.having(Author.books.count == 3)
/// Author.having(Author.books.count == 3)
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -210,7 +210,7 @@ public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
///
/// For example:
///
/// let request = Author.having(3 == Author.books.count)
/// Author.having(3 == Author.books.count)
public func == <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -222,7 +222,7 @@ public func == <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDe
///
/// For example:
///
/// let request = Author.having(Author.books.isEmpty == false)
/// Author.having(Author.books.isEmpty == false)
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -234,7 +234,7 @@ public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) ->
///
/// For example:
///
/// let request = Author.having(false == Author.books.isEmpty)
/// Author.having(false == Author.books.isEmpty)
public func == <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -246,7 +246,7 @@ public func == <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) ->
///
/// For example:
///
/// let request = Author.having(Author.books.count != Author.paintings.count)
/// Author.having(Author.books.count != Author.paintings.count)
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -259,7 +259,7 @@ public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
///
/// For example:
///
/// let request = Author.having(Author.books.count != 3)
/// Author.having(Author.books.count != 3)
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -271,7 +271,7 @@ public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
///
/// For example:
///
/// let request = Author.having(3 != Author.books.count)
/// Author.having(3 != Author.books.count)
public func != <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -283,7 +283,7 @@ public func != <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDe
///
/// For example:
///
/// let request = Author.having(Author.books.isEmpty != true)
/// Author.having(Author.books.isEmpty != true)
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -295,7 +295,7 @@ public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) ->
///
/// For example:
///
/// let request = Author.having(true != Author.books.isEmpty)
/// Author.having(true != Author.books.isEmpty)
public func != <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -307,7 +307,7 @@ public func != <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) ->
///
/// For example:
///
/// let request = Author.having(Author.books.count === Author.paintings.count)
/// Author.having(Author.books.count === Author.paintings.count)
public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -320,7 +320,7 @@ public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associa
///
/// For example:
///
/// let request = Author.having(Author.books.count === 3)
/// Author.having(Author.books.count === 3)
public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -332,7 +332,7 @@ public func === <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpr
///
/// For example:
///
/// let request = Author.having(3 === Author.books.count)
/// Author.having(3 === Author.books.count)
public func === <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -344,7 +344,7 @@ public func === <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowD
///
/// For example:
///
/// let request = Author.having(Author.books.count !== Author.paintings.count)
/// Author.having(Author.books.count !== Author.paintings.count)
public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -357,7 +357,7 @@ public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associa
///
/// For example:
///
/// let request = Author.having(Author.books.count !== 3)
/// Author.having(Author.books.count !== 3)
public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -369,7 +369,7 @@ public func !== <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpr
///
/// For example:
///
/// let request = Author.having(3 !== Author.books.count)
/// Author.having(3 !== Author.books.count)
public func !== <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -383,7 +383,7 @@ public func !== <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowD
///
/// For example:
///
/// let request = Author.having(Author.books.count <= Author.paintings.count)
/// Author.having(Author.books.count <= Author.paintings.count)
public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -396,7 +396,7 @@ public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
///
/// For example:
///
/// let request = Author.having(Author.books.count <= 3)
/// Author.having(Author.books.count <= 3)
public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -408,7 +408,7 @@ public func <= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
///
/// For example:
///
/// let request = Author.having(3 <= Author.books.count)
/// Author.having(3 <= Author.books.count)
public func <= <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -420,7 +420,7 @@ public func <= <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDe
///
/// For example:
///
/// let request = Author.having(Author.books.count < Author.paintings.count)
/// Author.having(Author.books.count < Author.paintings.count)
public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -433,7 +433,7 @@ public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
///
/// For example:
///
/// let request = Author.having(Author.books.count < 3)
/// Author.having(Author.books.count < 3)
public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -445,7 +445,7 @@ public func < <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
///
/// For example:
///
/// let request = Author.having(3 < Author.books.count)
/// Author.having(3 < Author.books.count)
public func < <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -457,7 +457,7 @@ public func < <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
///
/// For example:
///
/// let request = Author.having(Author.books.count > Author.paintings.count)
/// Author.having(Author.books.count > Author.paintings.count)
public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -470,7 +470,7 @@ public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
///
/// For example:
///
/// let request = Author.having(Author.books.count > 3)
/// Author.having(Author.books.count > 3)
public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -482,7 +482,7 @@ public func > <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
///
/// For example:
///
/// let request = Author.having(3 > Author.books.count)
/// Author.having(3 > Author.books.count)
public func > <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -494,7 +494,7 @@ public func > <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
///
/// For example:
///
/// let request = Author.having(Author.books.count >= Author.paintings.count)
/// Author.having(Author.books.count >= Author.paintings.count)
public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -507,7 +507,7 @@ public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associat
///
/// For example:
///
/// let request = Author.having(Author.books.count >= 3)
/// Author.having(Author.books.count >= 3)
public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -519,7 +519,7 @@ public func >= <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpre
///
/// For example:
///
/// let request = Author.having(3 >= Author.books.count)
/// Author.having(3 >= Author.books.count)
public func >= <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -533,7 +533,7 @@ public func >= <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDe
///
/// For example:
///
/// let request = Author.annotated(with: -Author.books.count)
/// Author.annotated(with: -Author.books.count)
public prefix func - <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = aggregate.prepare(request)
@@ -545,7 +545,7 @@ public prefix func - <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -
///
/// For example:
///
/// let request = Author.annotated(with: Author.books.count + Author.paintings.count)
/// Author.annotated(with: Author.books.count + Author.paintings.count)
public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -558,7 +558,7 @@ public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
///
/// For example:
///
/// let request = Author.annotated(with: Author.books.count + 1)
/// Author.annotated(with: Author.books.count + 1)
public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -570,7 +570,7 @@ public func + <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
///
/// For example:
///
/// let request = Author.annotated(with: 1 + Author.books.count)
/// Author.annotated(with: 1 + Author.books.count)
public func + <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -582,7 +582,7 @@ public func + <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
///
/// For example:
///
/// let request = Author.annotated(with: Author.books.count - Author.paintings.count)
/// Author.annotated(with: Author.books.count - Author.paintings.count)
public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -595,7 +595,7 @@ public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
///
/// For example:
///
/// let request = Author.annotated(with: Author.books.count - 1)
/// Author.annotated(with: Author.books.count - 1)
public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -607,7 +607,7 @@ public func - <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
///
/// For example:
///
/// let request = Author.annotated(with: 1 - Author.books.count)
/// Author.annotated(with: 1 - Author.books.count)
public func - <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -619,7 +619,7 @@ public func - <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
///
/// For example:
///
/// let request = Author.annotated(with: Author.books.count * Author.paintings.count)
/// Author.annotated(with: Author.books.count * Author.paintings.count)
public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -632,7 +632,7 @@ public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
///
/// For example:
///
/// let request = Author.annotated(with: Author.books.count * 2)
/// Author.annotated(with: Author.books.count * 2)
public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -644,7 +644,7 @@ public func * <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
///
/// For example:
///
/// let request = Author.annotated(with: 2 * Author.books.count)
/// Author.annotated(with: 2 * Author.books.count)
public func * <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -656,7 +656,7 @@ public func * <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
///
/// For example:
///
/// let request = Author.annotated(with: Author.books.count / Author.paintings.count)
/// Author.annotated(with: Author.books.count / Author.paintings.count)
public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (lRequest, lExpression) = lhs.prepare(request)
@@ -669,7 +669,7 @@ public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Associati
///
/// For example:
///
/// let request = Author.annotated(with: Author.books.count / 2)
/// Author.annotated(with: Author.books.count / 2)
public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = lhs.prepare(request)
@@ -681,7 +681,7 @@ public func / <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpres
///
/// For example:
///
/// let request = Author.annotated(with: 2 / Author.books.count)
/// Author.annotated(with: 2 / Author.books.count)
public func / <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
return AssociationAggregate { request in
let (request, expression) = rhs.prepare(request)
@@ -689,7 +689,21 @@ public func / <RowDecoder>(lhs: SQLExpressible, rhs: AssociationAggregate<RowDec
}
}
// MARK: - IFNULL(...)
/// Returns an aggregate that evaluates the `IFNULL` SQL function.
///
/// Team.annotated(with: Team.players.min(Column("score")) ?? 0)
public func ?? <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: SQLExpressible) -> AssociationAggregate<RowDecoder> {
var aggregate = AssociationAggregate<RowDecoder> { request in
let (request, expression) = lhs.prepare(request)
return (request: request, expression: expression ?? rhs)
}
// Preserve alias
aggregate.alias = lhs.alias
return aggregate
}
// TODO: add support for ABS(aggregate)
// TODO: add support for LENGTH(aggregate)
// TODO: add support for IFNULL(aggregate, ...)
// TODO: add support for IFNULL(..., aggregate)
Loaded 100 of 442 files, more files were not shown because too many files have changed in this diff. Show more