Compare commits

..
68 Commits
Author SHA1 Message Date
Gwendal Roué 4c2290f84b Move Design Notes 2021-01-28 08:29:48 +01:00
Gwendal Roué efc8e4bbf9 Fetching players 2021-01-28 08:27:41 +01:00
Gwendal Roué 5c986b142b Saving playerrs 2021-01-28 08:10:30 +01:00
Gwendal Roué 4ec77f8d02 TODO 2021-01-28 08:10:30 +01:00
Gwendal Roué d7dfb4c2ed Precise documentation 2021-01-28 08:10:30 +01:00
Gwendal Roué f4a32edbb9 TODO 2021-01-28 08:10:30 +01:00
Gwendal Roué 8bb9ef0849 Indent raw SQL versions 2021-01-28 08:10:30 +01:00
Gwendal Roué 0210144ea9 Extract Player definition 2021-01-28 08:10:30 +01:00
Gwendal Roué 2842bc92ca Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué 2ca857d895 Fix typo 2021-01-28 08:10:30 +01:00
Gwendal Roué 95ec107134 Group design notes at the end of the chapter 2021-01-28 08:10:30 +01:00
Gwendal Roué 18c65eecb6 Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué 3c1ab47843 Group design notes at the end of the chapter 2021-01-28 08:10:30 +01:00
Gwendal Roué 6b706bbc85 Group design notes 2021-01-28 08:10:30 +01:00
Gwendal Roué e6435ade96 Talk about sample code 2021-01-28 08:10:30 +01:00
Gwendal Roué c854b5a88a Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué f2d51d2feb The Database Service rewrite 2021-01-28 08:10:30 +01:00
Gwendal Roué 95cd6f3c4f Introduction 2021-01-28 08:10:30 +01:00
Gwendal Roué 4a0d8602e2 Clarify the tutorial scope 2021-01-28 08:10:30 +01:00
Gwendal Roué a83f76be10 Remove a missing logical link 2021-01-28 08:10:30 +01:00
Gwendal Roué 10420e6426 Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué 5ab90c1b6c More achievements 2021-01-28 08:10:30 +01:00
Gwendal Roué 5c70477a04 SwiftUI use in-memory databases 2021-01-28 08:10:30 +01:00
Gwendal Roué cb4a0f349e Rename the tutorial 2021-01-28 08:10:30 +01:00
Gwendal Roué 9a0db52c9b The Initial Application State 2021-01-28 08:10:30 +01:00
Gwendal Roué 7cf7300129 Fix typo and wording 2021-01-28 08:10:30 +01:00
Gwendal Roué 6fbeed1a2a Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué 1defe3aaf1 Why columns are hidden 2021-01-28 08:10:30 +01:00
Gwendal Roué 074af18152 Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué 43c9aa3474 Wording 2021-01-28 08:10:30 +01:00
Gwendal Roué d95a76a47a Compare with ActiveRecord 2021-01-28 08:10:30 +01:00
Gwendal Roué ae8c1f11a9 Player requests 2021-01-28 08:10:30 +01:00
Gwendal Roué 4decdd7dea SQL Interpolation: add support for collations 2021-01-28 08:10:30 +01:00
Gwendal Roué 1d41807e25 Add link 2021-01-28 08:10:30 +01:00
Gwendal Roué 571a70e073 Organization 2021-01-28 08:10:30 +01:00
Gwendal Roué 2822c959f8 Repurpose the focus of the tutorial 2021-01-28 08:10:30 +01:00
Gwendal Roué d8c5d85fcb Postpone name collation until the fetch 2021-01-28 08:10:30 +01:00
Gwendal Roué 3f493fa7a8 Mention ACID robustness against errors and crashes 2021-01-28 08:10:29 +01:00
Gwendal Roué cecc3cffdc Emphasis 2021-01-28 08:10:29 +01:00
Gwendal Roué 5ea0cf6cdd Introduce fetchable records 2021-01-28 08:10:29 +01:00
Gwendal Roué 3ebbddb9f3 Tip about helper methods 2021-01-28 08:10:29 +01:00
Gwendal Roué 238f01725b SQL version of AppDatabase.refreshPlayers() 2021-01-28 08:10:29 +01:00
Gwendal Roué 51b975e872 Fix typo 2021-01-28 08:10:29 +01:00
Gwendal Roué 4b9643daf2 Modifying Players chapter 2021-01-28 08:10:29 +01:00
Gwendal Roué 6daf078fc3 Fix focus 2021-01-28 08:10:29 +01:00
Gwendal Roué 7aced9b925 Documentation 2021-01-28 08:10:29 +01:00
Gwendal Roué 16fc88ba09 Wording 2021-01-28 08:10:29 +01:00
Gwendal Roué 4ac7e3d15c Avoid "such as" repetition 2021-01-28 08:10:29 +01:00
Gwendal Roué 48b8c1ee14 More notes about SQL injection prevention 2021-01-28 08:10:29 +01:00
Gwendal Roué 1af981255d How to deal with missing Swift versions of SQLite functions or operators? 2021-01-28 08:10:29 +01:00
Gwendal Roué 6a07361614 Indent design notes 2021-01-28 08:10:29 +01:00
Gwendal Roué f32f5e2d7b Describe the tutorial audience 2021-01-28 08:10:29 +01:00
Gwendal Roué 322959f1c4 Deleting players 2021-01-28 08:10:29 +01:00
Gwendal Roué eaca12aed1 Fix typo 2021-01-28 08:10:29 +01:00
Gwendal Roué 96a8b46214 Wording 2021-01-28 08:10:29 +01:00
Gwendal Roué 7f2f4fdfcc Wording 2021-01-28 08:10:29 +01:00
Gwendal Roué ceccbb38fb Wording 2021-01-28 08:10:29 +01:00
Gwendal Roué af21c82dd6 Better explain why id is autoincremented 2021-01-28 08:10:29 +01:00
Gwendal Roué b2573a12bc Explain why id is autoincremented 2021-01-28 08:10:29 +01:00
Gwendal Roué d00de45e4f Links & wording 2021-01-28 08:10:29 +01:00
Gwendal Roué 6512e7bf61 Fix typo 2021-01-28 08:10:29 +01:00
Gwendal Roué 1cd88114ec Rewrite introduction to migrations 2021-01-28 08:10:29 +01:00
Gwendal Roué 86cf024a78 AppDatabase error handling suggestion 2021-01-28 08:10:29 +01:00
Gwendal Roué afdde192cd Rewrite the AppDatabase introduction 2021-01-28 08:10:29 +01:00
Gwendal Roué 0b321dfedf Rewrite the introduction 2021-01-28 08:10:29 +01:00
Gwendal Roué 7617bb258d Getting Started tutorial 2021-01-28 08:10:29 +01:00
Gwendal Roué 104466170b Demo app feeds from a single observation 2021-01-28 08:10:29 +01:00
Gwendal Roué 4b5a1340aa Demo apps: store the database in its own folder
This is a recommended good practice
2021-01-28 08:10:29 +01:00
268 changed files with 10932 additions and 24506 deletions

No files matched your search

+1
View File
@@ -61,3 +61,4 @@ opt_in_rules:
vertical_whitespace:
max_empty_lines: 2
+120 -120
View File
@@ -26,6 +26,126 @@ git:
jobs:
include:
###########################################
## Test GRDB Xcode 12.2
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBOSX_maxSwift
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.2"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBOSX_minSwift
- name: "Test GRDB Xcode 12.2 - GRDBWatchOS"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBWatchOS
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBiOS_minTarget
- name: "Test GRDB Xcode 12.2 - GRDBtvOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12 - GRDBtvOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBtvOS_minTarget
- name: "Test GRDB Xcode 12.2 - SPM"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_SPM
###########################################
## Test GRDBCustom Xcode 12.2
- name: "Test GRDBCustom Xcode 12.2 - GRDBOSX"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBCustomSQLiteOSX
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test SQLCipher Xcode 12.2
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_SQLCipher3
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 4"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_framework_SQLCipher4
###########################################
## Test Installation Xcode 12.2
# Manual Install
- name: "Test Installation Xcode 12.2 - Manual Install"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_manual
# Travis is much too slow, and always fail this job
# # CocoaPods Lint
# - name: "Test Installation Xcode 12.2 - CocoaPods Lint"
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode12.2
# script: make test_CocoaPodsLint_GRDB
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.2 - CocoaPods Framework"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.2 - CocoaPods Static"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- name: "Test Installation Xcode 12.2 - SPM Package"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_SPM_Package
# SPM Install
- name: "Test Installation Xcode 12.2 - SPM Package in Xcode Project"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_SPM_Project
# Custom SQLite Install
- name: "Test Installation Xcode 12.2 - Custom SQLite"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.2
script: make test_install_customSQLite
###########################################
## Test GRDB Xcode 11.4
@@ -39,123 +159,3 @@ jobs:
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode11.4
script: make test_framework_GRDBiOS_minTarget
###########################################
## Test GRDB Xcode 12.5
- name: "Test GRDB Xcode 12.5 - GRDBOSX - Swift 5.3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBOSX_maxSwift
- name: "Test GRDB Xcode 12.5 - GRDBOSX - Swift 5.2"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBOSX_minSwift
- name: "Test GRDB Xcode 12.5 - GRDBWatchOS"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBWatchOS
- name: "Test GRDB Xcode 12.5 - GRDBiOS iOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBiOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12.5 - GRDBiOS iOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBiOS_minTarget
- name: "Test GRDB Xcode 12.5 - GRDBtvOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
- name: "Test GRDB Xcode 12.5 - GRDBtvOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBtvOS_minTarget
- name: "Test GRDB Xcode 12.5 - SPM"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_SPM
###########################################
## Test GRDBCustom Xcode 12.5
- name: "Test GRDBCustom Xcode 12.5 - GRDBOSX"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBCustomSQLiteOSX
- name: "Test GRDBCustom Xcode 12.5 - GRDBiOS maxTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
- name: "Test GRDBCustom Xcode 12.5 - GRDBiOS minTarget"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
###########################################
## Test SQLCipher Xcode 12.5
- name: "Test SQLCipher Xcode 12.5 - SQLCipher 3"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_SQLCipher3
- name: "Test SQLCipher Xcode 12.5 - SQLCipher 4"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_framework_SQLCipher4
###########################################
## Test Installation Xcode 12.5
# Manual Install
- name: "Test Installation Xcode 12.5 - Manual Install"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_manual
# Travis is much too slow, and always fail this job
# # CocoaPods Lint
# - name: "Test Installation Xcode 12.5 - CocoaPods Lint"
# gemfile: .ci/gemfiles/Gemfile.travis
# osx_image: xcode12.5
# script: make test_CocoaPodsLint_GRDB
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.5 - CocoaPods Framework"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_GRDB_CocoaPods_framework
# CocoaPods Install GRDB
- name: "Test Installation Xcode 12.5 - CocoaPods Static"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_GRDB_CocoaPods_static
# SPM Install
- name: "Test Installation Xcode 12.5 - SPM Package"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_SPM_Package
# SPM Install
- name: "Test Installation Xcode 12.5 - SPM Package in Xcode Project"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_SPM_Project
# Custom SQLite Install
- name: "Test Installation Xcode 12.5 - Custom SQLite"
gemfile: .ci/gemfiles/Gemfile.travis
osx_image: xcode12.5
script: make test_install_customSQLite
-6
View File
@@ -4,12 +4,6 @@ Here is a list of people who were happy to meet GRDB :-)
---
https://twitter.com/swiftkarim/status/1354753451377483781
> I cannot recommend GRDB enough. It works well with Swift and eliminates whole classes of potential programming errors that can be made with Core Data. Also being able to use raw SQL queries if needed can be extremely useful!
---
https://twitter.com/peres/status/1352219836508729346
> Just the occasional reminder that GRDB and its documentation is the gold standard. That's it.
-201
View File
@@ -7,12 +7,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 5.x Releases
- `5.9.x` Releases - [5.9.0](#590)
- `5.8.x` Releases - [5.8.0](#580)
- `5.7.x` Releases - [5.7.0](#570) | [5.7.1](#571) | [5.7.2](#572) | [5.7.3](#573) | [5.7.4](#574)
- `5.6.x` Releases - [5.6.0](#560)
- `5.5.x` Releases - [5.5.0](#550)
- `5.4.x` Releases - [5.4.0](#540)
- `5.3.x` Releases - [5.3.0](#530)
- `5.2.x` Releases - [5.2.0](#520)
- `5.1.x` Releases - [5.1.0](#510)
@@ -74,201 +68,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- [0.110.0](#01100), ...
---
## 5.9.0
Released August 15, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.8.0...v5.9.0)
- **Fixed**: [#980](https://github.com/groue/GRDB.swift/pull/980) by [@jroselightricks](https://github.com/jroselightricks): Fix spelling
- **Fixed**: [#989](https://github.com/groue/GRDB.swift/pull/989) by [@pp5x](https://github.com/pp5x): FTS: add support of ifNotExists in synchronize()
- **Fixed**: [#999](https://github.com/groue/GRDB.swift/issues/999): `request(for: association)` no longer crashes when the foreign key contains a NULL value.
- **Fixed**: [#1025](https://github.com/groue/GRDB.swift/issues/1025) by [@mattgallagher](https://github.com/mattgallagher): Fix ValueObservation crash
- **Fixed**: Fix thread unsafety in `ValueObservation.print()`
- **New**: The `selectID()` method is now available for [Identifiable Records](README.md#identifiable-records)
- **New**: Cached prepared statements can profit from [SQL Interpolation](Documentation/SQLInterpolation.md):
```swift
let updateStatement = try db.cachedStatement(literal: "INSERT ...")
// ~~~~~~~
```
- **New**: [#993](https://github.com/groue/GRDB.swift/pull/993) by [@groue](https://github.com/groue): QueryInterfaceRequest builder with dynamic table/view name
- **New**: Types that adopt both `DatabaseValueConvertible` and `Codable` now profit from automatic JSON encoding and decoding.
- **New**: [#1010](https://github.com/groue/GRDB.swift/pull/1010) by [@tternes](https://github.com/tternes): Add VACUUM INTO Support
- **New**: [#1012](https://github.com/groue/GRDB.swift/pull/1012) by [@ZevEisenberg](https://github.com/ZevEisenberg): Add brackets to urls in doc comments to make them clickable
- **New**: [#1019](https://github.com/groue/GRDB.swift/pull/1019) by [@groue](https://github.com/groue): Merge prepared statement types, and introduce statement cursor
- **Documentation Update**: The [Requests](README.md#requests) chapter was updated for the new `Table` type that can build requests without any record type.
- **Documentation Update**: The [Custom Value Types](README.md#custom-value-types) chapter was extended about the new support for codable value types encoded as JSON arrays or objects.
- **Documentation Update**: The [Fetching Methods](README.md#fetching-methods) and [Prepared Statements](README.md#prepared-statements) chapters have been updated for the unique `Statement` class, and the new `Database.allStatements()` method.
## 5.8.0
Released May 16, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.7.4...v5.8.0)
- **New**: Support for the `ESCAPE` clause with the `LIKE` operator.
- **New**: You can now define an `SQLRequest` without any generic qualifier (which defaults to `Row`):
```swift
let request = SQLRequest("SELECT ...")
```
- **New**: [#967](https://github.com/groue/GRDB.swift/pull/967) by [@steipete](https://github.com/steipete): Make SelectStatement conform to CustomStringConvertible
- **Fixed**: The `DerivableRequest.limit(_:offset:)` method was ill-designed, and removed from the documentation. It is unfortunately impossible to deprecate it without triggering warnings on the legit use cases (on `QueryInterfaceRequest`).
- **Fixed**: [#973](https://github.com/groue/GRDB.swift/pull/973): Restore access to attached databases from record types
- **Fixed**: [#974](https://github.com/groue/GRDB.swift/pull/974): Provide access to included associations when root table is not selected
- **Documentation Update**: A new [Query Interface Organization](Documentation/QueryInterfaceOrganization.md) document reveals the relationship between the various components of the GRDB query builder.
## 5.7.4
Released April 11, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.7.3...v5.7.4)
- **New**: [#953](https://github.com/groue/GRDB.swift/pull/953): Refactor the SwiftUI demo app
- **Fixed**: [#955](https://github.com/groue/GRDB.swift/pull/955) by [@steipete](https://github.com/steipete): Robustness of @Query in the SwiftUI demo app
- **Fixed**: [#956](https://github.com/groue/GRDB.swift/pull/956): Fix case-sensitivity of region-based database observation
- **New**: [#958](https://github.com/groue/GRDB.swift/pull/958) by [@chrisballinger](https://github.com/chrisballinger): Always add userInfo to databaseJSONDecoder and databaseJSONEncoder
- **New**: [#960](https://github.com/groue/GRDB.swift/pull/960) by [@MartinP7r](https://github.com/MartinP7r): Add tests for userInfo being applied to database encoder/decoder
## 5.7.3
Released April 5, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.7.2...v5.7.3)
- **Fixed**: [#950](https://github.com/groue/GRDB.swift/pull/950) by [@MartinP7r](https://github.com/MartinP7r): Fix memory consumption when encoding JSON columns
- **Fixed**: [#951](https://github.com/groue/GRDB.swift/pull/951) by [@alexwlchan](https://github.com/alexwlchan): Fix documentation typo
- **Fixed**: [#952](https://github.com/groue/GRDB.swift/pull/952) by [@holsety](https://github.com/holsety): Fix documentation typo
- **Documentation Update**: [#953](https://github.com/groue/GRDB.swift/pull/953): Refactor the SwiftUI demo app
#### 5.7.2
- **Fixed**: Really fix breaking change and restore `SQLLiteral` as a deprecated alias for `SQL`.
#### 5.7.1
- **Fixed**: Fix breaking change and restore `SQLLiteral` as a deprecated alias for `SQL`.
## 5.7.0
Released March 28, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.6.0...v5.7.0)
- **New**: [#947](https://github.com/groue/GRDB.swift/pull/947) by [@chrisballinger](https://github.com/chrisballinger): Allow access to Encoder from KeyedEncodingContainer
- **New**: Record types that adopt the standard [Identifiable](https://developer.apple.com/documentation/swift/identifiable) protocol have gained type-safe methods that deal with the primary key. For example:
```swift
let player = try Player.fetchOne(db, id: 42)
try Player.deleteAll(db, ids: [1, 2, 3])
```
See the new [Identifiable Records](README.md#identifiable-records) documentation chapter for more information.
- **New**: `SQLLiteral` has more use cases than initialy expected, and is renamed `SQL`.
- **New**: [`SQL` literal](Documentation/SQLInterpolation.md#sql-literal) can now be directly used as an expression, an ordering term, or a selection item.:
```swift
let name = "O'Brien"
let request = Player
.select(SQL("id, score"), ...)
.filter(SQL("name = \(name)") && ...)
.order(SQL("score DESC"), ...)
```
- **New**: Table creation DSL now supports columns and constraints defined with raw SQL String or [SQL literal](Documentation/SQLInterpolation.md#sql-literal):
```swift
try db.create(table: "player") do { t in
t.column(sql: "id INTEGER PRIMARY KEY AUTOINCREMENT")
t.column(literal: "name TEXT DEFAULT \("Anonymous")")
t.constraint(sql: "CHECK (LENGTH(name) > 0)")
t.constraint(literal: "CHECK (LENGTH(name) <= \(100))")
}
```
- **New**: Prepared statements can profit from [SQL Interpolation](Documentation/SQLInterpolation.md):
```swift
let updateStatement = try db.makeUpdateStatement(literal: "INSERT ...")
let selectStatement = try db.makeSelectStatement(literal: "SELECT ...")
// ~~~~~~~
```
- **New**: [DatabaseMigrator](Documentation/Migrations.md#asynchronous-migrations) can now asynchronously migrate a database. A Combine publisher is also available.
- **New**: Added support for the `EXISTS` and `NOT EXISTS` subquery operators. See the updated [SQL Operators](README.md#sql-operators) documentation.
- **New**: `Foundation.Decimal` can now be stored in the database, and all Foundation number types can be decoded from decimal numbers stored as strings. See the [NSNumber, NSDecimalNumber, and Decimal](README.md#nsnumber-nsdecimalnumber-and-decimal) chapter for details.
## 5.6.0
Released March 12, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.5.0...v5.6.0)
- **Fixed**: [#933](https://github.com/groue/GRDB.swift/pull/933): Fix DatabaseMigrator.eraseDatabaseOnSchemaChange in the context of shared databases
- **Fixed**: [#934](https://github.com/groue/GRDB.swift/pull/934): Fix a crash in the ValueObservation publisher
- **New**: [#936](https://github.com/groue/GRDB.swift/pull/936): Complete Associations and the DerivableRequest Protocol
- **New**: Database cursors can feed more standard Swift collections: `Array(cursor, minimumCapacity: ...)`, `Dictionary(uniqueKeysWithValues: cursor)`, etc (see [Cursors](README.md#cursors)).
- **Documentation update**: The [Associations Guide](Documentation/AssociationsBasics.md) has gained a new [Further Refinements to Associations](Documentation/AssociationsBasics.md#further-refinements-to-associations) chapter which shows the new association methods brought by [#936](https://github.com/groue/GRDB.swift/pull/936).
- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has an updated [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions.
- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a new chapter of good practices: [Record Types Hide Intimate Database Details](Documentation/GoodPracticesForDesigningRecordTypes.md#record-types-hide-intimate-database-details).
- **Documentation update**: A new [Single-Row Tables](Documentation/SingleRowTables.md) guide provides guidance for designing tables that store configuration values, user preferences, and generally some global application state.
## 5.5.0
Released March 3, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.4.0...v5.5.0)
- **New**: You can now define common table expressions without any generic qualifier (which defaults to `Row`):
```swift
let cte = CommonTableExpression(...)
```
The [Common Table Expressions Guide](Documentation/CommonTableExpressions.md) was updated accordingly.
- **New**: `DatabaseQueue` reading methods are now wrapped in a deferred transaction. This guarantees snapshot isolation in case of concurrent writes performed by external connections, and makes `DatabaseQueue` a type suitable for shared databases.
- **Fixed**: `DatabaseQueue.read` is now declared `throws` instead of `rethrows`.
- **Fixed**: [#930](https://github.com/groue/GRDB.swift/pull/930): Fix SQL generation for `COLLATE`, `IN`, `NOT IN`
## 5.4.0
Released February 15, 2021 &bull; [diff](https://github.com/groue/GRDB.swift/compare/v5.3.0...v5.4.0)
- **Breaking Change**: The query interface was refactored and some types such as `SQLExpression` are no longer a protocol.
This may break some applications that rely on Swift type inference, such as in the following example:
```swift
// No longer compiles
let values = [Column("score"), Column("score") + Column("bonus")]
```
The fix is to add an explicit declaration of the desired type:
```swift
// A possible fix
let values: [SQLExpressible] = [Column("score"), Column("score") + Column("bonus")]
```
Occurrences of such code breakage should be very rare.
- **New**: [SQL Interpolation](Documentation/SQLInterpolation.md) supports embedding collations into SQL literals:
```swift
let request: SQLRequest<Player> = "SELECT * FROM player ORDER BY email COLLATION \(.nocase)"
let request: SQLRequest<Player> = "SELECT * FROM player ORDER BY name COLLATION \(.localizedCompare)"
```
- **Documentation update**: [Adding support for missing SQL functions or operators](README.md#adding-support-for-missing-sql-functions-or-operators) explains how to extend the query interface when needed.
- **Documentation update**: The [Demo Applications](Documentation/DemoApps/) now provide tests for the database access layer.
## 5.3.0
+5 -124
View File
@@ -26,7 +26,6 @@ GRDB Associations
- [Sorting Associations]
- [Ordered Associations]
- [Columns Selected by an Association]
- [Further Refinements to Associations]
- [Table Aliases]
- [Refining Association Requests]
- [Fetching Values from Associations]
@@ -89,7 +88,7 @@ struct BookInfo {
let books = try Book.fetchAll(db)
let bookInfos = books.map { book -> BookInfo in
let author = try Author.fetchOne(db, id: book.authorId)
let author = try Author.fetchOne(db, key: book.authorId)
return BookInfo(book: book, author: author)
}
```
@@ -782,7 +781,6 @@ Fetch requests do not visit the database until you fetch values from them. This
- [Sorting Associations]
- [Ordered Associations]
- [Columns Selected by an Association]
- [Further Refinements to Associations]
- [Table Aliases]
- [Refining Association Requests]
@@ -857,18 +855,14 @@ Before we describe them in detail, let's see a few requests they can build:
let request = Author
.including(all: Author.books)
/// All authors with their awarded books
let request = Author
.including(all: Author.books.having(Book.awards.isEmpty == false))
/// All books with their respective author
let request = Book
.including(required: Book.author)
/// All books with their respective author, sorted by title
let request = Book
.including(required: Book.author)
.order(Column("title"))
.including(required: Book.author)
/// All books written by a French author
let request = Book
@@ -947,21 +941,7 @@ The pattern is always the same: you start from a base request, that you extend w
Another way to describe the difference is that `required` filters the fetched results in order to discard missing associated records, when `optional` does not filter anything, and lets missing values pass through.
Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins:
```swift
// SELECT book.* FROM book LEFT JOIN author ON author.id = book.authorID
Book.joining(optional: Book.author)
// SELECT book.* FROM book JOIN author ON author.id = book.authorID
Book.joining(required: Book.author)
// SELECT book.*, author.* FROM book LEFT JOIN author ON author.id = book.authorID
Book.including(optional: Book.author)
// SELECT book.*, author.* FROM book JOIN author ON author.id = book.authorID
Book.including(required: Book.author)
```
Finally, readers who speak SQL may compare `optional` with left joins, and `required` with inner joins.
## Combining Associations
@@ -1064,7 +1044,7 @@ let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
**You can filter associated records.**
The `filter(_:)`, `filter(id:)`, `filter(ids:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](../README.md#requests), can filter associated records as well:
The `filter(_:)`, `filter(key:)` and `filter(keys:)` methods, that you already know for [filtering simple requests](../README.md#requests), can filter associated records as well:
```swift
// SELECT book.*
@@ -1241,6 +1221,7 @@ let teamInfos = try Team
.fetchAll(db)
```
## Columns Selected by an Association
By default, associated records include all their columns:
@@ -1267,104 +1248,6 @@ let request = Book.including(required: restrictedAuthor)
To specify the default selection for all inclusions of a given type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request).
## Further Refinements to Associations
Associations support more refinements:
- `distinct`
Fetch all authors with the kinds of books they write (novels, poems, plays, etc):
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookKinds: Set<Book.Kind>
}
let distinctBookKinds = Author.books
.select(Column("kind"))
.distinct()
.forKey("bookKinds")
let authorInfos: [AuthorInfo] = try Author
.including(all: distinctBookKinds)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- `group`, `having`
Fetch all authors with the year of their latest book for each kind (novels, poems, plays, etc):
```swift
struct BookKindInfo: Decodable {
var kind: Book.Kind
var maxYear: Int
}
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookKindInfos: [BookKindInfo]
}
let bookKindInfos = Author.books
.select(
Column("kind"),
max(Column("year")).forKey("maxYear"))
.group(Column("kind"))
.forKey("bookKindInfos")
let authorInfos: [AuthorInfo] = try Author
.including(all: bookKindInfos)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- [Association Aggregates]
Fetch all authors with their awarded books:
```swift
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var awardedBooks: [Book]
}
let awardedBooks = Author.books
.having(Book.awards.isEmpty == false)
.forKey("awardedBooks")
let authorInfos: [AuthorInfo] = try Author
.including(all: awardedBooks)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- [Common Table Expressions]
Association can use their own CTEs:
```swift
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var specialBooks: [Book]
}
let specialCTE = CommonTableExpression(...)
let specialBooks = Author.books
.with(specialCTE)
... // use the CTE in the book association
.forKey("specialBooks")
let authorInfos = try Author
.including(all: specialBooks)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
> :warning: **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc.
## Table Aliases
In all examples we have seen so far, all associated records are joined, included, filtered, and sorted independently. We could not filter them on conditions that involve several records, for example.
@@ -2550,7 +2433,6 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Choosing Between BelongsTo and HasOne]: #choosing-between-belongsto-and-hasone
[Self Joins]: #self-joins
[Ordered Associations]: #ordered-associations
[Further Refinements to Associations]: #further-refinements-to-associations
[The Types of Associations]: #the-types-of-associations
[FetchableRecord]: ../README.md#fetchablerecord-protocols
[migration]: Migrations.md
@@ -2601,5 +2483,4 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[ValueObservation]: ../README.md#valueobservation
[FAQ]: ../README.md#faq-associations
[common table expressions]: CommonTableExpressions.md
[Common Table Expressions]: CommonTableExpressions.md
[Associations to Common Table Expressions]: CommonTableExpressions.md#associations-to-common-table-expressions
+2 -17
View File
@@ -46,19 +46,6 @@ let newPlayerCount = dbQueue.writePublisher { db -> Int in
</details>
<details>
<summary><strong>Asynchronously migrate the database</strong></summary>
This publisher migrates a database:
```swift
// DatabasePublishers.Migrate
let migrator: DatabaseMigrator = ...
let publisher = migrator.migratePublisher(dbQueue)
```
</details>
<details>
<summary><strong>Observe changes in database values</strong></summary>
@@ -112,12 +99,11 @@ let cancellable = publisher.sink(
# Asynchronous Database Access
GRDB provide publishers that perform asynchronous database accesses:
GRDB provide publishers that perform asynchronous database accesses.
- [`readPublisher(receiveOn:value:)`]
- [`writePublisher(receiveOn:updates:)`]
- [`writePublisher(receiveOn:updates:thenRead:)`]
- [`migratePublisher(_:receiveOn:)`]
#### `DatabaseReader.readPublisher(receiveOn:value:)`
@@ -139,7 +125,7 @@ When you use a [database pool], reads are generally non-blocking, unless the max
This publisher can be subscribed from any thread. A new database access starts on every subscription.
The fetched value is published on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
The fetched value is published on the main queue, unless you provide a specific scheduler to the `receiveOn` argument.
#### `DatabaseWriter.writePublisher(receiveOn:updates:)`
@@ -335,7 +321,6 @@ See [DatabaseRegionObservation] for more information.
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
[`migratePublisher(_:receiveOn:)`]: Migrations.md#asynchronous-migrations
[configured]: ../README.md#databasepool-configuration
[database pool]: ../README.md#database-pools
[database queue]: ../README.md#database-queues
+55 -44
View File
@@ -29,7 +29,7 @@ The CTE request can be provided as a [query interface request]:
```swift
// WITH playerName AS (SELECT name FROM player) ...
let playerNameCTE = CommonTableExpression(
let playerNameCTE = CommonTableExpression<Void>(
named: "playerName",
request: Player.select(Column("name")))
```
@@ -40,27 +40,27 @@ You can feed a CTE with raw SQL as well (second and third examples use [SQL Inte
let name = "O'Brien"
// WITH playerName AS (SELECT 'O''Brien') ...
let playerNameCTE = CommonTableExpression(
let playerNameCTE = CommonTableExpression<Void>(
named: "playerName",
sql: "SELECT ?", arguments: [name])
// WITH playerName AS (SELECT 'O''Brien') ...
let playerNameCTE = CommonTableExpression(
let playerNameCTE = CommonTableExpression<Void>(
named: "playerName",
literal: "SELECT \(name)")
// WITH playerName AS (SELECT 'O''Brien') ...
let request = SQLRequest("SELECT \(name)")
let playerNameCTE = CommonTableExpression(
let request: SQLRequest<String> = "SELECT \(name)"
let playerNameCTE = CommonTableExpression<Void>(
named: "playerName",
request: request)
request: requests)
```
All CTEs can be provided with explicit column names:
```swift
// WITH pair(a, b) AS (SELECT 1, 2) ...
let pairCTE = CommonTableExpression(
let pairCTE = CommonTableExpression<Void>(
named: "pair",
columns: ["a", "b"],
sql: "SELECT 1, 2")
@@ -71,7 +71,7 @@ Recursive CTEs need the `recursive` flag. The example below selects all integers
```swift
// WITH RECURSIVE counter(x) AS
// (VALUES(1) UNION ALL SELECT x+1 FROM counter WHERE x<1000)
let counterCTE = CommonTableExpression(
let counterCTE = CommonTableExpression<Int>(
recursive: true,
named: "counter",
columns: ["x"],
@@ -84,6 +84,8 @@ let counterCTE = CommonTableExpression(
> :point_up: **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs.
As you can see in all above examples, `CommonTableExpression` is a generic type: `CommonTableExpression<Void>`, `CommonTableExpression<Int>`. The generic argument (`Void`, `Int`) turns useful when you [join common table expressions](#associations-to-common-table-expressions), or when you [fetch values directly from a common table expression](#fetch-values-from-common-table-expressions). Otherwise, you can just use `Void`.
## Embed Common Table Expressions in Requests
@@ -101,7 +103,7 @@ We first build a `CommonTableExpression`:
```swift
let name = "O'Brien"
let playerNameCTE = CommonTableExpression(
let playerNameCTE = CommonTableExpression<Void>(
named: "playerName",
literal: "SELECT \(name)")
```
@@ -182,37 +184,48 @@ try Player
In the previous chapter, a common table expression was embedded as a subquery, with the `CommonTableExpression.all()` method.
`cte.all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests.
`all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests. You can also fetch from it, but only as long as it is provided with the definition of the CTE.
You can also fetch from `cte.all()`, as long as the request is given the definition of the CTE: `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`:
This will generally give requests of the form `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`.
This request, of type `QueryInterfaceRequest<Row>`, can fetch raw database [rows](../README.md#row-queries):
The generic type of `CommonTableExpression<...>` now turns out useful, so that you can fetch the desired outcome (database [rows](../README.md#row-queries), simple [values](../README.md#value-queries), or custom [records](../README.md#records)).
For example, let's fetch a range of integer:
```swift
let cte = CommonTableExpression(...)
let request = cte.all().with(cte)
let rows = try request.fetchAll(db) // [Row]
func counterRequest(range: ClosedRange<Int>) -> QueryInterfaceRequest<Int> {
// WITH RECURSIVE counter(x) AS
// (VALUES(...) UNION ALL SELECT x+1 FROM counter WHERE x<...)
// SELECT * FROM counter
let counter = CommonTableExpression<Int>(
recursive: true,
named: "counter",
columns: ["x"],
literal: """
VALUES(\(range.lowerBound)) \
UNION ALL \
SELECT x+1 FROM counter WHERE x < \(range.upperBound)
""")
return counter.all().with(counter)
}
let values = try dbQueue.read { db in
try counterRequest(range: 3...7).fetchAll(db)
}
print(values) // prints "[3, 4, 5, 6, 7]"
```
In order to fetch something else, such as simple [values](../README.md#value-queries), or custom [records](../README.md#records), you have two possible options:
When you have to fetch from a `CommonTableExpression` which does not have the desired generic type, you can still use the `asRequest(of:)` method:
1. Use the `asRequest(of:)` method:
```swift
let cte = CommonTableExpression(...)
let request = cte.all().with(cte).asRequest(of: Player.self)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
let players = try request.fetchAll(db) // [Player]
```
```swift
let cte: CommonTableExpression<Void> = ...
let rows: [Row] = try dbQueue.read { db in
try cte.all().with(cte)
.asRequest(of: Row.self)
.fetchAll(db)
}
```
2. Provide the fetched type to the cte itself:
```swift
let cte = CommonTableExpression<Player>(...)
// ~~~~~~~~
let request = cte.all().with(cte)
let players = try request.fetchAll(db) // [Player]
```
## Associations to Common Table Expressions
@@ -324,7 +337,7 @@ We can now define the CTE for the latest messages:
```swift
// WITH latestMessage AS
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
let latestMessageCTE = CommonTableExpression(
let latestMessageCTE = CommonTableExpression<Void>(
named: "latestMessage",
request: latestMessageRequest)
```
@@ -365,9 +378,9 @@ And we can fetch the data that feeds our application screen:
let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
```
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, anonymous `CommonTableExpression` CTEs can work against type safety. When you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your common table expressions with an explicit type: `CommonTableExpression<SomeType>`.
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, our go-to `CommonTableExpression<Void>` CTEs can work against type safety. So when you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your `CommonTableExpression` with a type instead of `Void`.
>
> To do so, you can use an existing record type, or an ad-hoc enum. For example:
> You can use an existing record type, or an ad-hoc enum. For example:
>
> ```swift
> enum CTE1 { }
@@ -376,9 +389,9 @@ let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
> enum CTE2 { }
> let cte2 = CommonTableExpression<CTE2>(...)
>
> let assoc1 = BaseRecord.association(to: cte1, on: ...) // from BaseRecord to CTE1
> let assoc2 = cte1.association(to: cte2, on: ...) // from CTE1 to CTE2
> let assoc3 = cte2.association(to: FarRecord.self, on: ...) // from CTE2 to FarRecord
> let assoc1 = BaseRecord.association(to: cte1, on: ...)
> let assoc2 = cte1.association(to: cte2, on: ...)
> let assoc3 = cte2.association(to: FarRecord.self, on: ...)
>
> // WITH ...
> // SELECT base.* FROM base
@@ -387,14 +400,12 @@ let chatInfos: [ChatInfos] = try dbQueue.read(request.fetchAll)
> // JOIN far ON ...
> let request = BaseRecord
> .with(cte1).with(cte2)
> .joining(required: assoc1. // OK
> .joining(required: assoc2. // OK
> .joining(required: assoc3))) // OK
> .joining(required: assoc1
> .joining(required: assoc2
> .joining(required: assoc3)))
>
> // Compiler error
> let request = BaseRecord
> .joining(required: assoc2) // Not OK
> .joining(required: assoc3) // Not OK
> let request = BaseRecord.joining(required: assoc2)
> ```
[query interface request]: ../README.md#requests
@@ -9,9 +9,6 @@
/* Begin PBXBuildFile section */
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */; };
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */; };
5671722A261A185300423B6F /* Query.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717229261A185300423B6F /* Query.swift */; };
5671723A261B23C800423B6F /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717239261B23C800423B6F /* PlayerList.swift */; };
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717251261B334D00423B6F /* PlayerRequestTests.swift */; };
567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */; };
567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */; };
567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */; };
@@ -19,15 +16,15 @@
567C3E4F2520B70E0011F6E9 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 567C3E3B2520B7000011F6E9 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E532520B75C0011F6E9 /* Player.swift */; };
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E542520B75C0011F6E9 /* Persistence.swift */; };
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */; };
567C3E622520B75D0011F6E9 /* AppView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* AppView.swift */; };
567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */; };
567C3E5F2520B75C0011F6E9 /* PlayerListViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */; };
567C3E602520B75C0011F6E9 /* PlayerFormViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */; };
567C3E612520B75D0011F6E9 /* PlayerForm.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerForm.swift */; };
567C3E622520B75D0011F6E9 /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* PlayerList.swift */; };
567C3E632520B75D0011F6E9 /* PlayerCreationSheet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */; };
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */; };
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E652520B7880011F6E9 /* AppDatabase.swift */; };
567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E752520BB650011F6E9 /* Localizable.stringsdict */; };
567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; };
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; };
78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -101,13 +98,6 @@
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
remoteInfo = GRDBiOS;
};
78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
remoteInfo = GRDBCombineDemo;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
@@ -129,9 +119,6 @@
56026C9C25B8A7D000D1DF3F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = "<group>"; };
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = "<group>"; };
56717229261A185300423B6F /* Query.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Query.swift; sourceTree = "<group>"; };
56717239261B23C800423B6F /* PlayerList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
56717251261B334D00423B6F /* PlayerRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequestTests.swift; sourceTree = "<group>"; };
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBCombineDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoApp.swift; sourceTree = "<group>"; };
567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
@@ -140,17 +127,15 @@
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
567C3E532520B75C0011F6E9 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
567C3E542520B75C0011F6E9 /* Persistence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = "<group>"; };
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormView.swift; sourceTree = "<group>"; };
567C3E5A2520B75C0011F6E9 /* AppView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppView.swift; sourceTree = "<group>"; };
567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationView.swift; sourceTree = "<group>"; };
567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewModel.swift; sourceTree = "<group>"; };
567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormViewModel.swift; sourceTree = "<group>"; };
567C3E592520B75C0011F6E9 /* PlayerForm.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerForm.swift; sourceTree = "<group>"; };
567C3E5A2520B75C0011F6E9 /* PlayerList.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = "<group>"; };
567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationSheet.swift; sourceTree = "<group>"; };
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionView.swift; sourceTree = "<group>"; };
567C3E652520B7880011F6E9 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
567C3E762520BB650011F6E9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = "<group>"; };
567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = "<group>"; };
78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCombineDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoUITests.swift; sourceTree = "<group>"; };
78E2F9E7261EEC22005D1F7F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
@@ -169,13 +154,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
78E2F9E0261EEC22005D1F7F /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
@@ -184,7 +162,6 @@
children = (
56026C9C25B8A7D000D1DF3F /* Info.plist */,
56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */,
56717251261B334D00423B6F /* PlayerRequestTests.swift */,
56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */,
);
path = GRDBCombineDemoTests;
@@ -214,7 +191,6 @@
567C3E292520B7000011F6E9 /* GRDB.xcodeproj */,
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */,
56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */,
78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */,
567C3E172520B6DE0011F6E9 /* Products */,
567C3E4D2520B70E0011F6E9 /* Frameworks */,
);
@@ -225,7 +201,6 @@
children = (
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */,
56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */,
78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */,
);
name = Products;
sourceTree = "<group>";
@@ -237,11 +212,10 @@
567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */,
567C3E542520B75C0011F6E9 /* Persistence.swift */,
567C3E532520B75C0011F6E9 /* Player.swift */,
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */,
56717229261A185300423B6F /* Query.swift */,
567C3E1F2520B6DF0011F6E9 /* Preview Content */,
56185BC125B8047D00B9C30F /* Resources */,
56185BC225B8048B00B9C30F /* Support */,
567C3E552520B75C0011F6E9 /* ViewModels */,
567C3E582520B75C0011F6E9 /* Views */,
);
path = GRDBCombineDemo;
@@ -277,27 +251,26 @@
name = Frameworks;
sourceTree = "<group>";
};
567C3E552520B75C0011F6E9 /* ViewModels */ = {
isa = PBXGroup;
children = (
567C3E562520B75C0011F6E9 /* PlayerListViewModel.swift */,
567C3E572520B75C0011F6E9 /* PlayerFormViewModel.swift */,
);
path = ViewModels;
sourceTree = "<group>";
};
567C3E582520B75C0011F6E9 /* Views */ = {
isa = PBXGroup;
children = (
567C3E5A2520B75C0011F6E9 /* AppView.swift */,
567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */,
567C3E592520B75C0011F6E9 /* PlayerForm.swift */,
567C3E5A2520B75C0011F6E9 /* PlayerList.swift */,
567C3E5B2520B75C0011F6E9 /* PlayerCreationSheet.swift */,
567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */,
567C3E592520B75C0011F6E9 /* PlayerFormView.swift */,
56717239261B23C800423B6F /* PlayerList.swift */,
);
path = Views;
sourceTree = "<group>";
};
78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */ = {
isa = PBXGroup;
children = (
78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */,
78E2F9E7261EEC22005D1F7F /* Info.plist */,
);
path = GRDBCombineDemoUITests;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
@@ -338,31 +311,13 @@
productReference = 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */;
productType = "com.apple.product-type.application";
};
78E2F9E2261EEC22005D1F7F /* GRDBCombineDemoUITests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoUITests" */;
buildPhases = (
78E2F9DF261EEC22005D1F7F /* Sources */,
78E2F9E0261EEC22005D1F7F /* Frameworks */,
78E2F9E1261EEC22005D1F7F /* Resources */,
);
buildRules = (
);
dependencies = (
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */,
);
name = GRDBCombineDemoUITests;
productName = GRDBCombineDemoUITests;
productReference = 78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */;
productType = "com.apple.product-type.bundle.ui-testing";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
567C3E0E2520B6DE0011F6E9 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 1250;
LastSwiftUpdateCheck = 1230;
LastUpgradeCheck = 1200;
TargetAttributes = {
56026C9725B8A7D000D1DF3F = {
@@ -372,10 +327,6 @@
567C3E152520B6DE0011F6E9 = {
CreatedOnToolsVersion = 12.0;
};
78E2F9E2261EEC22005D1F7F = {
CreatedOnToolsVersion = 12.5;
TestTargetID = 567C3E152520B6DE0011F6E9;
};
};
};
buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */;
@@ -399,7 +350,6 @@
targets = (
567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */,
56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */,
78E2F9E2261EEC22005D1F7F /* GRDBCombineDemoUITests */,
);
};
/* End PBXProject section */
@@ -482,13 +432,6 @@
);
runOnlyForDeploymentPostprocessing = 0;
};
78E2F9E1261EEC22005D1F7F /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
@@ -498,7 +441,6 @@
files = (
56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */,
56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */,
56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -506,25 +448,16 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
5671722A261A185300423B6F /* Query.swift in Sources */,
567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */,
567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */,
56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */,
5671723A261B23C800423B6F /* PlayerList.swift in Sources */,
567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */,
567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */,
567C3E612520B75D0011F6E9 /* PlayerForm.swift in Sources */,
567C3E632520B75D0011F6E9 /* PlayerCreationSheet.swift in Sources */,
567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */,
567C3E622520B75D0011F6E9 /* AppView.swift in Sources */,
567C3E622520B75D0011F6E9 /* PlayerList.swift in Sources */,
567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */,
567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
78E2F9DF261EEC22005D1F7F /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */,
567C3E5F2520B75C0011F6E9 /* PlayerListViewModel.swift in Sources */,
567C3E602520B75C0011F6E9 /* PlayerFormViewModel.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -541,11 +474,6 @@
name = GRDBiOS;
targetProxy = 567C3E512520B71C0011F6E9 /* PBXContainerItemProxy */;
};
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */;
targetProxy = 78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
@@ -731,7 +659,7 @@
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\"";
DEVELOPMENT_TEAM = "";
DEVELOPMENT_TEAM = AMD8W895CT;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
@@ -753,7 +681,7 @@
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\"";
DEVELOPMENT_TEAM = "";
DEVELOPMENT_TEAM = AMD8W895CT;
ENABLE_PREVIEWS = YES;
INFOPLIST_FILE = GRDBCombineDemo/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 14.0;
@@ -768,44 +696,6 @@
};
name = Release;
};
78E2F9EA261EEC22005D1F7F /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = GRDBCombineDemoUITests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBCombineDemoUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_TARGET_NAME = GRDBCombineDemo;
};
name = Debug;
};
78E2F9EB261EEC22005D1F7F /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
DEVELOPMENT_TEAM = "";
INFOPLIST_FILE = GRDBCombineDemoUITests/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
"@loader_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBCombineDemoUITests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
TEST_TARGET_NAME = GRDBCombineDemo;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
@@ -836,15 +726,6 @@
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoUITests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
78E2F9EA261EEC22005D1F7F /* Debug */,
78E2F9EB261EEC22005D1F7F /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 567C3E0E2520B6DE0011F6E9 /* Project object */;
@@ -38,16 +38,6 @@
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "78E2F9E2261EEC22005D1F7F"
BuildableName = "GRDBCombineDemoUITests.xctest"
BlueprintName = "GRDBCombineDemoUITests"
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
@@ -4,7 +4,7 @@ import GRDB
/// AppDatabase lets the application access the database.
///
/// It applies the pratices recommended at
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
struct AppDatabase {
/// Creates an `AppDatabase`, and make sure the database schema is ready.
init(_ dbWriter: DatabaseWriter) throws {
@@ -17,12 +17,12 @@ struct AppDatabase {
/// Application can use a `DatabasePool`, while SwiftUI previews and tests
/// can use a fast in-memory `DatabaseQueue`.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
private let dbWriter: DatabaseWriter
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
@@ -54,25 +54,9 @@ struct AppDatabase {
// MARK: - Database Access: Writes
extension AppDatabase {
/// A validation error that prevents some players from being saved into
/// the database.
enum ValidationError: LocalizedError {
case missingName
var errorDescription: String? {
switch self {
case .missingName:
return "Please provide a name"
}
}
}
/// Saves (inserts or updates) a player. When the method returns, the
/// player is present in the database, and its id is not nil.
func savePlayer(_ player: inout Player) throws {
if player.name.isEmpty {
throw ValidationError.missingName
}
try dbWriter.write { db in
try player.save(db)
}
@@ -81,7 +65,7 @@ extension AppDatabase {
/// Delete the specified players
func deletePlayers(ids: [Int64]) throws {
try dbWriter.write { db in
_ = try Player.deleteAll(db, ids: ids)
_ = try Player.deleteAll(db, keys: ids)
}
}
@@ -128,25 +112,6 @@ extension AppDatabase {
}
}
}
static let uiTestPlayers = [
Player(id: nil, name: "Arthur", score: 5),
Player(id: nil, name: "Barbara", score: 6),
Player(id: nil, name: "Craig", score: 8),
Player(id: nil, name: "David", score: 4),
Player(id: nil, name: "Elena", score: 1),
Player(id: nil, name: "Frederik", score: 2),
Player(id: nil, name: "Gilbert", score: 7),
Player(id: nil, name: "Henriette", score: 3)]
func createPlayersForUITests() throws {
try dbWriter.write { db in
try AppDatabase.uiTestPlayers.forEach { player in
var mutablePlayer = player
try mutablePlayer.save(db)
}
}
}
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
private func createRandomPlayers(_ db: Database) throws {
@@ -160,8 +125,19 @@ extension AppDatabase {
// MARK: - Database Access: Reads
extension AppDatabase {
/// Provides a read-only access to the database
var databaseReader: DatabaseReader {
dbWriter
/// Returns a publisher that tracks changes in players ordered by name
func playersOrderedByNamePublisher() -> AnyPublisher<[Player], Error> {
ValueObservation
.tracking(Player.all().orderedByName().fetchAll)
.publisher(in: dbWriter, scheduling: .immediate)
.eraseToAnyPublisher()
}
/// Returns a publisher that tracks changes in players ordered by score
func playersOrderedByScorePublisher() -> AnyPublisher<[Player], Error> {
ValueObservation
.tracking(Player.all().orderedByScore().fetchAll)
.publisher(in: dbWriter, scheduling: .immediate)
.eraseToAnyPublisher()
}
}
@@ -1,23 +1,12 @@
import GRDB
import SwiftUI
@main
struct GRDBCombineDemoApp: App {
let appDatabase = AppDatabase.shared
var body: some Scene {
WindowGroup {
AppView().environment(\.appDatabase, AppDatabase.shared)
PlayerList(viewModel: PlayerListViewModel(database: appDatabase))
}
}
}
// Let SwiftUI views access the database through the SwiftUI environment
private struct AppDatabaseKey: EnvironmentKey {
static let defaultValue: AppDatabase? = nil
}
extension EnvironmentValues {
var appDatabase: AppDatabase? {
get { self[AppDatabaseKey.self] }
set { self[AppDatabaseKey.self] = newValue }
}
}
@@ -6,20 +6,13 @@ extension AppDatabase {
private static func makeShared() -> AppDatabase {
do {
// Pick a folder for storing the SQLite database, as well as
// Create a folder for storing the SQLite database, as well as
// the various temporary files created during normal database
// operations (https://sqlite.org/tempfiles.html).
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
// Support for tests: delete the database if requested
if CommandLine.arguments.contains("-reset") {
try? fileManager.removeItem(at: folderURL)
}
// Create the database folder if needed
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
// Connect to a database on disk
@@ -30,14 +23,8 @@ extension AppDatabase {
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
// Prepare the database with test fixtures if requested
if CommandLine.arguments.contains("-fixedTestData") {
try appDatabase.createPlayersForUITests()
} else {
// Otherwise, populate the database if it is empty, for better
// demo purpose.
try appDatabase.createRandomPlayersIfEmpty()
}
// Populate the database if it is empty, for better demo purpose.
try appDatabase.createRandomPlayersIfEmpty()
return appDatabase
} catch {
@@ -2,8 +2,7 @@ import GRDB
/// The Player struct.
///
/// Identifiable conformance supports SwiftUI list animations, and type-safe
/// GRDB primary key methods.
/// Identifiable conformance supports SwiftUI list animations.
/// Equatable conformance supports tests.
struct Player: Identifiable, Equatable {
/// The player id.
@@ -51,7 +50,7 @@ extension Player {
/// Make Player a Codable Record.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#records>
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
fileprivate enum Columns {
@@ -69,8 +68,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// Define some player requests used by the application.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
extension DerivableRequest where RowDecoder == Player {
/// A request of players ordered by name.
///
@@ -1,23 +0,0 @@
import GRDB
/// A player request defines how to feed the player list
struct PlayerRequest {
enum Ordering {
case byScore
case byName
}
var ordering: Ordering
}
/// Make `PlayerRequest` able to be used with the `@Query` property wrapper.
extension PlayerRequest: Queryable {
static var defaultValue: [Player] { [] }
func fetchValue(_ db: Database) throws -> [Player] {
switch ordering {
case .byScore: return try Player.all().orderedByScore().fetchAll(db)
case .byName: return try Player.all().orderedByName().fetchAll(db)
}
}
}
@@ -1,113 +0,0 @@
//
// Query.swift
//
// A property wrapper inspired from
// https://davedelong.com/blog/2021/04/03/core-data-and-swiftui/
//
import Combine
import GRDB
import SwiftUI
/// The protocol that feeds the `@Query` property wrapper.
protocol Queryable: Equatable {
/// The type of the fetched value
associatedtype Value
/// The default value, used whenever the database is not available
static var defaultValue: Value { get }
/// Fetches the database value
func fetchValue(_ db: Database) throws -> Value
}
/// The property wrapper that observes a database query
@propertyWrapper
struct Query<Query: Queryable>: DynamicProperty {
/// The database reader that makes it possible to observe the database
@Environment(\.appDatabase?.databaseReader) private var databaseReader: DatabaseReader?
@StateObject private var core = Core()
private var baseQuery: Query
/// The fetched value
var wrappedValue: Query.Value {
core.value ?? Query.defaultValue
}
/// A binding to the query, that lets your views modify it.
///
/// This is how the demo app changes the player ordering.
var projectedValue: Binding<Query> {
Binding(
get: { core.query ?? baseQuery },
set: {
core.usesBaseQuery = false
core.query = $0
})
}
init(_ query: Query) {
baseQuery = query
}
func update() {
guard let databaseReader = databaseReader else {
fatalError("Attempting to use @Query without any database in the environment")
}
// Feed core with necessary information, and make sure tracking has started
if core.usesBaseQuery { core.query = baseQuery }
core.startTrackingIfNecessary(in: databaseReader)
}
private class Core: ObservableObject {
private(set) var value: Query.Value?
var databaseReader: DatabaseReader?
var usesBaseQuery = true
var query: Query? {
willSet {
if query != newValue {
// Stop tracking, and tell SwiftUI about the update
objectWillChange.send()
cancellable = nil
}
}
}
private var cancellable: AnyCancellable?
init() { }
func startTrackingIfNecessary(in databaseReader: DatabaseReader) {
if databaseReader !== self.databaseReader {
// Database has changed. Stop tracking.
self.databaseReader = databaseReader
cancellable = nil
}
guard let query = query else {
// No query set
return
}
guard cancellable == nil else {
// Already tracking
return
}
cancellable = ValueObservation
.tracking(query.fetchValue)
.publisher(
in: databaseReader,
scheduling: .immediate)
.sink(
receiveCompletion: { _ in
// Ignore errors
},
receiveValue: { [weak self] value in
guard let self = self else { return }
// Tell SwiftUI about the new value
self.objectWillChange.send()
self.value = value
})
}
}
}
@@ -0,0 +1,67 @@
import Combine
import Foundation
/// The view model that validates and saves an edited player into the database.
///
/// It feeds `PlayerForm`, `PlayerCreationSheet` and `PlayerEditionView`.
final class PlayerFormViewModel: ObservableObject {
/// A validation error that prevents the player from being saved into
/// the database.
enum ValidationError: LocalizedError {
case missingName
var errorDescription: String? {
switch self {
case .missingName:
return "Please give a name to this player."
}
}
}
@Published var name: String = ""
@Published var score: String = ""
private let database: AppDatabase
private var player: Player
init(database: AppDatabase, player: Player) {
self.database = database
self.player = player
updateViewFromPlayer()
}
// MARK: - Manage the Player Form
/// Validates and saves the player into the database.
func savePlayer() throws {
if name.isEmpty {
throw ValidationError.missingName
}
player.name = name
player.score = Int(score) ?? 0
try database.savePlayer(&player)
}
/// Resets form values to the original player values.
func reset() {
updateViewFromPlayer()
}
/// Edits a new player
func editNewPlayer() {
player = .new()
updateViewFromPlayer()
}
// MARK: - Private
private func updateViewFromPlayer() {
self.name = player.name
if player.score == 0 && player.id == nil {
// Avoid displaying "0" for a new player: it does not look good.
self.score = ""
} else {
self.score = "\(player.score)"
}
}
}
@@ -0,0 +1,118 @@
import Combine
import Foundation
/// The view model that feeds `PlayerList`, and performs list modifications
/// in the database.
final class PlayerListViewModel: ObservableObject {
enum Ordering {
case byScore
case byName
}
struct PlayerList {
var players: [Player]
var animatedChanges: Bool
}
/// The list ordering
@Published var ordering: Ordering = .byScore
/// The players in the list
@Published var playerList = PlayerList(players: [], animatedChanges: false)
/// The view model that edits a new player
let newPlayerViewModel: PlayerFormViewModel
private let database: AppDatabase
private var playersCancellable: AnyCancellable?
init(database: AppDatabase) {
self.database = database
newPlayerViewModel = PlayerFormViewModel(database: database, player: .new())
playersCancellable = playersPublisher(in: database)
.scan(nil) { (previousList: PlayerList?, players: [Player]) in
if previousList == nil {
// Do not animate first view update
return PlayerList(players: players, animatedChanges: false)
} else {
return PlayerList(players: players, animatedChanges: true)
}
}
.compactMap { $0 }
.sink { [weak self] playerList in
self?.playerList = playerList
}
}
// MARK: - Players List Management
/// Deletes all players
func deleteAllPlayers() {
// Eventual error presentation is left as an exercise for the reader.
try! database.deleteAllPlayers()
}
func deletePlayers(atOffsets offsets: IndexSet) {
// Eventual error presentation is left as an exercise for the reader.
let playerIDs = offsets.compactMap { playerList.players[$0].id }
try! database.deletePlayers(ids: playerIDs)
}
/// Refreshes the list of players
func refreshPlayers() {
// Eventual error presentation is left as an exercise for the reader.
try! database.refreshPlayers()
}
/// Spawns many concurrent database updates, for demo purpose
func stressTest() {
for _ in 0..<50 {
DispatchQueue.global().async {
self.refreshPlayers()
}
}
}
// MARK: - Change Player Ordering
/// Toggles between the available orderings
func toggleOrdering() {
switch ordering {
case .byName:
ordering = .byScore
case .byScore:
ordering = .byName
}
}
// MARK: - Player Edition
/// Returns a view model suitable for editing a player.
func formViewModel(for player: Player) -> PlayerFormViewModel {
PlayerFormViewModel(database: database, player: player)
}
// MARK: - Private
/// Returns a publisher of the players in the list
private func playersPublisher(in database: AppDatabase) -> AnyPublisher<[Player], Never> {
// Players depend on the current ordering
$ordering.map { ordering -> AnyPublisher<[Player], Error> in
switch ordering {
case .byScore:
return database.playersOrderedByScorePublisher()
case .byName:
return database.playersOrderedByNamePublisher()
}
}
.map { playersPublisher in
// Turn database errors into an empty players list.
// Eventual error presentation is left as an exercise for the reader.
playersPublisher.catch { error in
Just<[Player]>([])
}
}
.switchToLatest()
.eraseToAnyPublisher()
}
}
@@ -1,101 +0,0 @@
import SwiftUI
/// The main application view
struct AppView: View {
/// Database access
@Environment(\.appDatabase) private var appDatabase
/// The `players` property is kept up-to-date with the list of players.
@Query(PlayerRequest(ordering: .byScore)) private var players: [Player]
/// Tracks the presentation of the player creation sheet.
@State private var newPlayerIsPresented = false
// If you want to define the query on initialization, you will prefer:
//
// @Query<PlayerRequest> private var players: [Player]
//
// init(initialOrdering: PlayerRequest.Ordering) {
// _players = Query(PlayerRequest(ordering: initialOrdering))
// }
var body: some View {
NavigationView {
PlayerList(players: players)
.navigationBarTitle(Text("\(players.count) Players"))
.navigationBarItems(
leading: HStack {
EditButton()
newPlayerButton
},
trailing: ToggleOrderingButton(ordering: $players.ordering))
.toolbar { toolbarContent }
}
}
private var toolbarContent: some ToolbarContent {
ToolbarItemGroup(placement: .bottomBar) {
Button(
action: { try? appDatabase?.deleteAllPlayers() },
label: { Image(systemName: "trash").imageScale(.large) })
Spacer()
Button(
action: { try? appDatabase?.refreshPlayers() },
label: { Image(systemName: "arrow.clockwise").imageScale(.large) })
}
}
/// The button that presents the player creation sheet.
private var newPlayerButton: some View {
Button(
action: { newPlayerIsPresented = true },
label: { Image(systemName: "plus") })
.accessibility(label: Text("New Player"))
.sheet(
isPresented: $newPlayerIsPresented,
content: {
PlayerCreationView(dismissAction: {
newPlayerIsPresented = false
})
})
}
}
private struct ToggleOrderingButton: View {
@Binding var ordering: PlayerRequest.Ordering
var body: some View {
switch ordering {
case .byName:
Button(
action: { ordering = .byScore },
label: {
HStack {
Text("Name")
Image(systemName: "arrowtriangle.up.fill")
}
})
case .byScore:
Button(
action: { ordering = .byName },
label: {
HStack {
Text("Score")
Image(systemName: "arrowtriangle.down.fill")
}
})
}
}
}
struct AppView_Previews: PreviewProvider {
static var previews: some View {
Group {
// Preview a database of random players
AppView().environment(\.appDatabase, .random())
// Preview an empty database
AppView().environment(\.appDatabase, .empty())
}
}
}
@@ -1,37 +1,36 @@
import SwiftUI
/// The view that creates a new player.
struct PlayerCreationView: View {
/// The Player creation sheet
struct PlayerCreationSheet: View {
/// Manages the player form
let viewModel: PlayerFormViewModel
/// Executed when user cancels or saves the new user.
let dismissAction: () -> Void
@Environment(\.appDatabase) private var appDatabase
@State private var name = ""
@State private var score = ""
@State private var errorAlertIsPresented = false
@State private var errorAlertTitle = ""
var body: some View {
NavigationView {
PlayerFormView(name: $name, score: $score)
PlayerForm(viewModel: viewModel)
.alert(
isPresented: $errorAlertIsPresented,
content: { Alert(title: Text(errorAlertTitle)) })
.navigationBarTitle("New Player")
.navigationBarItems(
leading: Button(
action: dismissAction,
action: self.dismissAction,
label: { Text("Cancel") }),
trailing: Button(
action: save,
action: self.save,
label: { Text("Save") }))
}
}
private func save() {
do {
var player = Player(id: nil, name: name, score: Int(score) ?? 0)
try appDatabase?.savePlayer(&player)
try viewModel.savePlayer()
dismissAction()
} catch {
errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred"
@@ -42,7 +41,12 @@ struct PlayerCreationView: View {
struct PlayerCreationSheet_Previews: PreviewProvider {
static var previews: some View {
PlayerCreationView(dismissAction: { })
.environment(\.appDatabase, .empty())
let viewModel = PlayerFormViewModel(
database: .empty(),
player: .new())
return PlayerCreationSheet(
viewModel: viewModel,
dismissAction: { })
}
}
@@ -1,27 +1,28 @@
import SwiftUI
/// The view that edits an existing player.
/// The Player edition view, designed to be the destination of
/// a NavigationLink.
struct PlayerEditionView: View {
@Environment(\.appDatabase) private var appDatabase
@State var player: Player
/// Manages the player form
let viewModel: PlayerFormViewModel
var body: some View {
PlayerFormView(
name: $player.name,
score: Binding(
get: { "\(player.score)" },
set: { player.score = Int($0) ?? 0 }))
.onDisappear {
// save and ignore error
try? appDatabase?.savePlayer(&player)
}
PlayerForm(viewModel: viewModel)
.onDisappear(perform: {
// Ignore validation errors
try? self.viewModel.savePlayer()
})
}
}
struct PlayerEditionView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerEditionView(player: Player.newRandom())
let viewModel = PlayerFormViewModel(
database: .empty(),
player: .newRandom())
return NavigationView {
PlayerEditionView(viewModel: viewModel)
.navigationBarTitle("Player Edition")
}
}
@@ -0,0 +1,39 @@
import SwiftUI
/// The Player editing form, embedded in both
/// `PlayerCreationSheet` and `PlayerEditionView`.
struct PlayerForm: View {
/// Manages the player form
@ObservedObject var viewModel: PlayerFormViewModel
var body: some View {
List {
TextField("Name", text: $viewModel.name)
TextField("Score", text: $viewModel.score)
.keyboardType(.numberPad)
}
.listStyle(GroupedListStyle())
// Make sure the form is reset, in case a previous edition ended
// with a validation error.
//
// The bug we want to prevent is the following:
//
// 1. Launch the app
// 2. Tap a player
// 3. Erase the name so that validation fails
// 4. Hit the back button
// 5. Tap the same player
// 6. Bug: the form displays an empty name.
.onAppear(perform: viewModel.reset)
}
}
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
let viewModel = PlayerFormViewModel(
database: .empty(),
player: .newRandom())
return PlayerForm(viewModel: viewModel)
}
}
@@ -1,31 +0,0 @@
import SwiftUI
/// The Player editing form, embedded in both
/// `PlayerCreationView` and `PlayerEditionView`.
struct PlayerFormView: View {
@Binding var name: String
@Binding var score: String
var body: some View {
List {
TextField("Name", text: $name)
.accessibility(label: Text("Player Name"))
TextField("Score", text: $score).keyboardType(.numberPad)
.accessibility(label: Text("Player Score"))
}
.listStyle(InsetGroupedListStyle())
}
}
struct PlayerFormView_Previews: PreviewProvider {
static var previews: some View {
Group {
PlayerFormView(
name: .constant(""),
score: .constant(""))
PlayerFormView(
name: .constant(Player.randomName()),
score: .constant("\(Player.randomScore())"))
}
}
}
@@ -1,35 +1,117 @@
import SwiftUI
/// The list of players
struct PlayerList: View {
/// Database access
@Environment(\.appDatabase) private var appDatabase
/// Manages the list of players
@ObservedObject var viewModel: PlayerListViewModel
/// The players in the list
var players: [Player]
/// Controls the presentation of the player creation sheet.
@State private var newPlayerIsPresented = false
var body: some View {
NavigationView {
VStack {
playerList
toolbar
}
.navigationBarTitle(Text("\(viewModel.playerList.players.count) Players"))
.navigationBarItems(
leading: HStack {
EditButton()
newPlayerButton
},
trailing: toggleOrderingButton)
}
}
private var playerList: some View {
List {
ForEach(players) { player in
NavigationLink(destination: editionView(for: player)) {
PlayerRow(player: player).animation(nil)
ForEach(viewModel.playerList.players) { player in
NavigationLink(destination: self.editionView(for: player)) {
PlayerRow(player: player)
.animation(nil)
}
}
.onDelete(perform: { offsets in
let playerIds = offsets.compactMap { players[$0].id }
try? appDatabase?.deletePlayers(ids: playerIds)
self.viewModel.deletePlayers(atOffsets: offsets)
})
}
.animation(.default)
.listStyle(PlainListStyle())
.animation(viewModel.playerList.animatedChanges ? .default : nil)
}
private var toolbar: some View {
HStack {
Button(
action: viewModel.deleteAllPlayers,
label: { Image(systemName: "trash").imageScale(.large) })
Spacer()
Button(
action: viewModel.refreshPlayers,
label: { Image(systemName: "arrow.clockwise").imageScale(.large) })
Spacer()
Button(
action: viewModel.stressTest,
label: { Image(systemName: "tornado").imageScale(.large) })
}
.padding()
}
/// The button that toggles between name/score ordering.
private var toggleOrderingButton: some View {
switch viewModel.ordering {
case .byName:
return Button(action: viewModel.toggleOrdering, label: {
HStack {
Text("Name")
Image(systemName: "arrowtriangle.up.fill")
.imageScale(.small)
}
})
case .byScore:
return Button(action: viewModel.toggleOrdering, label: {
HStack {
Text("Score")
Image(systemName: "arrowtriangle.down.fill")
.imageScale(.small)
}
})
}
}
/// The view that edits a player in the list.
private func editionView(for player: Player) -> some View {
PlayerEditionView(player: player).navigationBarTitle(player.name)
PlayerEditionView(
viewModel: viewModel.formViewModel(for: player))
.navigationBarTitle(player.name)
}
/// The button that presents the player creation sheet.
private var newPlayerButton: some View {
Button(
action: {
// Make sure we do not edit a previously created player.
self.viewModel.newPlayerViewModel.editNewPlayer()
self.newPlayerIsPresented = true
},
label: { Image(systemName: "plus").imageScale(.large) })
.sheet(
isPresented: $newPlayerIsPresented,
content: { self.newPlayerCreationSheet })
}
/// The player creation sheet.
private var newPlayerCreationSheet: some View {
PlayerCreationSheet(
viewModel: self.viewModel.newPlayerViewModel,
dismissAction: {
self.newPlayerIsPresented = false
})
}
}
private struct PlayerRow: View {
struct PlayerRow: View {
var player: Player
var body: some View {
@@ -41,14 +123,9 @@ private struct PlayerRow: View {
}
}
struct PlayerList_Previews: PreviewProvider {
struct PlayerListView_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
PlayerList(players: [
Player(id: 1, name: "Arthur", score: 100),
Player(id: 2, name: "Barbara", score: 1000),
])
.navigationTitle("Preview")
}
let viewModel = PlayerListViewModel(database: .random())
return PlayerList(viewModel: viewModel)
}
}
@@ -143,4 +143,112 @@ class AppDatabaseTests: XCTestCase {
let players = try dbQueue.read(Player.fetchAll)
XCTAssertEqual(players, [player])
}
func test_playersOrderedByNamePublisher_publishes_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we observe players and wait for the first value
let exp = expectation(description: "Players")
var players: [Player]?
let cancellable = appDatabase.playersOrderedByNamePublisher().sink { completion in
if case let .failure(error) = completion {
XCTFail("Unexpected error \(error)")
}
} receiveValue: {
players = $0
exp.fulfill()
}
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then the players are the two players ordered by name
XCTAssertEqual(players, [player1, player2])
}
func test_playersOrderedByNamePublisher_publishes_right_on_subscripion() throws {
// Our SwiftUI views have no "waiting" state, and must be fed with
// players without any delay in order to avoid any rendering glitch.
// This test makes sure `playersOrderedByNamePublisher` publishes right
// on subscription.
// Given a players database
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we observe players
var players: [Player]?
_ = appDatabase.playersOrderedByNamePublisher().sink { completion in
if case let .failure(error) = completion {
XCTFail("Unexpected error \(error)")
}
} receiveValue: {
players = $0
}
// Then the players are published right on subscription
XCTAssertNotNil(players)
}
func test_playersOrderedByScorePublisher_publishes_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we observe players and wait for the first value
let exp = expectation(description: "Players")
var players: [Player]?
let cancellable = appDatabase.playersOrderedByScorePublisher().sink { completion in
if case let .failure(error) = completion {
XCTFail("Unexpected error \(error)")
}
} receiveValue: {
players = $0
exp.fulfill()
}
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then the players are the two players ordered by score descending
XCTAssertEqual(players, [player2, player1])
}
func test_playersOrderedByScorePublisher_publishes_right_on_subscripion() throws {
// Our SwiftUI views have no "waiting" state, and must be fed with
// players without any delay in order to avoid any rendering glitch.
// This test makes sure `playersOrderedByScorePublisher` publishes right
// on subscription.
// Given a players database
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
// When we observe players
var players: [Player]?
_ = appDatabase.playersOrderedByScorePublisher().sink { completion in
if case let .failure(error) = completion {
XCTFail("Unexpected error \(error)")
}
} receiveValue: {
players = $0
}
// Then the players are published right on subscription
XCTAssertNotNil(players)
}
}
@@ -1,43 +0,0 @@
import XCTest
import GRDB
@testable import GRDBCombineDemo
class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we fetch players ordered by name
let playerRequest = PlayerRequest(ordering: .byName)
let players = try dbQueue.read(playerRequest.fetchValue)
// Then the players are the two players ordered by name
XCTAssertEqual(players, [player1, player2])
}
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
try dbQueue.write { db in
try player1.insert(db)
try player2.insert(db)
}
// When we fetch players ordered by score
let playerRequest = PlayerRequest(ordering: .byScore)
let players = try dbQueue.read(playerRequest.fetchValue)
// Then the players are the two players ordered by score descending
XCTAssertEqual(players, [player2, player1])
}
}
@@ -1,81 +0,0 @@
//
// GRDBCombineDemoUITests.swift
// GRDBCombineDemoUITests
//
// Created by Peter Steinberger on 08.04.21.
//
import XCTest
class GRDBCombineDemoUITests: XCTestCase {
override func setUpWithError() throws {
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
}
override func tearDownWithError() throws {
}
func runApp() -> XCUIApplication {
// UI tests must launch the application that they test.
let app = XCUIApplication()
// We enforce a fresh database to ensure 8 random players.
app.launchArguments = ["-reset", "-fixedTestData"]
app.launch()
return app
}
// This test, introduced in 481f6e93, tests the @Query fix added in
// 68874412. The fix expresses itself when a view defines an @Query
// property that is replaced in the view initializer, as in 481f6e93.
//
// It happens that I did not find that this particular view setup was suited
// for a demo app. The demo has to find a delicate balance, not too trivial,
// but without gratuitous complexity.
//
// I simplified the demo app in a5ffc52d, and we no longer have any view
// that defines an @Query property which is replaced in the view
// initializer. This means that this test no longer checks against
// 68874412 regressions!
//
// Whenever the @Query property wrapper ships with GRDB itself, make sure
// we test for those regressions!
func testInitialSortingIsByScore() throws {
let app = runApp()
let getFirstCell = { () -> XCUIElement in
app.tables.element(boundBy: 0).cells.element(boundBy: 0)
}
// Given default sorting, Henriette must be on top
XCTAssertEqual(getFirstCell().label, "Craig, 8 points")
// Reverse sorting will bring Arthur on top (sort by name)
app.buttons["Score"].tap()
XCTAssertEqual(getFirstCell().label, "Arthur, 5 points")
}
func testListAndAddPlayer() throws {
let app = runApp()
// Ensure we have 8 players visible
XCTAssert(app.tables.cells.count == 8)
// add a player
app.buttons["New Player"].tap()
let playerNameField = app.textFields["Player Name"]
playerNameField.tap()
playerNameField.typeText("Tim Apple")
app.buttons["Save"].tap()
// This is suboptimal, but we need to wait for the animation to finish
// A better way could be to disable animations globally,
// and/or a hook to detect when the async fetch completes.
sleep(2)
XCTAssert(app.tables.cells.count == 9)
}
}
@@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
</dict>
</plist>
@@ -3,7 +3,7 @@ Combine + SwiftUI Demo Application
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBCombineDemo/Screenshot.png" width="50%">
**This demo application is a Combine + SwiftUI application.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md).
**This demo application is a Combine + SwiftUI application, based on the MVVM design pattern.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md).
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
@@ -19,7 +19,7 @@ The topics covered in this demo are:
- [GRDBCombineDemoApp.swift](GRDBCombineDemo/GRDBCombineDemoApp.swift)
`GRDBCombineDemoApp` feeds the app views with a database, through the SwiftUI environment.
`GRDBCombineDemoApp` feeds the app views with a database.
- [AppDatabase.swift](GRDBCombineDemo/AppDatabase.swift)
@@ -31,19 +31,18 @@ The topics covered in this demo are:
- [Player.swift](GRDBCombineDemo/Player.swift)
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records).
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). It defines the database requests used by the application.
- [PlayerRequest.swift](GRDBCombineDemo/PlayerRequest.swift), [Query.swift](GRDBCombineDemo/Query.swift), [AppView.swift](GRDBCombineDemo/Views/AppView.swift)
- [PlayerList.swift](GRDBCombineDemo/Views/PlayerList.swift) and [PlayerListViewModel.swift](GRDBCombineDemo/ViewModels/PlayerListViewModel.swift)
`PlayerRequest` defines the player requests used by the app (sorted by score, or by name).
`PlayerList` is the SwiftUI view that displays the list of players, fed by `PlayerListViewModel`.
- [PlayerForm.swift](GRDBCombineDemo/Views/PlayerForm.swift), [PlayerEditionView.swift](GRDBCombineDemo/Views/PlayerEditionView.swift), [PlayerCreationSheet.swift](GRDBCombineDemo/Views/PlayerCreationSheet.swift) and [PlayerFormViewModel.swift](GRDBCombineDemo/ViewModels/PlayerFormViewModel.swift).
`PlayerRequest` feeds the `@Query` property wrapper. `@Query`, inspired by [this article](https://davedelong.com/blog/2021/04/03/core-data-and-swiftui/), allows SwiftUI views to display up-to-date database content thanks to GRDB's [ValueObservation](../../../README.md#valueobservation).
`AppView` is the SwiftUI view that uses `@Query` in order to feed its player list.
`PlayerForm` is the SwiftUI view that displays a Player editing form. It is embedded in `PlayerEditionView` and `PlayerCreationSheet`, two SwiftUI views that edit or create a player. All those views are fed by `PlayerFormViewModel`.
- [GRDBCombineDemoTests](GRDBCombineDemoTests)
- Test the database schema
- Test the `Player` record and its requests
- Test the `PlayerRequest` methods that feed the list of players.
- Test the `AppDatabase` methods that let the app access the database.
@@ -78,10 +78,8 @@
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<RemoteRunnable
runnableDebuggingMode = "2"
BundleIdentifier = "com.apple.Carousel"
RemotePath = "/GRDBDemoiOS">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
@@ -89,7 +87,7 @@
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</RemoteRunnable>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -97,10 +95,8 @@
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<RemoteRunnable
runnableDebuggingMode = "2"
BundleIdentifier = "com.apple.Carousel"
RemotePath = "/GRDBDemoiOS">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
@@ -108,16 +104,7 @@
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</RemoteRunnable>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "568E5FBE1E926430002582E0"
BuildableName = "GRDBDemoWatchOS.app"
BlueprintName = "GRDBDemoWatchOS"
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</MacroExpansion>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
@@ -3,7 +3,7 @@ import GRDB
/// AppDatabase lets the application access the database.
///
/// It applies the pratices recommended at
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
final class AppDatabase {
/// Creates an `AppDatabase`, and make sure the database schema is ready.
init(_ dbWriter: DatabaseWriter) throws {
@@ -16,12 +16,12 @@ final class AppDatabase {
/// Application can use a `DatabasePool`, and tests can use a fast
/// in-memory `DatabaseQueue`.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
private let dbWriter: DatabaseWriter
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
@@ -64,7 +64,7 @@ extension AppDatabase {
/// Delete the specified players
func deletePlayers(ids: [Int64]) throws {
try dbWriter.write { db in
_ = try Player.deleteAll(db, ids: ids)
_ = try Player.deleteAll(db, keys: ids)
}
}
@@ -2,9 +2,8 @@ import GRDB
/// The Player struct.
///
/// Identifiable conformance supports type-safe GRDB primary key methods.
/// Hashable conformance supports table view updates
struct Player: Identifiable, Hashable {
struct Player: Hashable {
/// The player id.
///
/// Int64 is the recommended type for auto-incremented database ids.
@@ -50,7 +49,7 @@ extension Player {
/// Make Player a Codable Record.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#records>
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
// Define database columns from CodingKeys
fileprivate enum Columns {
@@ -68,8 +67,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// Define some player requests used by the application.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
extension DerivableRequest where RowDecoder == Player {
/// A request of players ordered by name.
///
@@ -144,6 +144,34 @@ class AppDatabaseTests: XCTestCase {
XCTAssertEqual(players, [player])
}
func test_observePlayerCount() throws {
// Given a players database that contains one player
let dbQueue = DatabaseQueue()
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
try player.insert(db)
}
// When we observe the player count and wait for the first value
let exp = expectation(description: "Player count")
var count: Int?
let cancellable = appDatabase.observePlayerCount(
onError: { error in
XCTFail("Unexpected error \(error)")
},
onChange: {
count = $0
exp.fulfill()
})
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
}
// Then that first value is one
XCTAssertEqual(count, 1)
}
func test_observePlayersOrderedByName() throws {
// Given a players database that contains two players
let dbQueue = DatabaseQueue()
+1 -1
View File
@@ -3,7 +3,7 @@ UIKit Demo Application
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png" width="50%">
**This demo application is a storyboard-based UIKit application.** For a demo application that uses Combine and SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
**This demo application is a storyboard-based UIKit application, based on the MVC design pattern.** For a demo application that uses Combine and SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md).
> :point_up: **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration.
+3 -2
View File
@@ -1,5 +1,6 @@
Demo Applications
=================
- [UIKit Demo Application](GRDBDemoiOS/README.md): a storyboard-based UIKit application.
- [Combine + SwiftUI Demo Application](GRDBCombineDemo/README.md): a Combine + SwiftUI application.
- [UIKit Demo Application](GRDBDemoiOS/README.md): a storyboard-based UIKit application, based on the MVC design pattern.
- [Combine + SwiftUI Demo Application](GRDBCombineDemo/README.md): a Combine + SwiftUI application, based on the MVVM design pattern.
+2 -2
View File
@@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html):
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.3/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html):
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.3/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
+4 -4
View File
@@ -387,16 +387,16 @@ let publisher = observation
> :question: This change makes it possible to concatenate subqueries with the UNION operator.
4. In order to extract raw SQL string from an [SQL literal], you now need a database connection:
4. In order to extract raw SQL string from an [SQLLiteral], you now need a database connection:
```swift
// BEFORE: GRDB 4
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
// BEFORE: GRDB 4
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(query.arguments) // prints ["O'Brien", 42]
// NEW: GRDB 5
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try dbQueue.read(query.build)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
@@ -506,7 +506,7 @@ let publisher = observation
[Custom SQL functions]: ../README.md#custom-sql-functions
[Batch updates]: ../README.md#update-requests
[SQL Interpolation]: SQLInterpolation.md
[SQL literal]: SQLInterpolation.md#sql-literal
[SQLLiteral]: SQLInterpolation.md#sqlliteral
[SQLRequest]: ../README.md#custom-requests
[QueryInterfaceRequest]: ../README.md#requests
[Combine publishers]: Combine.md
@@ -9,8 +9,6 @@ To support this guide, we'll design a simple library application that lets the u
- [Trust SQLite More Than Yourself]
- [Persistable Record Types are Responsible for Their Tables]
- [Record Types Hide Intimate Database Details]
- [Singleton Records]
- [Define Record Requests]
- [Compose Records]
- [How to Design Database Managers]
@@ -98,13 +96,13 @@ Define one record type per database table, and make it adopt a [PersistableRecor
In this sample code, we'll use Codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
```swift
struct Author: Codable, Identifiable {
struct Author: Codable {
var id: Int64?
var name: String
var country: String?
}
struct Book: Codable, Identifiable {
struct Book: Codable {
var id: Int64?
var authorId: Int64
var title: String
@@ -140,108 +138,12 @@ That's it. The `Author` type can read and write in the `author` database table.
> print(author.id!) // Guaranteed non-nil id
> }
> ```
>
> :bulb: **Tip**: When the database table has a single-column primary key, have your record type adopt the standard [Identifiable] protocol. This allows GRDB to define type-safe id-related methods:
>
> ```swift
> let authorID: Int64 = ...
> let author: Author? = try dbQueue.read { db in
> try Author.fetchOne(db, id: authorID)
> }
> ```
Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table!
Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*.
Applying the **[Single Responsibility Principle]** has a consequence: don't even try to have an author responsible for its books. Don't add a `books: [Book]` property in Author. Don't let Author write in the `book` table. When a new fellow coworker joins your team and asks you "who is saving books in the database?", you don't want to answer "it depends." You want to confidently answer: "the Book type".
## Record Types Hide Intimate Database Details
The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.)
Sometimes, it happens that raw database column names and types are not a very good fit for the application.
Let's look at three examples:
1. Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. For easy debugging of the database contents, a book kind is represented as a string ("novel", "essay", etc.):
```swift
try db.create(table: "book") { t in
...
t.column("kind", .text).notNull()
}
```
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We want an enum instead:
```swift
struct Book: Codable {
enum Kind: String, Codable {
case novel, poems, essay, play
}
var id: Int64?
var authorId: Int64
var title: String
var kind: Kind
}
```
In order to make it possible to use `Book.Kind` in book requests (see [Define Record Requests] below), we add this conformance:
```swift
extension Book.Kind: DatabaseValueConvertible { }
```
> :bulb: Records can pick the best suited [Value] type for their column properties (Bool, Int, String, Date, etc.) Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database.
2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
When this happens, keep column properties private, and provide sensible accessors instead:
```swift
struct Place: Codable {
var id: Int64?
var name: String
private var latitude: CLLocationDegrees
private var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D {
get {
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
}
```
> :bulb: Private properties make it possible to hide raw columns from the rest of the application.
3. The record below exposes a `price: Decimal` property ($12.00), backed by an integer column that stores a quantity of cents (1200). An integer column is preferred because it allows SQLite to compute exact sums of prices.
```swift
struct Product: Codable {
var id: Int64?
var name: String
private var priceCents: Int
var price: Decimal {
get { Decimal(priceCents) / 100 }
set { priceCents = NSDecimalNumber(decimal: newValue * 100).intValue }
}
}
```
> :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface.
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#customizing-the-persistence-methods) before they enter the database.
## Singleton Records
**Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row.
The recommended setup for such records is described in the [Single-Row Tables](SingleRowTables.md) guide. Go check it, and come back when you're done!
> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table.
## Define Record Requests
@@ -264,7 +166,7 @@ extension Author {
}
```
Otherwise, declare a plain `String` enum that conforms to the `ColumnExpression` protocol:
Otherwise, declare a plain String enum that conforms to the ColumnExpression protocol:
```swift
// For a non-codable record
@@ -276,50 +178,31 @@ extension Author {
}
```
Those columns let you define requests:
```swift
try dbQueue.read { db in
// Order authors by name, in a localized case-insensitive fashion
let sortedAuthors: [Author] = try Author.all()
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
.fetchAll(db)
// French authors
let frenchAuthors: [Author] = try Author.all()
.filter(Author.Columns.country == "France")
.fetchAll(db)
}
```
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable [testability](DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift).
The `DerivableRequest` protocol generally lets you filter, sort, and join or include associations (we'll talk about associations in the [Compose Records] chapter below).
To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc:
Here is how you define those requests:
```swift
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
// Some requests of Author --------------------v
extension DerivableRequest where RowDecoder == Author {
/// Order authors by name, in a localized case-insensitive fashion
/// Returns a request for all authors ordered by name, in a localized
/// case-insensitive fashion
func orderByName() -> Self {
let name = Author.Columns.name
return order(name.collating(.localizedCaseInsensitiveCompare))
}
/// Filters authors from a country
/// Returns a request for all authors from a country
func filter(country: String) -> Self {
filter(Author.Columns.country == country)
}
/// Filters authors with at least one book
func havingBooks() -> Self {
having(Author.books.isEmpty == false)
}
}
```
Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style:
Those methods defined on the `DerivableRequest` protocol hide intimate database details. They allow you to compose database requests in a fluent style:
```swift
try dbQueue.read { db in
@@ -331,55 +214,72 @@ try dbQueue.read { db in
.filter(country: "France")
.fetchAll(db)
let sortedSpanishAuthorsHavingBooks: [Author] = try Author.all()
let sortedSpanishAuthors: [Author] = try Author.all()
.filter(country: "Spain")
.havingBooks()
.orderByName()
.fetchAll(db)
}
```
Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors:
Those customized request methods are also available on record associations, because associations conform to the `DerivableRequest` protocol:
```swift
// Book requests ~~~~~~~~~~~~~~~~~~~~~~~~
// Some requests of Book
extension DerivableRequest where RowDecoder == Book {
/// Filters books by kind
func filter(kind: Book.Kind) -> Self {
filter(Book.Columns.kind == kind)
}
/// Filters books from a country
/// Returns a request for all books from a country
func filter(authorCountry: String) -> Self {
// Books do not have any country column. But their author has one.
// A book is from a country if it can be joined to an author from this country:
// A book is from a country if it can be
// joined with an author from that country:
// ---------------------------v
joining(required: Book.author.filter(country: authorCountry))
}
}
try dbQueue.read { db in
let italianNovels: [Book] = try Book.all()
.filter(kind: .novel)
let italianBooks = try Book.all()
.filter(authorCountry: "Italy")
.fetchAll(db)
}
```
Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example:
Not *every requests* can be expressed on `DerivableRequest`. For example, [Association Aggregates] are out of scope. When this happens, define your requests in a constrained extension to `QueryInterfaceRequest`:
```swift
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
// More requests of Author -------------------------v
extension QueryInterfaceRequest where RowDecoder == Author {
// Selects author ids
func id() -> QueryInterfaceRequest<Int64> {
select(Author.Columns.id)
/// Returns a request for all authors with at least one book
func havingBooks() -> QueryInterfaceRequest<Author> {
having(Author.books.isEmpty == false)
}
}
// IDs of French authors
let ids: [Int64] = try Author.all().filter(country: "France").id().fetchAll(db)
```
Those requests defined on `QueryInterfaceRequest` still compose fluently:
```swift
try dbQueue.read { db in
let sortedFrenchAuthorsHavingBooks = try Author.all()
.filter(country: "France")
.havingBooks() // <-
.orderByName()
.fetchAll(db)
}
```
Finally, when it happens that a request only makes sense when defined on the Record type itself, just go ahead and define a static method or property of your Record type:
```swift
extension MySingletonRecord {
/// The one any only record stored in the database
static let shared = all().limit(1)
}
let singleton = try dbQueue.read { db
try MySingletonRecord.shared.fetchOne(db)
}
```
## Compose Records
We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
@@ -458,7 +358,7 @@ Granted with primitive and derived record types, your application will load the
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
let request = Author
.filter(id: authorId)
.filter(key: authorId)
.including(all: Author.books)
return try AuthorInfo.fetchOne(db, request)
}
@@ -474,7 +374,7 @@ Granted with primitive and derived record types, your application will load the
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
let request = Book
.filter(id: bookId)
.filter(key: bookId)
.including(required: Book.author)
return try BookInfo.fetchOne(db, request)
}
@@ -511,7 +411,7 @@ Those properties provide an alternative way to feed our application:
}
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
guard let author = try Author.fetchOne(db, id: authorId) else {
guard let author = try Author.fetchOne(db, key: authorId) else {
return nil
}
let books = try author.books.fetchAll(db)
@@ -530,7 +430,7 @@ Those properties provide an alternative way to feed our application:
}
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
guard let book = try Book.fetchOne(db, id: bookId) else {
guard let book = try Book.fetchOne(db, key: bookId) else {
return nil
}
guard let author = try book.author.fetchOne(db) else {
@@ -572,7 +472,7 @@ class NaiveLibraryManager {
func author(id: Int64) -> Author? {
do {
return try dbQueue.read { db in
try Author.fetchOne(db, id: id)
try Author.fetchOne(db, key: id)
}
} catch {
return nil
@@ -582,7 +482,7 @@ class NaiveLibraryManager {
func book(id: Int64) -> Book? {
do {
return try dbQueue.read { db in
try Book.fetchOne(db, id: id)
try Book.fetchOne(db, key: id)
}
} catch {
return nil
@@ -631,13 +531,13 @@ class ImprovedLibraryManager {
func author(id: Int64) throws -> Author? {
try dbQueue.read { db in
try Author.fetchOne(db, id: id)
try Author.fetchOne(db, key: id)
}
}
func book(id: Int64) throws -> Book? {
try dbQueue.read { db in
try Book.fetchOne(db, id: id)
try Book.fetchOne(db, key: id)
}
}
@@ -711,7 +611,7 @@ extension LibraryManager {
func bookInfo(bookId: Int64) throws -> BookInfo? {
try dbQueue.read { db in
guard let book = try Book.fetchOne(db, id: bookId) else {
guard let book = try Book.fetchOne(db, key: bookId) else {
return nil
}
guard let author = try book.author.fetchOne(db) else {
@@ -731,7 +631,7 @@ extension LibraryManager {
func authorInfo(authorId: Int64) throws -> AuthorInfo? {
try dbQueue.read { db in
guard let author = try Author.fetchOne(db, id: authorId) else {
guard let author = try Author.fetchOne(db, key: authorId) else {
return nil
}
let books = try author.books.fetchAll(db)
@@ -796,6 +696,7 @@ Instead, have a look at [Database Observation]:
[Django]: https://docs.djangoproject.com/en/2.0/topics/db/
[record protocols]: ../README.md#record-protocols-overview
[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns
[Single Responsibility Principle]: https://en.wikipedia.org/wiki/Single_responsibility_principle
[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
[Why Adopt GRDB?]: WhyAdoptGRDB.md
@@ -812,8 +713,6 @@ Instead, have a look at [Database Observation]:
[TransactionObserver]: ../README.md#transactionobserver-protocol
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details
[Singleton Records]: #singleton-records
[Define Record Requests]: #define-record-requests
[Compose Records]: #compose-records
[How to Design Database Managers]: #how-to-design-database-managers
@@ -828,5 +727,3 @@ Instead, have a look at [Database Observation]:
[Codable Record]: ../README.md#codable-records
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[Combine Support]: Combine.md
[Value]: ../README.md#values
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
Binary file not shown.

Before

Width:  |  Height:  |  Size: 498 KiB

+1 -23
View File
@@ -68,7 +68,7 @@ try dbQueue.read { db in
}
```
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.9/Structs/DatabaseMigrator.html) for more migrator methods.
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.3/Structs/DatabaseMigrator.html) for more migrator methods.
## The `eraseDatabaseOnSchemaChange` Option
@@ -119,26 +119,4 @@ migrator.registerMigration("AddNotNullCheckOnName") { db in
}
```
## Asynchronous Migrations
`DatabaseMigrator` provides two ways to migrate a database in an asynchronous way.
The `asyncMigrate(_:completion:)` method:
```swift
// Completes in a protected dispatch queue that can write in the database
migrator.asyncMigrate(dbQueue, completion: { db, error in
if let error = error {
// Some error occurred during migrations
}
})
```
The `migratePublisher(_:receiveOn:)` [Combine](https://developer.apple.com/documentation/combine) publisher:
```swift
// DatabasePublishers.Migrate
let publisher = migrator.migratePublisher(dbQueue)
```
This publisher completes on the main queue, unless you provide a specific [scheduler](https://developer.apple.com/documentation/combine/scheduler) to the `receiveOn` argument.
@@ -212,30 +212,30 @@ extension Base: MyDatabaseDecoder {
//: **prepared statement**:
//:
//: try dbQueue.read { db in
//: let statement = try db.makeStatement(sql: "SELECT ...")
//: let statement = try db.makeSelectStatement(sql: "SELECT ...")
//: try Base.fetchCursor(statement) // Cursor of Base
//: try Base.fetchAll(statement) // [Base]
//: try Base.fetchOne(statement) // Base?
//: }
extension MyDatabaseDecoder {
// MARK: - Fetch from Prepared Statement
// MARK: - Fetch from SelectStatement
// Statement, StatementArguments, and RowAdapter are the fundamental
// SelectStatement, StatementArguments, and RowAdapter are the fundamental
// fetching parameters of GRDB. Make sure to accept them all:
static func fetchCursor(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
// Turn the cursor of raw rows into a cursor of decoded rows
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
self.decode(row: $0)
}
}
static func fetchAll(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
// Turn the cursor into an Array
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
static func fetchOne(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
// Consume the first value of the cursor
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next()
}
@@ -243,7 +243,7 @@ extension MyDatabaseDecoder {
try dbQueue.read { db in
print("> Fetch from prepared statement")
let statement = try db.makeStatement(sql: "SELECT * FROM base")
let statement = try db.makeSelectStatement(sql: "SELECT * FROM base")
let bases = try Base.fetchAll(statement)
for base in bases {
print(base.description)
@@ -422,7 +422,7 @@ protocol ContextFetchableRecord {
extension ContextFetchableRecord {
static func fetchCursor(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil,
context: Context)
@@ -454,7 +454,7 @@ protocol FailableFetchableRecord {
extension FailableFetchableRecord {
static func fetchCursor(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> MapCursor<RowCursor, Self>
@@ -8,39 +8,16 @@ configuration.prepareDatabase { db in
}
let dbQueue = DatabaseQueue(configuration: configuration)
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
var id: Int64?
var name: String
var score: Int
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
try dbQueue.write { db in
try! dbQueue.inDatabase { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("score", .integer).notNull()
}
do {
var player = Player(id: nil, name: "Arthur", score: 100)
try player.insert(db)
player = Player(id: nil, name: "Barbara", score: 100)
try player.insert(db)
}
try db.execute(sql: "INSERT INTO player (name, score) VALUES (?, ?)", arguments: ["Arthur", 1000])
try db.execute(sql: "INSERT INTO player (name, score) VALUES (?, ?)", arguments: ["Barbara", 1000])
do {
let players = try Player.fetchAll(db)
for player in players {
print(player)
}
}
do {
let count = try Player.fetchCount(db)
print(count)
}
let names = try String.fetchAll(db, sql: "SELECT name FROM player")
print(names)
}
-632
View File
@@ -1,632 +0,0 @@
Query Interface Organization
============================
**The [query interface] is a Swift API that approximates the [SQLite SELECT query grammar](https://sqlite.org/lang_select.html) through a hierarchy of values and protocols.**
This document exposes its inner organization, so that you can leverage the most of those types and protocols when you want it.
In the diagram below, protocols are pale blue and have rounded corners, and standard types are grey rectangles. Solid arrows read "inherits from", and dashed arrows read "produces". Generic types are marked as such, as well as "PATs" (protocols with associated types).
<img src="https://github.com/groue/GRDB.swift/raw/development/Documentation/Images/QueryInterfaceOrganization2.png" width="100%">
Diagram items are described below:
- [Association]
- [Column]
- [ColumnExpression]
- [DatabaseRegionConvertible]
- [DatabaseValue]
- [DatabaseValueConvertible]
- [DerivableRequest]
- [FetchRequest]
- [Int, String, Date…]
- [QueryInterfaceRequest]
- [SQL]
- [SQLExpression]
- [SQLExpressible]
- [SQLOrderingTerm]
- [SQLOrdering]
- [SQLRequest]
- [SQLSelectable]
- [SQLSelection]
- [SQLSpecificExpressible]
- [SQLSubquery]
- [SQLSubqueryable]
---
### Association
`Association` is the protocol for all [associations]. It is adopted by `BelongsToAssociation`, `HasManyAssociation`, etc. It conforms to [DerivableRequest].
```swift
protocol Association: DerivableRequest {
associatedtype OriginRowDecoder
func forKey(_ key: String) -> Self
}
```
Association has two sub-protocols:
```swift
protocol AssociationToOne: Association { }
protocol AssociationToMany: Association { }
```
`AssociationToMany`, adopted by `HasManyAssociation` and `HasManyThroughAssociation`, leverages [association aggregates].
### Column
`Column` is the type for database columns. It conforms to [ColumnExpression].
```swift
Column("name")
Column("id")
Column.rowID
```
### ColumnExpression
`ColumnExpression` is the protocol for database columns. It is adopted by [Column]. It conforms to [SQLSpecificExpressible].
```swift
protocol ColumnExpression: SQLSpecificExpressible {
/// The name of a database column.
var name: String { get }
}
```
Columns can be used, for example, to query database rows:
```swift
let row = try Row.fetchOne(db, sql: "SELECT 'Arthur' AS name")!
let name: String = row[Column("name")] // "Arthur"
```
Columns are special expressions that allow some optimizations and niceties:
- Database observation: When a request is limited to a known list of rowids in a database table, changes applied to other rows do not trigger the observation. GRDB needs column expressions in order to apply this optimization:
```swift
// Optimized Observations
ValueObservation.tracking { db in
try Player.fetchOne(db, id: 1)
// or
try Player.filter(Column("id") == 1).fetchOne(db)
}
// Non-optimized observations
ValueObservation.tracking { db in
try SQLRequest<Player>("SELECT * FROM player WHERE id = 1").fetchOne(db)
// or
try Player.filter(sql: "id = 1").fetchOne(db)
}
```
- SQL generation: when it generates SQL queries, GRDB appends `LIMIT 1` or not, depending on the primary key and unique indexes used on the queried table. GRDB needs column expressions in order to improve its SQL generation:
```swift
// Nicer SQL
// SELECT * FROM player WHERE id = 1
try Player.fetchOne(db, id: 1)
try Player.filter(Column("id") == 1).fetchOne(db)
// Less nice SQL
// SELECT * FROM player WHERE id = 1 LIMIT 1
try Player.filter(sql: "id = 1").fetchOne(db)
```
### DatabaseRegionConvertible
`DatabaseRegionConvertible` is the protocol for observable requests. It is adopted by [FetchRequest].
```swift
protocol DatabaseRegionConvertible {
func databaseRegion(_ db: Database) throws -> DatabaseRegion
}
```
DatabaseRegionConvertible feeds [DatabaseRegionObservation], which tracks database transactions that impact a particular database region:
```swift
let request = Player.all()
let observation = DatabaseRegionObservation(tracking: request)
let observer = try observation.start(in: dbQueue) { (db: Database) in
print("Players were changed")
}
```
### DatabaseValue
`DatabaseValue` is the type for SQL values (integers, doubles, strings, blobs, and NULL). It conforms to [SQLSpecificExpressible].
You generally build a DatabaseValue from a [DatabaseValueConvertible] type:
```swift
1.databaseValue
"Hello".databaseValue
DatabaseValue.null
```
The query interface will sometimes not accept raw [SQLExpressible] values such as [Int, String, Date], etc. In this case, turn those values into DatabaseValue so that you leverage APIs that need [SQLSpecificExpressible]. For example:
```swift
// SQL: firstName || ' ' || lastName
let fullname = [
Column("firstName"),
" ".databaseValue,
Column("lastName"),
].joined(operator: .concat)
```
### DatabaseValueConvertible
`DatabaseValueConvertible` is the protocol for types that can provide [DatabaseValue]: SQL integers, doubles, strings, blobs, and NULL. It is adopted by [Int, String, Date], etc. It conforms to [SQLExpressible] because all SQL values are SQL expressions.
```swift
protocol DatabaseValueConvertible: SQLExpressible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
/// Returns a value initialized from `dbValue`, if possible.
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
}
```
### DerivableRequest
`DerivableRequest` is the protocol for query interface requests and associations that can be refined. It is adopted by [QueryInterfaceRequest] and [Association].
```swift
protocol DerivableRequest: AggregatingRequest, FilteredRequest,
JoinableRequest, OrderedRequest,
SelectionRequest, TableRequest
{
func distinct() -> Self
func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self
}
```
- `AggregatingRequest` provides grouping methods such as `groupByPrimaryKey()`
- `FilteredRequest` provides filtering methods such as `filter(expression)` or `filter(id: value)`
- `JoinableRequest` provides association methods such as `joining(required: association)` or `including(all: association)`
- `OrderedRequest` provides ordering methods such as `order(ordering)` or `reversed()`
- `SelectionRequest` provides selection methods such as `select(selection)` or `annotated(with: selection)`
- `TableRequest` provides table targeting methods such as `aliased(tableAlias)`
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) and [Associations](AssociationsBasics.md).
### FetchRequest
`FetchRequest` is the protocol for requests that can fetch. It is adopted by [QueryInterfaceRequest] and [SQLRequest]. It conforms to [SQLSubqueryable] and [DatabaseRegionConvertible].
```swift
protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible {
/// The type that tells how fetched database rows should be interpreted.
associatedtype RowDecoder
/// Returns a PreparedRequest that is ready to be executed.
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
/// Returns the number of rows fetched by the request.
func fetchCount(_ db: Database) throws -> Int
}
```
FetchRequest can fetch values from the database as long as its `RowDecoder` associated type is `Row`, a [DatabaseValueConvertible] type, or a [FetchableRecord] type.
```swift
let row: Row? = try SQLRequest<Row>("SELECT * FROM player").fetchOne(db)
let players: [Player] = try Player.all().fetchAll(db)
```
FetchRequest usually executes a single SQL query:
```swift
// SELECT * FROM player
let request = Player.all()
try request.fetchAll(db)
```
This single SQL query is exposed through `makePreparedRequest(_:forSingleResult:)`:
```swift
let request = Player.all()
let preparedRequest = try request.makePreparedRequest(db)
print(preparedRequest.statement.sql) // SELECT * FROM player
```
But not all fetch requests execute a single SQL query. A [QueryInterfaceRequest] that involves [associations] can execute several:
```swift
// SELECT * FROM player
// SELECT * FROM award WHERE playerId IN (...)
struct PlayerInfo: Decodable, FetchableRecord {
var player: Player
var awards: [Award]
}
let playerInfos = try Player
.including(all: Player.awards)
.asRequest(of: PlayerInfo.self)
.fetchAll(db)
```
Those supplementary SQL queries are an implementation detail of `PreparedRequest`, and are not currently exposed.
### Int, String, Date…
The basic value types conform to [DatabaseValueConvertible] so that they can feed database queries with [DatabaseValue]:
```swift
// SELECT * FROM player WHERE name = 'O''Brien'
// ~~~~~~~~~~
Player.filter(Column("name") == "O'Brien")
```
### QueryInterfaceRequest
`QueryInterfaceRequest` is the type of fetch requests built by the GRDB query builder. It conforms to [FetchRequest] and [DerivableRequest].
It is generic on the type of fetched values:
```swift
struct PlayerInfo: Decodable, FetchableRecord {
var player: Player
var awards: [Award]
}
// QueryInterfaceRequest<Player>
let playerRequest = Player.all()
// QueryInterfaceRequest<String>
let nameRequest = Player.select(Column("name"), as: String.self)
// QueryInterfaceRequest<PlayerInfo>
let playerInfoRequest = Player
.including(all: Player.awards)
.asRequest(of: PlayerInfo.self)
try playerRequest.fetchAll(db) // [Player]
try nameRequest.fetchAll(db) // [String]
try playerInfoRequest.fetchAll(db) // [PlayerInfo]
```
For more information on QueryInterfaceRequest, see [Requests](../README.md#requests) and [Associations](AssociationsBasics.md).
### SQL
`SQL` is the type for SQL literals that support [SQL Interpolation]. It can feed all GRDB APIs that have a `literal` argument:
```swift
let literal: SQL = "SELECT * FROM player"
let request = SQLRequest<Player>(literal: literal)
let players: [Player] = try request.fetchAll(db)
```
`SQL` conforms to [SQLSpecificExpressible], and thus behaves as an [SQLite expression](https://sqlite.org/syntax/expr.html) by default:
```swift
let literal: SQL = "name = \("O'Brien")"
let request = Player.filter(literal)
let players: [Player] = try request.fetchAll(db)
```
:warning: **Warning**: Not all SQL snippets are expressions. It is not recommended to pass `SQL` literals around, or you may end up forgetting their content, and eventually generate invalid SQL. When possible, prefer building an explicit [SQLExpression], [SQLOrdering], [SQLSelection], [SQLRequest], or [SQLSubquery], depending on what you want to express:
```swift
// SQLExpression
SQL("name = \("O'Brien")").sqlExpression
// SQLOrdering
SQL("name DESC)").sqlOrdering
// SQLSelection
SQL("score + bonus AS total)").sqlSelection
SQL("*").sqlSelection
// SQLRequest
SQLRequest<Player>(literal: "SELECT * FROM player")
// SQLSubquery
SQLRequest(literal: "SELECT * FROM player").sqlSubquery
```
### SQLExpression
`SQLExpression` is the opaque type for all [SQLite expressions](https://sqlite.org/syntax/expr.html). It adopts [SQLSpecificExpressible], and is built from [SQLExpressible].
```swift
struct SQLExpression: SQLSpecificExpressible {
// opaque implementation
}
```
Functions and methods that build an SQL expression should return an SQLExpression value:
```swift
// SELECT * FROM player WHERE LENGTH(name) > 0
let expression = length(Column("name")) > 0 // SQLExpression
Player.filter(expression)
```
When it looks like GRDB APIs are unable to build a particular expression, use [SQL]:
```swift
func date(_ value: SQLSpecificExpressible) -> SQLExpression {
SQL("DATE(\(value))").sqlExpression
}
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
```
This technique, based on [SQL Interpolation], is composable and works well even when several tables are involved. See how the `createdAt` column below is correctly attributed to the `player` table:
```swift
// SELECT player.*, team.* FROM player
// JOIN team ON team.id = player.teamId
// WHERE DATE(player.createdAt) = '2020-01-23'
let request = Player
.filter(date(Column("createdAt")) == "2020-01-23")
.including(required: Player.team)
```
### SQLExpressible
`SQLExpressible` is the protocol for all [SQLite expressions](https://sqlite.org/syntax/expr.html). It is adopted by [Column], [SQL], [SQLExpression], and also [Int, String, Date], etc. It has an `sqlExpression` property which returns an [SQLExpression].
```swift
protocol SQLExpressible {
var sqlExpression: SQLExpression { get }
}
```
SQLExpressible-conforming types include types which are not directly related to SQL, such as [Int, String, Date], etc. Because of this, SQLExpressible has limited powers that prevent misuses and API pollution. For full-fledged SQL expressions, see [SQLSpecificExpressible]. For example, compare:
```swift
Player.filter(1) // Compiler warning (will become an error in the next major release)
Player.select(1) // Compiler error
Player.order("name") // Compiler error
length("name") // Compiler error
"name".desc // Compiler error
```
```swift
Player.filter(id: 1) // OK
Player.filter(1.databaseValue) // Odd, but OK
Player.select(1.databaseValue) // Odd, but OK
Player.order(Column("name")) // OK
length(Column("name")) // OK
Column("name").desc // OK
```
### SQLOrderingTerm
`SQLOrderingTerm` is the protocol for all [SQLite ordering terms](https://sqlite.org/syntax/ordering-term.html). It is adopted by [SQLSpecificExpressible]. It has an `sqlOrdering` property which returns an [SQLOrdering].
```swift
protocol SQLOrderingTerm {
var sqlOrdering: SQLOrdering { get }
}
```
SQLOrderingTerm feeds the `order()` method of the query interface:
```swift
// SELECT * FROM player
// ORDER BY score DESC, name COLLATE ...
Player.order(
Column("score").desc,
Column("name").collating(.localizedCaseInsensitiveCompare))
```
All [SQLSpecificExpressible] values are ordering terms. [SQLExpressible] values are not: `Player.order("name")` does not compile. Instead, use:
```swift
// SELECT * FROM player ORDER BY name -- Order according to a column
Player.order(Column("name"))
// SELECT * FROM player ORDER BY 'name' -- Order according to a constant string (why not)
Player.order("name".databaseValue)
```
### SQLOrdering
`SQLOrdering` is the opaque type for all [SQLite ordering terms](https://sqlite.org/syntax/ordering-term.html). An SQLOrdering adopts and is built from [SQLOrderingTerm].
```swift
struct SQLOrdering: SQLOrderingTerm {
// opaque implementation
}
```
Functions and methods that build ordering terms should return an SQLOrdering value:
```swift
// SELECT * FROM player ORDER BY score DESC
let ordering = Column("score").desc // SQLOrdering
Player.order(ordering)
```
To build an SQLOrdering without applying any `DESC` or `ASC` qualifier, use `sqlOrdering` (from [SQLOrderingTerm], inherited by [SQLSpecificExpressible], [ColumnExpression]...):
```swift
let ordering = Column("score").sqlOrdering // SQLOrdering
```
### SQLRequest
`SQLRequest` is the type of fetch requests expressed with raw SQL. It conforms to [FetchRequest].
It is generic on the type of fetched values (which defaults to `Row`):
```swift
let rowRequest = SQLRequest(sql: "SELECT * FROM player") // SQLRequest<Row>
let playerRequest = SQLRequest<Player>(sql: "SELECT * FROM player") // SQLRequest<Player>
let nameRequest = SQLRequest<String>(sql: "SELECT name FROM player") // SQLRequest<String>
try rowRequest.fetchAll(db) // [Row]
try playerRequest.fetchAll(db) // [Player]
try nameRequest.fetchAll(db) // [String]
try rowRequest.fetchOne(db) // Row?
try playerRequest.fetchOne(db) // Player?
try nameRequest.fetchOne(db) // String?
```
SQLRequest supports [SQL Interpolation]:
```swift
// SELECT * FROM player WHERE name = 'O''Brien'
let playerRequest: SQLRequest<Player> = """
SELECT * FROM player WHERE name = \("O'Brien")
"""
```
### SQLSelectable
`SQLSelectable` is the protocol for all [SQLite result columns](https://sqlite.org/syntax/result-column.html). It is adopted by [SQLSpecificExpressible]. It has an `sqlSelection` property which returns an [SQLSelection].
```swift
protocol SQLSelectable {
var sqlSelection: SQLSelection { get }
}
```
SQLSelectable feeds the `select()` method of the query interface:
```swift
Player.select(AllColumns())
Player.select(Column("name"), Column("score"))
```
All [SQLSpecificExpressible] values are selectable. Other selectable values are:
```swift
// SELECT * FROM player
Player.select(AllColumns())
// SELECT MAX(score) AS maxScore FROM player
Player.select(max(Column("score")).forKey("maxScore"))
```
[SQLExpressible] values are not selectable: `Player.select("name")` does not compile. Instead, use:
```swift
// SELECT name FROM player -- Selects a column
Player.select(Column("name"))
// SELECT 'name' FROM player -- Selects a constant string (why not)
Player.select("name".databaseValue)
```
### SQLSelection
`SQLSelection` is the opaque type for all [SQLite result columns](https://sqlite.org/syntax/result-column.html). An SQLSelection adopts and is built from [SQLSelectable].
```swift
struct SQLSelection: SQLSelectable {
// opaque implementation
}
```
Functions and methods that build result columns should return an SQLSelection value:
```swift
// SELECT (score + bonus) AS total
let selection = (Column("score") + Column("bonus")).forKey("total") // SQLSelection
Player.select(selection)
```
### SQLSpecificExpressible
`SQLSpecificExpressible` is the protocol for all SQL expressions, except values such as [Int, String, Date], etc. It conforms to [SQLExpressible], [SQLSelectable], and [SQLOrderingTerm]. It is adopted by [Column], [SQL], and [SQLExpression]. It is also adopted through [SQLSubqueryable] by [QueryInterfaceRequest] and [SQLRequest].
```swift
protocol SQLSpecificExpressible: SQLExpressible, SQLSelectable, SQLOrderingTerm { }
```
Use SQLSpecificExpressible when you want to operate on expressions, except [Int, String, Date] and other types which are not directly related to SQL. For example, the built-in `length(_:)` GRDB function accepts SQLSpecificExpressible:
```swift
/// The LENGTH SQL function
func length(_ value: SQLSpecificExpressible) -> SQLExpression { ... }
length(Column("name")) // OK
length("name") // Compiler error
```
### SQLSubquery
`SQLSubquery` is the opaque type for all [SQLite SELECT queries](https://sqlite.org/syntax/select-stmt.html). An SQLSubquery adopts and is built from [SQLSubqueryable].
```swift
struct SQLSubquery: SQLSubqueryable {
// opaque implementation
}
```
### SQLSubqueryable
`SQLSubqueryable` is the protocol for all [SQLite SELECT queries](https://sqlite.org/syntax/select-stmt.html). It conforms to [SQLSpecificExpressible], and is adopted by [FetchRequest], [QueryInterfaceRequest], [SQLRequest]. It has an `sqlSubquery` property which returns an [SQLSubquery].
```swift
protocol SQLSubqueryable: SQLSpecificExpressible {
var sqlSubquery: SQLSubquery { get }
}
```
SQLSubqueryable provides the GRDB support for subqueries. Its [SQLSpecificExpressible] facet lets you use any request as an expression:
```swift
// SELECT * FROM player
// WHERE score >= (SELECT AVG(score) FROM player)
let averageScore = Player.select(average(Column("score")))
Player.filter(Column("score") >= averageScore)
```
SQLSubqueryable has the `contains(_:)` and `exists()` methods that support the `value IN (subquery)` and `EXISTS (subquery)` expressions.
Use SQLSubqueryable in order to define a function that requires a subquery argument:
```swift
func myRequest(_ nameSubquery: SQLSubqueryable) -> SQLRequest<Player> {
"""
SELECT * FROM player
WHERE name IN (\(nameSubquery) UNION ...)
"""
}
myRequest(SQLRequest("SELECT ..."))
myRequest(Player.select(...).filter(...))
```
[Association]: #association
[associations]: AssociationsBasics.md
[association aggregates]: AssociationsBasics.md#association-aggregates
[Column]: #column
[ColumnExpression]: #columnexpression
[DatabaseRegionConvertible]: #databaseregionconvertible
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
[DatabaseValue]: #databasevalue
[DatabaseValueConvertible]: #databasevalueconvertible
[DerivableRequest]: #derivablerequest
[FetchableRecord]: ../README.md#fetchablerecord-protocol
[FetchRequest]: #fetchrequest
[Int, String, Date…]: #int-string-date
[Int, String, Date]: #int-string-date
[query interface]: ../README.md#the-query-interface
[QueryInterfaceRequest]: #queryinterfacerequest
[SQL]: #sql
[SQL Interpolation]: SQLInterpolation.md
[SQLExpression]: #sqlexpression
[SQLExpressible]: #sqlexpressible
[SQLOrderingTerm]: #sqlorderingterm
[SQLOrdering]: #sqlordering
[SQLRequest]: #sqlrequest
[SQLSelectable]: #sqlselectable
[SQLSelection]: #sqlselection
[SQLSpecificExpressible]: #sqlspecificexpressible
[SQLSubquery]: #sqlsubquery
[SQLSubqueryable]: #sqlsubqueryable
+28 -40
View File
@@ -22,7 +22,7 @@ try dbQueue.write { db in
SQL Interpolation is an answer to these troubles. It is available in Swift 5.
- [Introduction]
- [SQL Literal]
- [SQLLiteral]
- [SQL Interpolation and the Query Interface]
- [SQL Interpolation and Record Protocols]
- [SQL Interpolation Reference]
@@ -73,38 +73,38 @@ Plain SQL strings are indeed still available, and SQL interpolation only kicks i
```
## SQL Literal
## SQLLiteral
**`SQL`** is the type that looks like a plain String, but profits from SQL interpolation:
**SQLLiteral** is the type that looks like a plain String, but profits from SQL interpolation:
```swift
try dbQueue.write { db in
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
try db.execute(literal: query)
}
```
**`SQL` is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
**SQLLiteral is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
```swift
try dbQueue.write { db in
let query = "UPDATE player SET name = \(name) WHERE id = \(id)" // a regular String
// Compiler error:
// Cannot convert value of type 'String' to expected argument type 'SQL'
// Cannot convert value of type 'String' to expected argument type 'SQLLiteral'
try db.execute(literal: query)
}
```
`SQL` can build your queries step by step, with regular operators and methods:
SQLLiteral can build your queries step by step, with regular operators and methods:
```swift
// +, +=, append
var query: SQL = "UPDATE player "
var query: SQLLiteral = "UPDATE player "
query += "SET name = \(name) "
query.append(literal: "WHERE id = \(id)")
// joined(), joined(separator:)
let components: [SQL] = [
let components: [SQLLiteral] = [
"UPDATE player",
"SET name = \(name)",
"WHERE id = \(id)"
@@ -115,7 +115,7 @@ let query = components.joined(separator: " ")
Extract the plain SQL string from a literal:
```swift
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try dbQueue.read(query.build)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
@@ -124,17 +124,17 @@ print(arguments) // prints ["O'Brien", 42]
Build a literal from a plain SQL string:
```swift
let query = SQL(
let query = SQLLiteral(
sql: "UPDATE player SET name = ? WHERE id = ?",
arguments: [name, id])
```
`SQL` can embed any [value], as we have seen above, but not only. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
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 the Query Interface
SQL Interpolation and `SQL` let you embed raw SQL snippets in [query interface requests].
SQL Interpolation and SQLLiteral let you embed raw SQL snippets in [query interface requests].
For example:
@@ -143,37 +143,25 @@ For example:
let request = Player.filter(literal: "name = \("O'Brien")")
```
You can also build literals from other expressions. For example, let's call the `DATE` SQLite function on a query interface column:
You can also build literal expressions from other expressions. For example, let's call the `DATE` SQLite function on a query interface column:
```swift
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
let createdAt = Column("createdAt")
let creationDay = SQL("DATE(\(createdAt))")
let creationDay = SQLLiteral("DATE(\(createdAt))").sqlExpression
let request = Player.filter(creationDay == "2020-01-23")
```
Such literals play well with the query interface, even when several tables are involved with [associations](AssociationsBasics.md):
Such literal expressions can be returned by Swift functions:
```swift
// SELECT player.*, team.*
// FROM player
// JOIN team ON team.id = player.teamID
// WHERE DATE(player.createdAt) = '2020-01-23'
// ~~~~~~~~~~~~~~~~~~~~~~
// automatic table disambiguation
let request = Player
.filter(creationDay == "2020-01-23")
.including(required: Player.team)
```
This allows you to define Swift functions that you can use in all circumstances:
```swift
func date(_ expression: SQLExpressible) -> SQLExpression {
SQL("DATE(\(expression))").sqlExpression
func date(_ value: SQLExpressible) -> SQLExpression {
SQLLiteral("DATE(\(value))").sqlExpression
}
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
// SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
let createdAt = Column("createdAt")
let request = Player.filter(date(createdAt) == "2020-01-23")
```
@@ -346,7 +334,7 @@ Let's extend Player with database methods.
extension Player: Decodable, FetchableRecord, TableRecord {
/// A complex request
static func complexRequest() -> SQLRequest<Player> {
let query: SQL = "SELECT \(columnsOf: self) "
let query: SQLLiteral = "SELECT \(columnsOf: self) "
query += "FROM \(self) "
query += "JOIN \(Team.self) ON ..."
query += "GROUP BY ..."
@@ -355,7 +343,7 @@ Let's extend Player with database methods.
}
```
This last request shows how to build an SQLRequest from an [SQL Literal]. You will need `SQL` when the request can not be written in a single stroke.
This last request shows how to build an SQLRequest from an [SQLLiteral]. You will need SQLLiteral when the request can not be written in a single stroke.
@@ -443,7 +431,7 @@ This chapter lists all kinds of supported interpolations.
```swift
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
let subquery = SQLRequest("SELECT MAX(score) FROM player")
let subquery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
"SELECT * FROM player WHERE score = (\(subquery))"
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
@@ -461,11 +449,11 @@ This chapter lists all kinds of supported interpolations.
"WITH \(definitionFor: cte) SELECT * FROM \(cte)"
```
- `SQL` literal:
- SQLLiteral:
```swift
// SELECT * FROM player WHERE name = 'O''Brien'
let condition: SQL = "name = \("O'Brien")"
let condition: SQLLiteral = "name = \("O'Brien")"
"SELECT * FROM player WHERE \(literal: condition)"
```
@@ -480,7 +468,7 @@ This chapter lists all kinds of supported interpolations.
```
[Introduction]: #introduction
[SQL Literal]: #sql-literal
[SQLLiteral]: #sqlliteral
[SQL Interpolation and the Query Interface]: #sql-interpolation-and-the-query-interface
[SQL Interpolation and Record Protocols]: #sql-interpolation-and-record-protocols
[SQL Interpolation Reference]: #sql-interpolation-reference
+4 -10
View File
@@ -66,7 +66,7 @@ Since several processes may open the database at the same time, protect the crea
}
}
}
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
let dbPool = try DatabasePool(path: databaseURL.path)
// Perform here other database setups, such as defining
// the database schema with a DatabaseMigrator, and
@@ -173,9 +173,9 @@ do {
> The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension.
See https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report for more information about this exception.
See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for more information about this exception.
1. If you use SQLCipher, use SQLCipher 4+, and call the [`cipher_plaintext_header_size` pragma](https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_plaintext_header_size) from your database preparation function:
1. If you use SQLCipher, use SQLCipher 4+, and call the `cipher_plaintext_header_size` pragma from your database preparation function:
```swift
var configuration = Configuration()
@@ -186,13 +186,7 @@ See https://developer.apple.com/documentation/xcode/understanding-the-exception-
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
This will avoid this issue: https://github.com/sqlcipher/sqlcipher/issues/255.
This will also disable a SQLCipher security feature: the salt. As described by https://www.zetetic.net/sqlcipher/design/:
> The salt is used for key derivation and it ensures that even if two databases are created using the same password, they will not have the same encryption key.
Applications are responsible for managing the salt themselves and providing it to SQLCipher. See https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_plaintext_header_size for instructions.
This will avoid https://github.com/sqlcipher/sqlcipher/issues/255.
2. [**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) In each process that wants to write in the database:
-242
View File
@@ -1,242 +0,0 @@
Single-Row Tables
=================
Let's talk about database tables that should contain a single row.
Such tables can store configuration values, user preferences, and generally some global application state. They are a suitable alternative to `UserDefaults` in some applications, especially when configuration refers to values found in other database tables, and database integrity is a concern.
An alternative way to store such configuration is a table of key-value pairs: two columns, and one row for each configuration value. This technique works, but it has a few drawbacks: you will have to deal with the various types of configuration values (strings, integers, dates, etc), and you won't be able to define foreign keys. This is why we won't explore key-value tables.
This guide helps you implementing a single-row table with GRDB, with recommendations on the database schema, migrations, and the design of a matching [record] type.
- [The Single-Row Table]
- [The Single-Row Record]
- [Wrap-Up]
## The Single-Row Table
As always with GRDB, everything starts at the level of the database schema. Putting the robust SQLite on our side is always a good idea, because we have to write less code, and this helps shipping less bugs.
We want to instruct SQLite that our table must never contain more than one row. We will never have to wonder what to do if we were unlucky enough to find two rows with conflicting values in this table.
SQLite is not able to guarantee that the table is never empty, so we have to deal with two cases: either the table is empty, or it contains one row.
Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app perform an insert in case of a failed update (in the [The Single-Row Record] chapter). And we instruct SQLite to just replace the eventual existing row in case of conflicting inserts:
```swift
// CREATE TABLE appConfiguration (
// id INTEGER PRIMARY KEY ON CONFLICT REPLACE CHECK (id = 1),
// flag BOOLEAN NOT NULL,
// ...)
try db.create(table: "appConfiguration") { t in
// Single row guarantee
t.column("id", .integer)
// Have inserts replace the existing row
.primaryKey(onConflict: .replace)
// Make sure the id column is always 1
.check { $0 == 1 }
// The configuration colums
t.column("flag", .boolean).notNull()
// ... other columns
}
```
When you use [migrations], you may wonder if it is a good idea or not to perform an initial insert just after the table is created. Well, this is not recommended:
```swift
// NOT RECOMMENDED
migrator.registerMigration("appConfiguration") { db in
try db.create(table: "appConfiguration") { t in
// Single row guarantee
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
// Define sensible defaults for each column
t.column("flag", .boolean).notNull()
.defaults(to: false)
// ... other columns
}
// Populate the table
try db.execute(sql: "INSERT INTO appConfiguration DEFAULT VALUES")
}
```
It is not a good idea to populate the table in a migration, for two reasons:
1. This is not a hard guarantee that the table will never be empty. As a consequence, this won't prevent your Swift code from dealing with the possibility of a missing row. On top of that, the Swift code that deals with the missing row may not use the same default values as the SQLite schema (a [DRY] violation), with unclear consequences.
2. Migrations that are shipped in the wild should *never* change, because you want to control the state of the databases installed on your users' devices, regardless of the application version they install first, regardless of how many application versions are skipped when they download an upgrade, etc. By inserting an initial row in a migration, you make it difficult for your application to adjust the sensible default values in the future, while keeping a clear idea of the various installation and upgrade scenarios.
The recommended migration creates the table, nothing more:
```swift
// RECOMMENDED
migrator.registerMigration("appConfiguration") { db in
try db.create(table: "appConfiguration") { t in
// Single row guarantee
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
// The configuration colums
t.column("flag", .boolean).notNull()
// ... other columns
}
}
```
## The Single-Row Record
Now that the database schema has been defined, we can define the [record] type that will help the application access the single row:
```swift
struct AppConfiguration: Codable {
// Support for the single row guarantee
private var id = 1
// The configuration properties
var flag: Bool
// ... other properties
}
```
In case the database table would be empty, we need a default configuration:
```swift
extension AppConfiguration {
/// The default configuration
static let `default` = AppConfiguration(flag: false, ...)
}
```
We make our record able to access the database:
```swift
extension AppConfiguration: FetchableRecord, PersistableRecord {
```
We have seen in the [The Single-Row Table] chapter that by default, updates throw an error if the database table is empty. To avoid this error, we instruct GRDB to perform an insert in case of a failed update (see [Persistence Methods] for more information):
```swift
// Customize the default PersistableRecord behavior
func update(_ db: Database, columns: Set<String>) throws {
do {
try performUpdate(db, columns: columns)
} catch PersistenceError.recordNotFound {
// No row was updated: perform an insert
try performInsert(db)
}
}
```
The standard GRDB method `fetchOne` returns an optional which is nil when the database table is empty. As a convenience, let's define a method that returns a non-optional (replacing the missing row with `default`):
```swift
/// Returns the persisted configuration, or the default one if the
/// database table is empty.
static func fetch(_ db: Database) throws -> AppConfiguration {
try fetchOne(db) ?? .default
}
}
```
And that's it! Now we can use our singleton record:
```swift
// READ
let config = try dbQueue.read { db in
try AppConfiguration.fetch(db)
}
if config.flag {
// ...
}
// WRITE
try dbQueue.write { db in
var config = try AppConfiguration.fetch(db)
// Update some config values
try config.updateChanges(db) {
$0.flag = true
}
// Other possible ways to write config:
try config.update(db)
try config.save(db)
try config.insert(db)
}
```
The three `update`, `save` and `insert` methods can be used interchangeably: all three make sure the configuration is stored in the database.
The `updateChanges` method only updates the values changed by its closure argument (and performs an insert if the database table is empty).
See [Persistence Methods] for more information.
## Wrap-Up
We all love to copy and paste, don't we? Just customize the template code below:
```swift
// Table creation
try db.create(table: "appConfiguration") { t in
// Single row guarantee
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
// The configuration columns
t.column("flag", .boolean).notNull()
// ... other columns
}
```
```swift
//
// AppConfiguration.swift
//
import GRDB
struct AppConfiguration: Codable {
// Support for the single row guarantee
private var id = 1
// The configuration properties
var flag: Bool
// ... other properties
}
extension AppConfiguration {
/// The default configuration
static let `default` = AppConfiguration(flag: false, ...)
}
// Database Access
extension AppConfiguration: FetchableRecord, PersistableRecord {
// Customize the default PersistableRecord behavior
func update(_ db: Database, columns: Set<String>) throws {
do {
try performUpdate(db, columns: columns)
} catch PersistenceError.recordNotFound {
// No row was updated: perform an insert
try performInsert(db)
}
}
/// Returns the persisted configuration, or the default one if the
/// database table is empty.
static func fetch(_ db: Database) throws -> AppConfiguration {
try fetchOne(db) ?? .default
}
}
```
[migrations]: Migrations.md
[record]: ../README.md#records
[The Single-Row Table]: #the-single-row-table
[The Single-Row Record]: #the-single-row-record
[Wrap-Up]: #wrap-up
[DRY]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
[Persistence Methods]: ../README.md#persistence-methods
+956
View File
@@ -0,0 +1,956 @@
Tutorial: Building a Database Access Layer
==========================================
<img align="right" src="https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png" width="50%">
**This tutorial builds and explains a database access layer for a UIKit or SwiftUI application**. See the [demo applications] for sample code.
The target audience has basic database knowledge, and knows what tables and columns are. The tutorial visits high-level GRDB features: record types, query interface, database observation. Raw SQL is also provided, so that you can choose your favorite way to use SQLite.
The setup of Xcode projects, view controllers, or SwiftUI is not discussed. Refer to the demo apps for sample code.
When you want an explanation about some particular recommendation or piece of code, expand the design notes marked with an ℹ️.
As you can see in the [screenshot], the demo application displays the list of players stored in the database. The application user can sort players by name or by score. She can add, edit, and delete players. The list of players can be "refreshed". For demo purpose, refreshing players performs random modifications to the players. The tornado icon exercices multi-threading robustness by spawning many concurrent refreshes.
Let's start!
- [The Database Service]
- [The Shared Application Database]
- [The Database Schema]
- [The Player Struct]
- [Saving Players]
- [Deleting Players]
- [Fetching Players]
- [Refreshing Players]
- [Sorting Players]
- [Observing Players]
- [The Initial Application State]
- [Testing the Database]
## The Database Service
The database service (or database manager, or persistence layer) is a class named `AppDatabase` that grants access to the SQLite database of players. It fetches the list of players, inserts new players, etc.
`AppDatabase` accesses the database through a GRDB [database connection]. In the application, the service uses a `DatabasePool` connection that leverages the advantages of the SQLite [WAL mode]. Tests use a service that connects to an in-memory database, with `DatabaseQueue`, so that they can run as fast as possible. SwiftUI previews also run with in-memory databases.
Database pools and queues share a common protocol: `DatabaseWriter`. This is what the `AppDatabase` service needs, in order to support both:
```swift
// File: AppDatabase.swift
import GRDB
final class AppDatabase {
/// Creates an `AppDatabase`.
init(_ dbWriter: DatabaseWriter) throws {
self.dbWriter = dbWriter
}
/// Provides access to the database.
private let dbWriter: DatabaseWriter
}
```
<details>
<summary>ℹ️ Design Notes</summary>
> :point_right: The `dbWriter` property is private: this allows `AppDatabase` to restrict the operations that can be performed on the database.
>
> :point_right: The initializer is not private: we can freely create `AppDatabase` instances, for the application, and for tests.
>
> :point_right: The initializer is declared with the `throws` qualifier, because it will be extended, below in this guide, in order to prepare the database for application use.
</details>
> ✅ At this stage, we have an `AppDatabase` class which encapsulates access to the database. It supports both WAL databases, and in-memory databases, so that it can feed the application, tests, and SwiftUI previews.
## The Shared Application Database
Our app uses a single database file, so we want a "shared" database: `AppDatabase.shared`.
The shared `AppDatabase` instance opens a file named "db.sqlite" stored in a "database" folder. The database is created if the file does not already exist:
```swift
// File: Persistence.swift
import GRDB
extension AppDatabase {
/// The database for the application
static let shared = makeShared()
private static func makeShared() -> AppDatabase {
do {
// Create a folder for storing the SQLite database
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
// Connect to a database on disk
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
return appDatabase
} catch {
fatalError("Unresolved error \(error)")
}
}
}
```
The [Combine + SwiftUI Demo Application] defines more instances of `AppDatabase`, such as en empty players database suitable for some SwiftUI previews:
```swift
// File: Persistence.swift
extension AppDatabase {
/// Creates an empty database for SwiftUI previews
static func empty() -> AppDatabase {
// Connect to an in-memory database
let dbQueue = DatabaseQueue()
return try! AppDatabase(dbQueue)
}
}
```
<details>
<summary>ℹ️ Design Notes</summary>
> :point_right: Some applications will prefer to manage the shared `AppDatabase` instance differently, for example with some dependency injection technique. In this case, you will not define `AppDatabase.shared`.
>
> Just make sure that there exists a single instance of `DatabaseQueue` or `DatabasePool` for any given database file. This is because multiple instances would compete for database access, and sometimes throw errors. Get inspiration from `AppDatabase.makeShared()`, above, in order to create the single instance of database service used by the application.
>
> :point_right: The database is stored in its own directory, so that you can easily:
>
> - Set up [data protection].
> - Remove the database as well as its companion [temporary files](https://sqlite.org/tempfiles.html) from disk in a single stroke.
>
> :point_right: `AppDatabase.shared` is created from a `DatabasePool` in order to profit from the SQLite [WAL mode].
>
> :point_right: Any error which prevents the application from opening the database has the application crash. You will have to adapt this sample code if you intend to build an app that is able to run without a working database. For example, you could modify `AppDatabase` so that it feeds from a `Result<DatabaseWriter, Error>` instead of a plain `DatabaseWriter` - but your mileage may vary. This sample code has the error bubble up in crash reports, which is arguably better than displaying a blank screen without any error reporting.
</details>
> ✅ At this stage, we have an `AppDatabase.shared` object which vends an empty database. We'll add methods and properties to `AppDatabase`, as we discover the needs of our application.
## The Database Schema
Now that we have an empty database, let's define its schema: the database table(s) that will store our application data. A good database schema will have SQLite manage the database integrity for you, and make sure it is impossible to store invalid data in the database: this is an important step!
Our database has one table, `player`, where each row contains the attributes of a player: a unique identifier (aka *primary key*), a name, and a score. The identifier makes it possible to instruct the database to perform operations on a specific player. We'll make sure all players have a name and a score (we'll prevent *NULL* values from entering those columns).
In order to define the schema and create the `player` table, it is recommended to use [migrations]. All applications around us evolve as time passes, and ship several versions: it is likely our app will do the same. The database schema evolves as well, as we add features and fix bugs in our app. That's exactly what migrations are for: they represent the building steps of our database schema, as our app goes through its versions.
The migrations are defined in the `AppDatabase.migrator` property, in which we register the *initial migration*:
```swift
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
migrator.registerMigration("initial") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("score", .integer).notNull()
}
}
// Migrations for future application versions will be inserted here:
// migrator.registerMigration(...) { db in
// ...
// }
return migrator
}
```
<details>
<summary>Raw SQL version</summary>
> Some readers like to write SQL. Please be welcome:
>
> ```swift
> private var migrator: DatabaseMigrator {
> var migrator = DatabaseMigrator()
>
> migrator.registerMigration("initial") { db in
> try db.execute(sql: """
> CREATE TABLE player (
> id INTEGER PRIMARY KEY AUTOINCREMENT,
> name TEXT NOT NULL,
> score INTEGER NOT NULL
> )
> """)
> }
>
> return migrator
> }
> ```
</details>
The migrations are now defined, but they are not applied yet. Let's modify the `AppDatabase` initializer, and *migrate* the database. It means that unapplied migrations are run. In the end, we are sure that the database schema is exactly what we want it to be:
```swift
/// Creates an `AppDatabase` from a database connection,
/// and make sure the database schema is ready.
init(_ dbWriter: DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
}
```
<details>
<summary>ℹ️ Design Notes</summary>
> :point_right: GRDB is a library that fosters robust database schemas, defined right at the SQLite level, because you can't build a safer haven for your precious users' data. There is no such thing as "automatic schema definition" or "automatic migrations" based on annotated Swift models. See [Trust SQLite More Than Yourself] for a longer explanation of this policy.
>
> :point_right: The database table for players is named `player`, because GRDB recommends that table names are English, singular, and camel-cased (`player`, `country`, `postalAddress`, etc.) Such names will help you using [Associations] when you need them. Database table names that follow another naming convention are totally OK, but you will have to perform extra configuration.
>
> :point_right: The primary key for players is an auto-incremented column named `id`. It also could have been a UUID column named `uuid`. GRDB generally accepts all primary keys, even if they are not named `id`, even if they span several columns, without any extra setup. Yet `id` is a frequent convention.
>
> :point_right: The `id` column is [autoincremented](https://sqlite.org/autoinc.html), in order to avoid id reuse. Reused ids can trip up [database observation] tools: a deletion followed by an insertion with the same id could be interpreted as an update, with unintended consequences.
</details>
> ✅ At this stage, we have an `AppDatabase.shared` object which vends a database that contains a `player` table.
## The Player Struct
The application will insert, edit, display, and delete players. Let's *model* a player with a dedicated type:
```swift
// File: Player.swift
/// A Player
struct Player {
var id: Int64?
var name: String
var score: Int
}
```
With its `name` and `score` properties, it can feed our application screens. With its `id` property, it can talk to `AppDatabase`, whenever we need to perform operations of a particular player (such as saving changes performed on a player).
The type of `id` is `Int64?`, because it matches the `id` column in the `player` table (SQLite integer primary keys are 64-bit integers, even on 32-bit platforms). When the id is nil, the player is not yet saved in the database. When the id is not nil, it is the identifier of a player in the database.
The `name` and `score` properties are regular `String` and `Int`. They are not optional because the `player` table was created with "not null" constraints on those database columns: we do not want to insert nil names, and we are sure we won't fetch nil names either.
> ✅ Now we have a `Player` type that fits the columns of the `player` database table, and is able to deal with all application needs. This is what GRDB calls a [record type]. At this stage, `Player` has no database power yet.
## Saving Players
The user application inserts player by tapping the "+" button on the top left of the [screen], which displays a form. The user fills the name and score fields, and hits the "Done" button.
The same form screen is pushed when the user taps a player in the list. The app then updates the player when the user hits the back button.
The `AppDatabase` service supports both these use cases by providing a `savePlayer(_:)` method.
We can write it with raw SQL:
<details>
<summary>Raw SQL version</summary>
> ```swift
> // File: AppDatabase.swift
>
> extension AppDatabase {
> /// Saves (inserts or updates) a player. When the method returns, the
> /// player is present in the database, and its id is not nil.
> func savePlayer(_ player: inout Player) throws {
> try dbWriter.write { db in
> try save(db, player: &player)
> }
> }
>
> /// Saves (inserts or updates) a player. When the method returns, the
> /// player is present in the database, and its id is not nil.
> private func save(_ db: Database, player: inout Player) throws {
> if let id = player.id {
> // Player has an id: update
> try db.execute(literal: """
> UPDATE player
> SET name = \(player.name),
> score = \(player.score)
> WHERE id = \(id)
> """)
>
> if db.changesCount == 0 {
> // Player was not updated. This means that is was not
> // present in the database. So let's insert it with its id.
> try db.execute(literal: """
> INSERT INTO player (id, name, score)
> VALUES (\(player.id), \(player.name), \(player.score))
> """)
> }
> } else {
> // Player has no id: insert
> try db.execute(literal: """
> INSERT INTO player (name, score)
> VALUES (\(player.name), \(player.score))
> """)
> player.id = db.lastInsertedRowID
> }
> }
> }
> ```
>
> The `savePlayer(_:)` method calls a private helper method `save(_:player:)`. This helper method will be reused later in the tutorial.
>
> Note that the helper method uses the `execute(literal:)` method, which avoids [SQL injection], thanks to [SQL Interpolation].
</details>
SQL is just fine, but we can also make `Player` a [persistable record], so that you do not have to write the SQL queries that perform common persistence operations.
In our specific case, the `Player` struct adopts the `MutablePersistableRecord` protocol, because the `player` database table has an autoincremented id:
- "Persistable": players can be inserted, updated and deleted.
- "Mutable": a player is modified (mutated) upon insertion, because its `id` property is set from the autoincremented SQLite id.
Conformance to `MutablePersistableRecord` is easy for types that adopt the standard [Encodable] protocol:
```swift
// File: Player.swift
// Give Player database powers
extension Player: Encodable, MutablePersistableRecord {
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
```
In this tutorial, the name of the database table matches the name of the type, and so do columns and properties: we do not have to configure anything.
<details>
<summary>Avoiding Encodable</summary>
The `Encodable` protocol is handy, but you may prefer not to use it. In this case, you have to fulfill the `MutablePersistableRecord` requirements:
```swift
// File: Player.swift
// Give Player database powers
extension Player: MutablePersistableRecord {
/// Defines the values persisted in the database
func encode(to container: inout PersistenceContainer) {
container["id"] = id
container["name"] = name
container["score"] = score
}
/// Updates a player id after it has been inserted in the database.
mutating func didInsert(with rowID: Int64, for column: String?) {
id = rowID
}
}
```
</details>
Thanks to persistable records, we now support both inserts and updates:
```swift
// File: AppDatabase.swift
extension AppDatabase {
/// Saves (inserts or updates) a player. When the method returns, the
/// player is present in the database, and its id is not nil.
func savePlayer(_ player: inout Player) throws {
try dbWriter.write { db in
try player.save(db)
}
}
}
```
Usage:
```swift
// Inserts a player
var player = Player(id: nil, name: "Arthur", score: 0)
try AppDatabase.shared.savePlayer(player)
print("Player id is \(player.id)") // Prints "Player id is 1"
// Updates a player
player.score = 1000
try AppDatabase.shared.savePlayer(player)
```
> ✅ At this stage, we can save players in the database.
## Deleting Players
The application can delete players:
- The "Trash" icon at the bottom left of the [screen] deletes all players.
- The "Edit" button at the top left of the screen lets the user delete individual players.
- The player list supports the swipe to delete gesture.
The `AppDatabase` service supports these use cases with two new methods:
```swift
// File: AppDatabase.swift
extension AppDatabase {
/// Delete the specified players
func deletePlayers(ids: [Int64]) throws {
try dbWriter.write { db in
_ = try Player.deleteAll(db, keys: ids)
}
}
/// Delete all players
func deleteAllPlayers() throws {
try dbWriter.write { db in
_ = try Player.deleteAll(db)
}
}
}
```
Both `deleteAll(_:)` and `deleteAll(_:keys:)` methods are available for all persistable records.
<details>
<summary>Raw SQL version</summary>
> If you do not want to make `Player` a persistable record, you can fallback to raw SQL:
>
> ```swift
> // File: AppDatabase.swift
>
> extension AppDatabase {
> /// Delete the specified players
> func deletePlayers(ids: [Int64]) throws {
> try dbWriter.write { db in
> try db.execute(literal: """
> DELETE FROM player WHERE id IN \(ids)
> """)
> }
> }
>
> /// Delete all players
> func deleteAllPlayers() throws {
> try dbWriter.write { db in
> try db.execute(sql: "DELETE FROM player")
> }
> }
> }
> ```
>
> The `deletePlayers(ids:)` method above uses [SQL Interpolation] so that you can embed an array of ids right inside your SQL query (`WHERE id IN \(ids)`). The "really raw" SQL version below is a little more involved:
>
> ```swift
> func deletePlayers(ids: [Int64]) throws {
> try dbWriter.write { db in
> if ids.isEmpty {
> // Avoid SQL syntax error
> return
> }
> // DELETE FROM player WHERE id IN (?, ?, ...)
> // ~~~~~~~~~
> // as many question marks as there are ids
> let placeholders = databaseQuestionMarks(count: ids.count)
> let query = "DELETE FROM player WHERE id IN (\(placeholders))"
> try db.execute(sql: query, arguments: StatementArguments(ids))
> }
> }
> ```
>
> All the techniques we have seen avoid [SQL injection].
</details>
> ✅ At this stage, we can delete all or individual players from the database.
## Fetching Players
GRDB record types also provide fetching methods, when they adopt the [FetchableRecord] protocol.
This protocol is "free" when `Player` adopts the [Decodable] protocol:
```swift
// File: Player.swift
extension Player: Decodable, FetchableRecord { }
```
<details>
<summary>Avoiding Decodable</summary>
The `Decodable` protocol is handy, but you may prefer not to use it. In this case, you have to fulfill the [FetchableRecord] requirement:
```swift
// File: Player.swift
extension Player: FetchableRecord {
/// Creates a player from a database row
init(row: Row) {
id = row["id"]
name = row["name"]
score = row["score"]
}
}
```
</details>
> ✅ At this stage, we can turn raw database rows into players.
## Refreshing Players
The refresh button at the bottom center of the [screen] applies random transformations to the player database. The `AppDatabase` service supports this use cases by providing a `refreshPlayers()` method.
```swift
// File: AppDatabase.swift
extension AppDatabase {
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() throws {
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
// When database is empty, insert new random players
try createRandomPlayers(db)
} else {
// Insert a player
if Bool.random() {
var player = Player.newRandom()
try player.save(db)
}
// Delete a random player
if Bool.random() {
try Player.order(sql: "RANDOM()").limit(1).deleteAll(db)
}
// Update some players
for var player in try Player.fetchAll(db) where Bool.random() {
try player.updateChanges(db) {
$0.score = Player.randomScore()
}
}
}
}
}
private func createRandomPlayers(_ db: Database) throws {
for _ in 0..<8 {
var player = Player.newRandom()
try player.save(db)
}
}
}
```
The `AppDatabase.refreshPlayers()` method calls a private helper method `createRandomPlayers(_:)`. This helper method will be reused later in the tutorial.
Refreshing players needs some support from the `Player` record type, so that we can build random players:
```swift
// File: Player.swift
extension Player {
private static let names = ["Arthur", "Anita", ...]
/// Creates a new player with random name and random score
static func newRandom() -> Player {
Player(id: nil, name: randomName(), score: randomScore())
}
/// Returns a random name
static func randomName() -> String {
names.randomElement()!
}
/// Returns a random score
static func randomScore() -> Int {
10 * Int.random(in: 0...100)
}
}
```
<details>
<summary>Raw SQL version</summary>
> Let's write `AppDatabase.refreshPlayers()` without any support from SQL generation provided by record protocols:
>
> ```swift
> // File: AppDatabase.swift
>
> extension AppDatabase {
> /// Refresh all players (by performing some random changes, for demo purpose).
> func refreshPlayers() throws {
> try dbWriter.write { db in
> if try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player") == 0 {
> // When database is empty, insert new random players
> try createRandomPlayers(db)
> } else {
> // Insert a player
> if Bool.random() {
> var player = Player.newRandom()
> try save(db, player: &player)
> }
>
> // Delete a random player
> if Bool.random() {
> try db.execute(sql: """
> DELETE FROM player
> ORDER BY RANDOM()
> LIMIT 1
> """)
> }
>
> // Update some players
> let ids = try Int64.fetchAll(db, sql: "SELECT id FROM player")
> for id in ids where Bool.random() {
> try db.execute(literal: """
> UPDATE player
> SET score = \(Player.randomScore())
> WHERE id = \(id)
> """)
> }
> }
> }
> }
>
> private func createRandomPlayers(_ db: Database) throws {
> for _ in 0..<8 {
> var player = Player.newRandom()
> try save(db, player: &player)
> }
> }
> }
> ```
>
> The `save(_:player:)` method was defined, with raw SQL, in [Saving Players].
</details>
<details>
<summary>ℹ️ Design Notes</summary>
> The role of the `AppDatabase` service is to provide a set of [ACID] transformations, that fully control the state of the database. Either a player is saved, either it is not. Players are refreshed, or they are not. If our application would synchronize its local database with some remote server, we would want players to be fully synchronized, or not at all. Intermediate states such as partially saved, deleted, refreshed, or synchronized players must be avoided, in order to make the application robust. After all, errors happen, and even hard crashes. Thanks to the ACID guarantees provided by SQLite, errors and crashes are unable to threaten important database invariants.
>
> **The added value of the `AppDatabase` service is to provide one method per database transformation needed by the app.** All those methods perform **a single GRDB write**, in order to profit from all ACID guarantees of SQLite transactions. Refreshing players is one of those transformations. Saving a player is another, which supports the user interface for editing of creating players.
>
> :bulb: **Tip**: when two distinct service methods want to reuse a piece of code, we extract it in a helper method such as `createRandomPlayers(_:)` above. Unlike service methods, helper methods access the database through their `Database` argument, not through the `dbWriter` property.
</details>
> ✅ At this stage, we can modify players in a controlled and robust way.
## Sorting Players
The application [screen] displays a list of players. The user can choose the order of players by tapping the button at the top right of the screen. The app supports two orderings: by descending score, and by ascending name.
In this chapter, we will not describe how the applications keeps its screen synchronized with the content of the database. This will be the topic of [Observing Players].
Here we will extend the `Player` record type so that it provides the **database requests** needed by the application.
<details>
<summary>ℹ️ Design Notes</summary>
> With GRDB, record types are responsible of their table: they know how data is stored in the database. This is why `Player` is better suited to know what sorting players by name, or by score, means.
>
> On the other side, `Player` does not perform database fetches on its own. Actual database fetches are performed by the application, depending on the user actions, by invoking methods on `AppDatabase.shared`.
>
> `Player` *defines* database requests, and `AppDatabase` *executes* those requests.
</details>
We made `Player` a full-fledged record type in the previous chapters. Record types can profit from the [query interface], a Swift way to build database requests.
In order to build requests that sort by score or by name, we need to define columns. When the `Player` type is [Codable], we can profit from its `CodingKeys` so that the compiler makes sure we do not make any typo:
```swift
// File: Player.swift
extension Player {
// Player columns are defined from CodingKeys
fileprivate enum Columns {
static let name = Column(CodingKeys.name)
static let score = Column(CodingKeys.score)
}
}
```
<details>
<summary>ℹ️ Design Notes</summary>
> `Player.Columns` is declared `fileprivate`. The goal is to prevent other application files from messing with the intimate relationship between the `Player` record type and the `player` database table.
>
> Some apps eventually need to relax the visibility of those columns. Until they really have to, though, `fileprivate` is the recommended default for columns.
</details>
<details>
<summary>Avoiding Codable</summary>
The `Codable` protocol is handy, but you may prefer not to use it. In this case, define columns as a String enum:
```swift
// File: Player.swift
extension Player {
// Player columns
fileprivate enum Columns: String, ColumnExpression {
case name
case score
}
}
```
</details>
Following advice from the [Good Practices for Designing Record Types], we can now define player requests in an extension of the `DerivableRequest` protocol:
```swift
// File: Player.swift
/// Define some player requests used by the application.
extension DerivableRequest where RowDecoder == Player {
/// A request of players ordered by name.
///
/// For example:
///
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByName().fetchAll(db)
/// }
func orderedByName() -> Self {
// Sort by name in a localized case insensitive fashion
order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
/// A request of players ordered by score.
///
/// For example:
///
/// let players: [Player] = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchAll(db)
/// }
/// let bestPlayer: Player? = try dbWriter.read { db in
/// try Player.all().orderedByScore().fetchOne(db)
/// }
func orderedByScore() -> Self {
// Sort by descending score, and then by name, in a
// localized case insensitive fashion
order(
Player.Columns.score.desc,
Player.Columns.name.collating(.localizedCaseInsensitiveCompare))
}
}
```
Names are sorted according to the `localizedCaseInsensitiveCompare` collation. See [String Comparison](../README.md#string-comparison) for more information.
Writing an "extension of the `DerivableRequest` protocol" may sound intimidating. Well, don't be shy, and look at the sample code above: it contains inline documentation which describes the usage of those requests. Is it more clear now? `DerivableRequest` makes it possible to extend the query interface with custom requests, and also to hide some database implementation details inside a dedicated record type.
If you know the [Active Record](https://guides.rubyonrails.org/active_record_querying.html) Ruby library, you may be reminded of [scopes](https://guides.rubyonrails.org/active_record_querying.html#scopes):
```ruby
# player.rb
class Player < ApplicationRecord
scope :ordered_by_name, -> { order(name: :asc) }
end
```
<details>
<summary>Raw SQL version</summary>
> You can build SQL requests with `SQLRequest`, which profits from [SQL Interpolation]. If you have the `Player` type conform to [FetchableRecord], those requests will be able to fetch. Otherwise, we'll have to fetch raw database rows and we will have more work to do. But those requests can still be defined:
>
> ```swift
> // File: Player.swift
>
> /// Define some player requests used by the application.
> extension Player {
> /// A request of players ordered by name.
> ///
> /// For example:
> ///
> /// let players: [Player] = try dbWriter.read { db in
> /// try Player.orderedByName().fetchAll(db)
> /// }
> static func orderedByName() -> SQLRequest<Player> {
> // Sort by name in a localized case insensitive fashion
> """
> SELECT * FROM player
> ORDER BY name COLLATING \(.localizedCaseInsensitiveCompare)
> """
> }
>
> /// A request of players ordered by score.
> ///
> /// For example:
> ///
> /// let players: [Player] = try dbWriter.read { db in
> /// try Player.orderedByScore().fetchAll(db)
> /// }
> static func orderedByScore() -> SQLRequest<Player> {
> // Sort by descending score, and then by name, in a
> // localized case insensitive fashion
> """
> SELECT * FROM player
> ORDER BY score DESC,
> name COLLATING \(.localizedCaseInsensitiveCompare)
> """
> }
> }
> ```
>
> Compared to query interface requests, raw SQL requests lose two benefits:
>
> - SQL requests are not composable together. You can not reuse them. For example:
>
> ```swift
> // A request from a future version of our app.
> // Request composition is only possible for query interface requests.
> let request = Player.all()
> .filter(team: .red)
> .including(all: Player.awards)
> .orderedByName()
> ```
>
> - SQL requests do not auto-optimize when you are only interested in the first row:
>
> ```swift
> // No automatic appending of `LIMIT 1`, as query interface requests do.
> let bestPlayer: Player? = try dbWriter.read { db in
> try Player.orderedByScore().fetchOne(db)
> }
> ```
</details>
> ✅ At this stage, we have defined the database requests that can feed the list of players in the application.
## Observing Players
Some elements that are visible in the application [screen] do not depend on the database: action buttons, and the selected ordering. Those are transient information that live in a UIKit controller, or a SwiftUI view.
The database content on screen is:
- The number of players (in the navigation title).
- The list of all players.
Those two elements are not independent. We want them to be always consistent: if there are twelve players in the list, the title must be "12 Players".
In the previous [Sorting Players] chapter, we built database requests for players, one sorted by name, one sorted by score. Now is time to fetch those players from those requests.
More precisely, we will **observe** the requests of players. This will make it much easier to display an always-accurate list of players in the app. We will not have to remember to update the list whenever the player database is updated.
> ✅ At this stage, we can feed UIViewControllers and SwiftUI with an always fresh list of players.
## The Initial Application State
Let's perform a little polishing step, so that the first time the application is launched, it is already populated with a few players. We write a demo application, and a demo is nicer when the user can play right away.
To this end, we create a new `AppDatabase.createRandomPlayersIfEmpty()` method. It reuses the `createRandomPlayers(_:)` helper method defined in the [Refreshing Players] chapter:
```swift
// File: AppDatabase.swift
extension AppDatabase {
/// Create random players if the database is empty.
func createRandomPlayersIfEmpty() throws {
try dbWriter.write { db in
if try Player.fetchCount(db) == 0 {
try createRandomPlayers(db)
}
}
}
}
```
And we modify `AppDatabase.makeShared()` so that the application never boots with an empty database:
```swift
// File: Persistence.swift
import GRDB
extension AppDatabase {
/// The database for the application
static let shared = makeShared()
private static func makeShared() -> AppDatabase {
do {
// Create a folder for storing the SQLite database
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
// Connect to a database on disk
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
// Populate the database if it is empty, for better demo purpose.
try appDatabase.createRandomPlayersIfEmpty()
return appDatabase
} catch {
fatalError("Unresolved error \(error)")
}
}
}
```
<details>
<summary>ℹ️ Design Notes</summary>
> We do not call `createRandomPlayersIfEmpty()` from the `AppDatabase` initializer, or from its migrator, because we also need to create empty databases (for tests, or some SwiftUI previews). The correct place is indeed `makeShared()`, the method that creates the database for the application itself.
</details>
> ✅ At this stage, we have a polished Database Access Layer that makes sure the demo app looks good.
## Testing the Database
[The Database Service]: #the-database-service
[The Shared Application Database]: #the-shared-application-database
[The Database Schema]: #the-database-schema
[The Player Struct]: #the-player-struct
[Saving Players]: #saving-players
[Deleting Players]: #deleting-players
[Fetching Players]: #fetching-players
[Refreshing Players]: #refreshing-players
[Sorting Players]: #sorting-players
[Observing Players]: #observing-players
[The Initial Application State]: #the-initial-application-state
[Testing the Database]: #testing-the-database
[demo applications]: DemoApps
[UIKit demo application]: DemoApps/GRDBDemoiOS/README.md
[Combine + SwiftUI Demo Application]: DemoApps/GRDBCombineDemo/README.md
[database connection]: https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
[DatabaseQueue]: ../README.md#database-queues
[DatabasePool]: ../README.md#database-pools
[migrations]: Migrations.md
[Codable]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[Encodable]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[Decodable]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[record type]: ../README.md#records
[persistable record]: ../README.md#persistablerecord-protocol
[FetchableRecord]: ../README.md#fetchablerecord-protocol
[WAL mode]: https://sqlite.org/wal.html
[data protection]: ../README.md#data-protection
[Associations]: AssociationsBasics.md
[Sharing a database]: SharingADatabase.md
[database observation]: ../README.md#database-changes-observation
[SQL Interpolation]: SQLInterpolation.md
[SQL injection]: ../README.md#avoiding-sql-injection
[screenshot]: https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png
[screen]: https://github.com/groue/GRDB.swift/raw/master/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png
[ACID]: https://en.wikipedia.org/wiki/ACID
[query interface]: ../README.md#the-query-interface
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
[Trust SQLite More Than Yourself]: GoodPracticesForDesigningRecordTypes.md#trust-sqlite-more-than-yourself
+3
View File
@@ -283,6 +283,8 @@ while let row = try rows.next() {
If this little tour of GRDB has convinced you, the real trip starts here: [GRDB].
And if you happen to maintain an Objective-C application that uses FMDB, checkout [GRDBObjc]. It provides FMDB-compatible bindings to GRDB, so that you can inject sweet drops of Swift into your app, at your own pace, and at minimal cost.
Happy GRDB! :gift:
[Concurrency Guide]: ../README.md#concurrency
@@ -294,6 +296,7 @@ Happy GRDB! :gift:
[Fluent]: https://github.com/vapor/fluent
[FMDB]: http://github.com/ccgus/fmdb
[GRDB]: http://github.com/groue/GRDB.swift
[GRDBObjc]: http://github.com/groue/GRDBObjc
[PersistableRecord]: ../README.md#records
[Realm]: http://realm.io
[FetchableRecord]: ../README.md#records
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '5.9.0'
s.version = '5.3.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
File diff suppressed because it is too large. Load diff
+7 -23
View File
@@ -9,12 +9,12 @@ public struct Configuration {
/// If true, foreign key constraints are checked.
///
/// Default: true
public var foreignKeysEnabled = true
public var foreignKeysEnabled: Bool = true
/// If true, database modifications are disallowed.
///
/// Default: false
public var readonly = false
public var readonly: Bool = false
/// The configuration label.
///
@@ -91,7 +91,7 @@ public struct Configuration {
/// When true, the `Database.suspendNotification` and
/// `Database.resumeNotification` suspend and resume the database. Database
/// suspension helps avoiding the [`0xdead10cc`
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
///
/// During suspension, all database accesses but reads in WAL mode may throw
/// a DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. You can
@@ -108,9 +108,6 @@ public struct Configuration {
/// The function argument is run when an SQLite connection is opened,
/// before the connection is made available for database access methods.
///
/// This method can be called several times. The preparation functions are
/// run in the same order.
///
/// For example:
///
/// var config = Configuration()
@@ -118,21 +115,8 @@ public struct Configuration {
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
/// }
///
/// When you use a `DatabasePool`, preparation functions are called for
/// the writer connection and all reader connections. You can distinguish
/// them by querying `db.configuration.readonly`:
///
/// var config = Configuration()
/// config.prepareDatabase { db in
/// if db.configuration.readonly {
/// // reader connection
/// } else {
/// // writer connection
/// }
/// }
///
/// On newly created databases, `DatabasePool` the WAL mode is activated
/// after the preparation functions have run.
/// This method can be called several times. The setup functions are run in
/// the same order.
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
setups.append(setup)
}
@@ -175,11 +159,11 @@ public struct Configuration {
/// never allow leaving a transaction opened at the end of a read access.
///
/// Default: false
public var allowsUnsafeTransactions = false
public var allowsUnsafeTransactions: Bool = false
// MARK: - Concurrency
/// The behavior in case of SQLITE_BUSY error. See <https://www.sqlite.org/rescode.html#busy>
/// The behavior in case of SQLITE_BUSY error. See https://www.sqlite.org/rescode.html#busy
///
/// Default: immediateError
public var busyMode: Database.BusyMode = .immediateError
+21 -148
View File
@@ -9,16 +9,13 @@
//
//===----------------------------------------------------------------------===//
// MARK: - RangeReplaceableCollection, Sequence, Dictionary, Set extensions
// MARK: - Array, Sequence, Dictionary, Set extensions
extension RangeReplaceableCollection {
/// Creates a collection containing the elements of a cursor.
extension Array {
/// Creates an array containing the elements of a cursor.
///
/// // [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor)
///
/// - parameter cursor: The cursor whose elements feed the collection.
/// 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()
@@ -26,161 +23,24 @@ extension RangeReplaceableCollection {
append(element)
}
}
/// Creates a collection containing the elements of a cursor.
///
/// // [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor, minimumCapacity: 100)
///
/// - parameter cursor: The cursor whose elements feed the collection.
/// - parameter minimumCapacity: Prepares the returned collection to store
/// the specified number of elements.
@inlinable
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
self.init()
reserveCapacity(minimumCapacity)
while let element = try cursor.next() {
append(element)
}
}
}
extension Dictionary {
/// Creates a new dictionary whose keys are the groupings returned by the
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// // [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
///
/// - parameter cursor: A cursor of values to group into a dictionary.
/// - parameter keyForValue: A closure that returns a key for each element
/// in the cursor.
public init<C: Cursor>(grouping cursor: C, by keyForValue: (C.Element) throws -> Key)
public init<C: Cursor>(grouping values: C, by keyForValue: (C.Element) throws -> Key)
throws where Value == [C.Element]
{
self.init()
while let value = try cursor.next() {
while let value = try values.next() {
try self[keyForValue(value), default: []].append(value)
}
}
/// Creates a new dictionary whose keys are the groupings returned by the
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// // [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(
/// minimumCapacity: 100,
/// grouping: cursor,
/// by: { $0.teamID })
///
/// - parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
/// reallocating its storage buffer.
/// - parameter cursor: A cursor of values to group into a dictionary.
/// - parameter keyForValue: A closure that returns a key for each element
/// in the cursor.
public init<C: Cursor>(minimumCapacity: Int, grouping cursor: C, by keyForValue: (C.Element) throws -> Key)
throws where Value == [C.Element]
{
self.init(minimumCapacity: minimumCapacity)
while let value = try cursor.next() {
try self[keyForValue(value), default: []].append(value)
}
}
/// Creates a new dictionary from the key-value pairs in the given cursor.
///
/// You use this initializer to create a dictionary when you have a cursor
/// of key-value tuples with unique keys. Passing a cursor with duplicate
/// keys to this initializer results in a fatal error.
///
/// // [Int64: Player]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
///
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
/// new dictionary. Every key in `keysAndValues` must be unique.
/// - precondition: The cursor must not have duplicate keys.
public init<C: Cursor>(uniqueKeysWithValues keysAndValues: C)
throws where C.Element == (Key, Value)
{
self.init()
while let (key, value) = try keysAndValues.next() {
if updateValue(value, forKey: key) != nil {
fatalError("Duplicate values for key: '\(String(describing: key))'")
}
}
}
/// Creates a new dictionary from the key-value pairs in the given cursor.
///
/// You use this initializer to create a dictionary when you have a cursor
/// of key-value tuples with unique keys. Passing a cursor with duplicate
/// keys to this initializer results in a fatal error.
///
/// // [Int64: Player]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(
/// minimumCapacity: 100,
/// uniqueKeysWithValues: cursor)
///
/// - parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
/// reallocating its storage buffer.
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
/// new dictionary. Every key in `keysAndValues` must be unique.
/// - precondition: The cursor must not have duplicate keys.
public init<C: Cursor>(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: C)
throws where C.Element == (Key, Value)
{
self.init(minimumCapacity: minimumCapacity)
while let (key, value) = try keysAndValues.next() {
if updateValue(value, forKey: key) != nil {
fatalError("Duplicate values for key: '\(String(describing: key))'")
}
}
}
}
extension Set {
/// Creates a set containing the elements of a cursor.
///
/// // Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor)
///
/// - parameter cursor: A cursor of values to gather into a set.
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
while let element = try cursor.next() {
insert(element)
}
}
/// Creates a set containing the elements of a cursor.
///
/// // Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor, minimumCapacity: 100)
///
/// - parameter cursor: A cursor of values to gather into a set.
/// - parameter minimumCapacity: The minimum number of elements that the
/// newly created set should be able to store without reallocating its
/// storage buffer.
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
self.init(minimumCapacity: minimumCapacity)
while let element = try cursor.next() {
insert(element)
}
}
}
extension Sequence {
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Cursor>(
@@ -191,6 +51,19 @@ extension Sequence {
}
}
extension Set {
/// Creates a set containing the elements of a cursor.
///
/// 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()
while let element = try cursor.next() {
insert(element)
}
}
}
// MARK: - Cursor
/// A type that supplies the values of some external resource, one at a time.
+80 -267
View File
@@ -1,51 +1,4 @@
extension Database {
/// A SQLite schema. See <https://sqlite.org/lang_naming.html>
enum SchemaIdentifier: Hashable {
/// The main database
case main
/// The temp database
case temp
/// An attached database: <https://sqlite.org/lang_attach.html>
case attached(String)
/// The name of the schema in SQL queries
var sql: String {
switch self {
case .main: return "main"
case .temp: return "temp"
case let .attached(name): return name
}
}
/// The name of the master sqlite table
var masterTableName: String { // swiftlint:disable:this inclusive_language
switch self {
case .main: return "sqlite_master"
case .temp: return "sqlite_temp_master"
case let .attached(name): return "\(name).sqlite_master"
}
}
}
/// A table identifier
struct TableIdentifier {
/// The SQLite schema
var schemaID: SchemaIdentifier
/// The table name
var name: String
/// Returns the receiver, quoted for safe insertion as an identifier in
/// an SQL query.
///
/// // SELECT * FROM temp.player
/// db.execute(sql: "SELECT * FROM \(table.quotedDatabaseIdentifier)")
var quotedDatabaseIdentifier: String {
"\(schemaID.sql).\(name.quotedDatabaseIdentifier)"
}
}
// MARK: - Database Schema
@@ -57,8 +10,8 @@ extension Database {
SchedulingWatchdog.preconditionValidQueue(self)
schemaCache.clear()
// We also clear statement cache despite the automatic statement
// recompilation (see https://www.sqlite.org/c3ref/prepare.html)
// We also clear updateStatementCache and selectStatementCache despite
// the automatic statement recompilation (see https://www.sqlite.org/c3ref/prepare.html)
// because the automatic statement recompilation only happens a
// limited number of times.
internalStatementCache.clear()
@@ -68,55 +21,23 @@ extension Database {
/// Clears the database schema cache if the database schema has changed
/// since this method was last called.
func clearSchemaCacheIfNeeded() throws {
let schemaVersion = try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))
let schemaVersion = try Int32.fetchOne(internalCachedSelectStatement(sql: "PRAGMA schema_version"))
if _lastSchemaVersion != schemaVersion {
_lastSchemaVersion = schemaVersion
clearSchemaCache()
}
}
/// The list of database schemas, in the order of SQLite resolution:
/// temp, main, then attached databases.
func schemaIdentifiers() throws -> [SchemaIdentifier] {
if let schemaIdentifiers = schemaCache.schemaIdentifiers {
return schemaIdentifiers
}
var schemaIdentifiers = try Row
.fetchAll(self, sql: "PRAGMA database_list")
.map { row -> SchemaIdentifier in
switch row[1] as String {
case "main": return .main
case "temp": return .temp
case let other: return .attached(other)
}
}
// Temp schema shadows other schema: put it first
if let tempIdx = schemaIdentifiers.firstIndex(of: .temp) {
schemaIdentifiers.swapAt(tempIdx, 0)
}
schemaCache.schemaIdentifiers = schemaIdentifiers
return schemaIdentifiers
}
/// Returns whether a table exists in the main or temp schema.
/// Returns whether a table exists.
public func tableExists(_ name: String) throws -> Bool {
try schemaIdentifiers().contains {
try exists(type: .table, name: name, in: $0)
}
}
private func tableExists(_ table: TableIdentifier) throws -> Bool {
try exists(type: .table, name: table.name, in: table.schemaID)
try exists(type: .table, name: name)
}
/// Returns whether a table is an internal SQLite table.
///
/// Those are tables whose name begins with `sqlite_` and `pragma_`.
///
/// For more information, see <https://www.sqlite.org/fileformat2.html>
/// For more information, see https://www.sqlite.org/fileformat2.html
public static func isSQLiteInternalTable(_ tableName: String) -> Bool {
// https://www.sqlite.org/fileformat2.html#internal_schema_objects
// > The names of internal schema objects always begin with "sqlite_"
@@ -131,7 +52,7 @@ extension Database {
///
/// Those are tables whose name begins with `sqlite_` and `pragma_`.
///
/// For more information, see <https://www.sqlite.org/fileformat2.html>
/// For more information, see https://www.sqlite.org/fileformat2.html
@available(*, deprecated, message: "Use Database.isSQLiteInternalTable(_:) static method instead.")
public func isSQLiteInternalTable(_ tableName: String) -> Bool {
Self.isSQLiteInternalTable(tableName)
@@ -152,30 +73,26 @@ extension Database {
Self.isGRDBInternalTable(tableName)
}
/// Returns whether a view exists in the main or temp schema.
/// Returns whether a view exists.
public func viewExists(_ name: String) throws -> Bool {
try schemaIdentifiers().contains {
try exists(type: .view, name: name, in: $0)
}
try exists(type: .view, name: name)
}
/// Returns whether a trigger exists in the main or temp schema.
/// Returns whether a trigger exists.
public func triggerExists(_ name: String) throws -> Bool {
try schemaIdentifiers().contains {
try exists(type: .trigger, name: name, in: $0)
}
try exists(type: .trigger, name: name)
}
private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool {
private func exists(type: SchemaObjectType, name: String) throws -> Bool {
// SQlite identifiers are case-insensitive, case-preserving:
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
let name = name.lowercased()
return try schema(schemaID)
return try schema()
.names(ofType: type)
.contains { $0.lowercased() == name }
}
/// The primary key for table named `tableName`, in the main or temp schema.
/// The primary key for table named `tableName`.
///
/// All tables have a primary key, even when it is not explicit. When a
/// table has no explicit primary key, the result is the hidden
@@ -183,20 +100,10 @@ extension Database {
///
/// - throws: A DatabaseError if table does not exist.
public func primaryKey(_ tableName: String) throws -> PrimaryKeyInfo {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try primaryKey(TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
}
}
throw DatabaseError.noSuchTable(tableName)
}
/// Returns nil if table does not exist
private func primaryKey(_ table: TableIdentifier) throws -> PrimaryKeyInfo? {
SchedulingWatchdog.preconditionValidQueue(self)
if let primaryKey = schemaCache[table.schemaID].primaryKey(table.name) {
return primaryKey.value
if let primaryKey = schemaCache.primaryKey(tableName) {
return primaryKey
}
// https://www.sqlite.org/pragma.html
@@ -223,11 +130,7 @@ extension Database {
// 1 | name | TEXT | 0 | NULL | 0 |
// 2 | score | INTEGER | 0 | NULL | 0 |
guard let columns = try self.columns(in: table) else {
// table does not exist
schemaCache[table.schemaID].set(primaryKey: .missing, forTable: table.name)
return nil
}
let columns = try self.columns(in: tableName)
let primaryKey: PrimaryKeyInfo
let pkColumns = columns
@@ -265,14 +168,14 @@ extension Database {
if pkColumn.type.uppercased() == "INTEGER" {
primaryKey = .rowID(pkColumn.name)
} else {
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(table))
primaryKey = try .regular([pkColumn.name], tableHasRowID: tableHasRowID(tableName))
}
default:
// Multi-columns primary key
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(table))
primaryKey = try .regular(pkColumns.map(\.name), tableHasRowID: tableHasRowID(tableName))
}
schemaCache[table.schemaID].set(primaryKey: .value(primaryKey), forTable: table.name)
schemaCache.set(primaryKey: primaryKey, forTable: tableName)
return primaryKey
}
@@ -283,28 +186,18 @@ extension Database {
}
/// Returns whether the table has a rowid column.
///
/// - precondition: table exists.
private func tableHasRowID(_ table: TableIdentifier) throws -> Bool {
private func tableHasRowID(_ tableName: String) throws -> Bool {
// Not need to cache the result, because this information feeds
// `PrimaryKeyInfo`, which is cached.
do {
// Use a distinctive alias so that we better understand in the
// future why this query appears in the error log.
// https://github.com/groue/GRDB.swift/issues/945#issuecomment-804896196
//
// TODO: find a way to know if a table is WITHOUT ROWID without
// generating an error.
_ = try makeStatement(sql: """
SELECT rowid AS checkWithoutRowidOptimization FROM \(table.quotedDatabaseIdentifier)
""")
_ = try makeSelectStatement(sql: "SELECT rowid FROM \(tableName.quotedDatabaseIdentifier)")
return true
} catch DatabaseError.SQLITE_ERROR {
return false
}
}
/// The indexes on table named `tableName`, in the main or temp schema.
/// The indexes on table named `tableName`.
///
/// Only indexes on columns are returned. Indexes on expressions are
/// not returned.
@@ -314,35 +207,21 @@ extension Database {
///
/// If you want to know if a set of columns uniquely identify a row, prefer
/// `table(_:hasUniqueKey:)` instead.
///
/// - throws: A DatabaseError if table does not exist.
public func indexes(on tableName: String) throws -> [IndexInfo] {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try indexes(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
}
}
throw DatabaseError.noSuchTable(tableName)
}
/// Returns nil if table does not exist
private func indexes(on table: TableIdentifier) throws -> [IndexInfo]? {
if let indexes = schemaCache[table.schemaID].indexes(on: table.name) {
return indexes.value
if let indexes = schemaCache.indexes(on: tableName) {
return indexes
}
let indexes = try Row
// [seq:0 name:"index" unique:0 origin:"c" partial:0]
.fetchAll(self, sql: "PRAGMA \(table.schemaID.sql).index_list(\(table.name.quotedDatabaseIdentifier))")
.fetchAll(self, sql: "PRAGMA index_list(\(tableName.quotedDatabaseIdentifier))")
.compactMap { row -> IndexInfo? in
let indexName: String = row[1]
let unique: Bool = row[2]
let indexInfoRows = try Row
// [seqno:0 cid:2 name:"column"]
.fetchAll(self, sql: """
PRAGMA \(table.schemaID.sql).index_info(\(indexName.quotedDatabaseIdentifier))
""")
.fetchAll(self, sql: "PRAGMA index_info(\(indexName.quotedDatabaseIdentifier))")
// Sort by rank
.sorted(by: { ($0[0] as Int) < ($1[0] as Int) })
var columns: [String] = []
@@ -364,13 +243,12 @@ extension Database {
if indexes.isEmpty {
// PRAGMA index_list doesn't throw any error when table does
// not exist. So let's check if table exists:
if try tableExists(table) == false {
schemaCache[table.schemaID].set(indexes: .missing, forTable: table.name)
return nil
if try tableExists(tableName) == false {
throw DatabaseError(message: "no such table: \(tableName)")
}
}
schemaCache[table.schemaID].set(indexes: .value(indexes), forTable: table.name)
schemaCache.set(indexes: indexes, forTable: tableName)
return indexes
}
@@ -385,32 +263,17 @@ extension Database {
try columnsForUniqueKey(Array(columns), in: tableName) != nil
}
/// The foreign keys defined on table named `tableName`, in the main or temp schema.
///
/// - throws: A DatabaseError if table does not exist.
/// The foreign keys defined on table named `tableName`.
public func foreignKeys(on tableName: String) throws -> [ForeignKeyInfo] {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try foreignKeys(on: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
}
}
throw DatabaseError.noSuchTable(tableName)
}
/// Returns nil if table does not exist
private func foreignKeys(on table: TableIdentifier) throws -> [ForeignKeyInfo]? {
if let foreignKeys = schemaCache[table.schemaID].foreignKeys(on: table.name) {
return foreignKeys.value
if let foreignKeys = schemaCache.foreignKeys(on: tableName) {
return foreignKeys
}
var rawForeignKeys: [(
destinationTable: String,
mapping: [(origin: String, destination: String?, seq: Int)])] = []
var previousId: Int? = nil
for row in try Row.fetchAll(self, sql: """
PRAGMA \(table.schemaID.sql).foreign_key_list(\(table.name.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]
@@ -432,9 +295,8 @@ extension Database {
if rawForeignKeys.isEmpty {
// PRAGMA foreign_key_list doesn't throw any error when table does
// not exist. So let's check if table exists:
if try tableExists(table) == false {
schemaCache[table.schemaID].set(foreignKeys: .missing, forTable: table.name)
return nil
if try tableExists(tableName) == false {
throw DatabaseError(message: "no such table: \(tableName)")
}
}
@@ -457,51 +319,36 @@ extension Database {
return ForeignKeyInfo(destinationTable: destinationTable, mapping: completeMapping)
}
schemaCache[table.schemaID].set(foreignKeys: .value(foreignKeys), forTable: table.name)
schemaCache.set(foreignKeys: foreignKeys, forTable: tableName)
return foreignKeys
}
/// Returns the actual name of the database table, in the main or temp
/// schema, or nil if the table does not exist.
///
/// - throws: A DatabaseError if table does not exist.
func canonicalTableName(_ tableName: String) throws -> String? {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try schema(schemaIdentifier).canonicalName(tableName, ofType: .table) {
return result
}
/// Returns the actual name of the database table
func canonicalTableName(_ tableName: String) throws -> String {
guard let name = try schema().canonicalName(tableName, ofType: .table) else {
throw DatabaseError(message: "no such table: \(tableName)")
}
return nil
return name
}
func schema(_ schemaID: SchemaIdentifier) throws -> SchemaInfo {
if let schemaInfo = schemaCache[schemaID].schemaInfo {
func schema() throws -> SchemaInfo {
if let schemaInfo = schemaCache.schemaInfo {
return schemaInfo
}
let schemaInfo = try SchemaInfo(self, masterTableName: schemaID.masterTableName)
schemaCache[schemaID].schemaInfo = schemaInfo
let schemaInfo = try SchemaInfo(self)
schemaCache.schemaInfo = schemaInfo
return schemaInfo
}
}
extension Database {
/// The columns in the table named `tableName`, in the main or temp schema.
/// The columns in the table named `tableName`
///
/// - throws: A DatabaseError if table does not exist.
public func columns(in tableName: String) throws -> [ColumnInfo] {
for schemaIdentifier in try schemaIdentifiers() {
if let result = try columns(in: TableIdentifier(schemaID: schemaIdentifier, name: tableName)) {
return result
}
}
throw DatabaseError.noSuchTable(tableName)
}
/// Returns nil if table does not exist
private func columns(in table: TableIdentifier) throws -> [ColumnInfo]? {
if let columns = schemaCache[table.schemaID].columns(in: table.name) {
return columns.value
if let columns = schemaCache.columns(in: tableName) {
return columns
}
// https://www.sqlite.org/pragma.html
@@ -549,35 +396,27 @@ extension Database {
if sqlite3_libversion_number() < 3008005 {
// Work around a bug in SQLite where PRAGMA table_info would
// return a result even after the table was deleted.
if try !tableExists(table) {
schemaCache[table.schemaID].set(columns: .missing, forTable: table.name)
return nil
if try !tableExists(tableName) {
throw DatabaseError(message: "no such table: \(tableName)")
}
}
columnInfoQuery = "PRAGMA \(table.schemaID.sql).table_info(\(table.name.quotedDatabaseIdentifier))"
columnInfoQuery = "PRAGMA table_info(\(tableName.quotedDatabaseIdentifier))"
} else {
// Use PRAGMA table_xinfo so that we can load generated columns
columnInfoQuery = "PRAGMA \(table.schemaID.sql).table_xinfo(\(table.name.quotedDatabaseIdentifier))"
// For our purposes, we look for generated columns, not hidden
// columns. The "hidden" column magic numbers come from the SQLite
// source code. The values 2 and 3 refer to virtual and stored
// generated columns, respectively. Search for COLFLAG_VIRTUAL in
// https://www.sqlite.org/cgi/src/file?name=src/pragma.c&ci=fca8dc8b578f215a
columnInfoQuery = "SELECT * FROM pragma_table_xinfo('\(tableName)') WHERE hidden IN (0,2,3)"
}
let columns = try ColumnInfo
.fetchAll(self, sql: columnInfoQuery)
.filter {
// Purpose: keep generated columns, but discard hidden ones.
// The "hidden" column magic numbers come from the SQLite
// source code. The values 2 and 3 refer to virtual and stored
// generated columns, respectively, and 1 refer to hidden one.
// Search for COLFLAG_HIDDEN in
// https://www.sqlite.org/cgi/src/file?name=src/pragma.c&ci=fca8dc8b578f215a
$0.hidden != 1
}
.sorted(by: { $0.cid < $1.cid })
if columns.isEmpty {
// Table does not exist
schemaCache[table.schemaID].set(columns: .missing, forTable: table.name)
return nil
throw DatabaseError(message: "no such table: \(tableName)")
}
schemaCache[table.schemaID].set(columns: .value(columns), forTable: table.name)
schemaCache.set(columns: columns, forTable: tableName)
return columns
}
@@ -622,29 +461,22 @@ extension Database {
/// A column of a database table.
///
/// This type closely matches the information returned by the
/// `table_info` and `table_xinfo` pragmas.
/// `table_info` pragma.
///
/// sqlite> CREATE TABLE player (
/// ...> id INTEGER PRIMARY KEY,
/// ...> firstName TEXT,
/// ...> lastName TEXT);
/// sqlite> PRAGMA table_info(player);
/// cid name type notnull dflt_value pk
/// ------ ---------- ---------- ---------- ---------- -----
/// 0 id INTEGER 0 1
/// 1 firstName TEXT 0 0
/// 2 lastName TEXT 0 0
/// sqlite> PRAGMA table_xinfo(player);
/// cid name type notnull dflt_value pk hidden
/// ------ ---------- ---------- ---------- ---------- ----- ----------
/// 0 id INTEGER 0 1 0
/// 1 firstName TEXT 0 0 0
/// 2 lastName TEXT 0 0 0
/// > CREATE TABLE player (
/// id INTEGER PRIMARY KEY,
/// firstName TEXT,
/// lastName TEXT)
/// > PRAGMA table_info("player")
/// cid name type notnull dflt_value pk
/// ---- ----- ------- -------- ---------- ---
/// 0 id INTEGER 0 NULL 1
/// 1 name TEXT 0 NULL 0
/// 2 score INTEGER 0 NULL 0
///
/// See `Database.columns(in:)` and <https://www.sqlite.org/pragma.html#pragma_table_info>
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
public struct ColumnInfo: FetchableRecord {
let cid: Int
let hidden: Int?
/// The column name
public let name: String
@@ -689,8 +521,8 @@ public struct ColumnInfo: FetchableRecord {
/// the primary key for columns that are part of the primary key.
///
/// References:
/// - <https://sqlite.org/releaselog/3_7_16.html>
/// - <http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html>
/// - https://sqlite.org/releaselog/3_7_16.html
/// - http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html
public let primaryKeyIndex: Int
/// :nodoc:
@@ -701,7 +533,6 @@ public struct ColumnInfo: FetchableRecord {
isNotNull = row["notnull"]
defaultValueSQL = row["dflt_value"]
primaryKeyIndex = row["pk"]
hidden = row["hidden"]
}
}
@@ -838,24 +669,6 @@ public struct PrimaryKeyInfo {
return tableHasRowID
}
}
/// The name of the fastest primary key column
///
/// Returns nil for WITHOUT ROWID tables with a multi-columns primary key
var fastPrimaryKeyColumn: String? {
if let rowIDColumn = rowIDColumn {
// Prefer the user-provided name of the rowid
return rowIDColumn
} else if tableHasRowID {
// Prefer the rowid
return Column.rowID.name
} else if columns.count == 1 {
// WITHOUT ROWID table: use primary key column
return columns[0]
} else {
return nil
}
}
}
/// You get foreign keys from table names, with the
@@ -888,10 +701,11 @@ enum SchemaObjectType: String {
struct SchemaInfo: Equatable {
private var objects: Set<SchemaObject>
/// - parameter masterTable: "sqlite_master" or "sqlite_temp_master"
init(_ db: Database, masterTableName: String) throws { // swiftlint:disable:this inclusive_language
init(_ db: Database) throws {
objects = try Set(SchemaObject.fetchCursor(db, sql: """
SELECT type, name, tbl_name, sql FROM \(masterTableName)
SELECT type, name, tbl_name, sql, 0 AS isTemporary FROM sqlite_master \
UNION \
SELECT type, name, tbl_name, sql, 1 FROM sqlite_temp_master
"""))
}
@@ -910,9 +724,7 @@ struct SchemaInfo: Equatable {
/// try db.schema().canonicalName("foobar", ofType: .table) // "FooBar"
func canonicalName(_ name: String, ofType type: SchemaObjectType) -> String? {
let name = name.lowercased()
return objects
.first { $0.type == type.rawValue && $0.name.lowercased() == name }?
.name
return objects.first { $0.name.lowercased() == name }?.name
}
private struct SchemaObject: Codable, Hashable, FetchableRecord {
@@ -920,5 +732,6 @@ struct SchemaInfo: Equatable {
var name: String
var tbl_name: String?
var sql: String?
var isTemporary: Bool
}
}
+186 -485
View File
@@ -4,62 +4,6 @@ extension Database {
// MARK: - Statements
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?")
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
///
/// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// - parameter sql: An SQL query.
/// - returns: A Statement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func makeStatement(sql: String) throws -> Statement {
try makeStatement(sql: sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?")
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
///
/// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// - parameter sqlLiteral: An `SQL` literal.
/// - returns: A Statement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
/// - precondition: No argument must be set, or all arguments must be set.
/// An error is raised otherwise.
///
/// // OK
/// try makeStatement(literal: """
/// SELECT COUNT(*) FROM player WHERE score > ?
/// """)
/// try makeStatement(literal: """
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
/// """)
///
/// // NOT OK
/// try makeStatement(literal: """
/// SELECT COUNT(*) FROM player
/// WHERE color = ? AND score > \(1000)
/// """)
public func makeStatement(literal sqlLiteral: SQL) throws -> Statement {
let (sql, arguments) = try sqlLiteral.build(self)
let statement = try makeStatement(sql: sql)
if arguments.isEmpty == false {
// Throws if arguments do not match
try statement.setArguments(arguments)
}
return statement
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player WHERE id = ?")
@@ -67,139 +11,25 @@ extension Database {
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
///
/// - parameter sql: An SQL query.
/// - returns: A Statement.
/// - returns: A SelectStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
@available(*, deprecated, renamed: "makeStatement(sql:)")
public func makeSelectStatement(sql: String) throws -> Statement {
try makeStatement(sql: sql)
public func makeSelectStatement(sql: String) throws -> SelectStatement {
try makeSelectStatement(sql: sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// - parameter sqlLiteral: An `SQL` literal.
/// - returns: A Statement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
/// - precondition: No argument must be set, or all arguments must be set.
/// An error is raised otherwise.
///
/// // OK
/// try makeSelectStatement(literal: """
/// SELECT COUNT(*) FROM player WHERE score > ?
/// """)
/// try makeSelectStatement(literal: """
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
/// """)
///
/// // NOT OK
/// try makeSelectStatement(literal: """
/// SELECT COUNT(*) FROM player
/// WHERE color = ? AND score > \(1000)
/// """)
@available(*, deprecated, renamed: "makeStatement(literal:)")
public func makeSelectStatement(literal sqlLiteral: SQL) throws -> Statement {
try makeStatement(literal: sqlLiteral)
}
/// Returns a new prepared statement that can be reused.
///
/// let statement = try db.makeStatement(sql: "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])!
///
/// - parameter sql: An SQL query.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// SQLite 3.20.0, see <http://www.sqlite.org/c3ref/prepare.html>)
/// - returns: A Statement.
/// 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 makeStatement(sql: String, prepFlags: Int32) throws -> Statement {
let statements = SQLStatementCursor(database: self, sql: sql, arguments: nil, prepFlags: prepFlags)
guard let statement = try statements.next() else {
throw DatabaseError(
resultCode: .SQLITE_ERROR,
message: "empty statement",
sql: sql)
}
do {
guard try statements.next() == nil else {
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: """
Multiple statements found. To execute multiple statements, use \
Database.execute(sql:) or Database.allStatements(sql:) instead.
""",
sql: sql)
}
} catch {
// Something while would not compile was found after the first statement.
// Complain about multiple statements anyway.
throw DatabaseError(
resultCode: .SQLITE_MISUSE,
message: """
Multiple statements found. To execute multiple statements, use \
Database.execute(sql:) or Database.allStatements(sql:) instead.
""",
sql: sql)
}
return statement
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?")
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
///
/// let statement = try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// The returned statement may have already been used: it may or may not
/// contain values for its eventual arguments.
///
/// - parameter sql: An SQL query.
/// - returns: A Statement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
public func cachedStatement(sql: String) throws -> Statement {
try publicStatementCache.statement(sql)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?")
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
///
/// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// - parameter sqlLiteral: An `SQL` literal.
/// - returns: A Statement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
/// - precondition: No argument must be set, or all arguments must be set.
/// An error is raised otherwise.
///
/// // OK
/// try cachedStatement(literal: """
/// SELECT COUNT(*) FROM player WHERE score > ?
/// """)
/// try cachedStatement(literal: """
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
/// """)
///
/// // NOT OK
/// try cachedStatement(literal: """
/// SELECT COUNT(*) FROM player
/// WHERE color = ? AND score > \(1000)
/// """)
public func cachedStatement(literal sqlLiteral: SQL) throws -> Statement {
let (sql, arguments) = try sqlLiteral.build(self)
let statement = try cachedStatement(sql: sql)
if arguments.isEmpty == false {
// Throws if arguments do not match
try statement.setArguments(arguments)
}
return statement
func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement {
try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
@@ -212,45 +42,15 @@ extension Database {
/// contain values for its eventual arguments.
///
/// - parameter sql: An SQL query.
/// - returns: A Statement.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
@available(*, deprecated, renamed: "cachedStatement(sql:)")
public func cachedSelectStatement(sql: String) throws -> Statement {
try cachedStatement(sql: sql)
}
/// Returns a prepared statement that can be reused.
///
/// let statement = try db.cachedSelectStatement(literal: "SELECT COUNT(*) FROM player WHERE score > \(20)")
/// let moreThanTwentyCount = try Int.fetchOne(statement)!
///
/// - parameter sqlLiteral: An `SQL` literal.
/// - returns: A Statement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
/// - precondition: No argument must be set, or all arguments must be set.
/// An error is raised otherwise.
///
/// // OK
/// try cachedSelectStatement(literal: """
/// SELECT COUNT(*) FROM player WHERE score > ?
/// """)
/// try cachedSelectStatement(literal: """
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
/// """)
///
/// // NOT OK
/// try cachedSelectStatement(literal: """
/// SELECT COUNT(*) FROM player
/// WHERE color = ? AND score > \(1000)
/// """)
@available(*, deprecated, renamed: "cachedStatement(literal:)")
public func cachedSelectStatement(literal sqlLiteral: SQL) throws -> Statement {
try cachedStatement(literal: sqlLiteral)
public func cachedSelectStatement(sql: String) throws -> SelectStatement {
try publicStatementCache.selectStatement(sql)
}
/// Returns a cached statement that does not conflict with user's cached statements.
func internalCachedStatement(sql: String) throws -> Statement {
try internalStatementCache.statement(sql)
func internalCachedSelectStatement(sql: String) throws -> SelectStatement {
try internalStatementCache.selectStatement(sql)
}
/// Returns a new prepared statement that can be reused.
@@ -262,34 +62,23 @@ extension Database {
/// - parameter sql: An SQL query.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
@available(*, deprecated, renamed: "makeStatement(sql:)")
public func makeUpdateStatement(sql: String) throws -> Statement {
try makeStatement(sql: sql)
public func makeUpdateStatement(sql: String) throws -> UpdateStatement {
try makeUpdateStatement(sql: sql, prepFlags: 0)
}
/// Returns a new prepared statement that can be reused.
///
/// - parameter sqlLiteral: An `SQL` literal.
/// - returns: A Statement.
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)", prepFlags: 0)
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
///
/// - parameter sql: An SQL query.
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
/// 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.
/// - precondition: No argument must be set, or all arguments must be set.
/// An error is raised otherwise.
///
/// // OK
/// try makeUpdateStatement(literal: """
/// UPDATE player SET name = ?
/// """)
/// try makeUpdateStatement(literal: """
/// UPDATE player SET name = \("O'Brien")
/// """)
///
/// // NOT OK
/// try makeUpdateStatement(literal: """
/// UPDATE player SET name = ?, score = \(10)
/// """)
@available(*, deprecated, renamed: "makeStatement(literal:)")
public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> Statement {
try makeStatement(literal: sqlLiteral)
func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement {
try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags)
}
/// Returns a prepared statement that can be reused.
@@ -302,120 +91,15 @@ extension Database {
/// contain values for its eventual arguments.
///
/// - parameter sql: An SQL query.
/// - returns: A Statement.
/// - returns: An UpdateStatement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
@available(*, deprecated, renamed: "cachedStatement(sql:)")
public func cachedUpdateStatement(sql: String) throws -> Statement {
try cachedStatement(sql: sql)
public func cachedUpdateStatement(sql: String) throws -> UpdateStatement {
try publicStatementCache.updateStatement(sql)
}
/// Returns a new prepared statement that can be reused.
///
/// - parameter sqlLiteral: An `SQL` literal.
/// - returns: A Statement.
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
/// - precondition: No argument must be set, or all arguments must be set.
/// An error is raised otherwise.
///
/// // OK
/// try cachedUpdateStatement(literal: """
/// UPDATE player SET name = ?
/// """)
/// try cachedUpdateStatement(literal: """
/// UPDATE player SET name = \("O'Brien")
/// """)
///
/// // NOT OK
/// try cachedUpdateStatement(literal: """
/// UPDATE player SET name = ?, score = \(10)
/// """)
@available(*, deprecated, renamed: "cachedStatement(sql:)")
public func cachedUpdateStatement(literal sqlLiteral: SQL) throws -> Statement {
try cachedStatement(literal: sqlLiteral)
}
/// Returns a cursor of all SQL statements separated by semi-colons.
///
/// let statements = try db.allStatements(sql: """
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// INSERT INTO player (name) VALUES (?);
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
/// while let statement = try statements.next() {
/// try statement.execute()
/// }
///
/// - parameters:
/// - sql: An SQL query.
/// - arguments: Statement arguments.
/// - returns: A cursor of `Statement`
/// - throws: A DatabaseError whenever an SQLite error occurs.
/// - precondition: Arguments must be nil, or all arguments must be set.
/// The returned cursor will throw an error otherwise.
///
/// // OK
/// try allStatements(sql: """
/// SELECT COUNT(*) FROM player WHERE score < ?;
/// SELECT COUNT(*) FROM player WHERE score > ?;
/// """)
/// try allStatements(sql: """
/// SELECT COUNT(*) FROM player WHERE score < ?;
/// SELECT COUNT(*) FROM player WHERE score > ?;
/// """, arguments: [1000, 1000])
///
/// // NOT OK
/// try allStatements(sql: """
/// SELECT COUNT(*) FROM player WHERE score < ?;
/// SELECT COUNT(*) FROM player WHERE score > ?;
/// """, arguments: [1000])
public func allStatements(sql: String, arguments: StatementArguments? = nil)
throws -> SQLStatementCursor
{
SQLStatementCursor(database: self, sql: sql, arguments: arguments)
}
/// Returns a cursor of all SQL statements separated by semi-colons.
///
/// Literals allow you to safely embed raw values in your SQL, without any
/// risk of syntax errors or SQL injection:
///
/// let statements = try db.allStatements(literal: """
/// INSERT INTO player (name) VALUES (\("Arthur"));
/// INSERT INTO player (name) VALUES (\("Barbara"));
/// INSERT INTO player (name) VALUES (\("O'Brien"));
/// """)
/// while let statement = try statements.next() {
/// try statement.execute()
/// }
///
/// - parameter sqlLiteral: An `SQL` literal.
/// - returns: A cursor of `Statement`
/// - throws: A DatabaseError whenever an SQLite error occurs.
/// - precondition: No argument must be set, or all arguments must be set.
/// The returned cursor will throw an error otherwise.
///
/// // OK
/// try allStatements(literal: """
/// SELECT COUNT(*) FROM player WHERE score < ?;
/// SELECT COUNT(*) FROM player WHERE score > ?;
/// """)
/// try allStatements(literal: """
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
/// SELECT COUNT(*) FROM player WHERE score > \(1000);
/// """)
///
/// // NOT OK
/// try allStatements(literal: """
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
/// SELECT COUNT(*) FROM player WHERE score > ?;
/// """)
public func allStatements(literal sqlLiteral: SQL) throws -> SQLStatementCursor {
let context = SQLGenerationContext(self)
let sql = try sqlLiteral.sql(context)
let arguments = context.arguments.isEmpty
? nil // builds statements without arguments
: context.arguments // force arguments to match
return SQLStatementCursor(database: self, sql: sql, arguments: arguments)
/// Returns a cached statement that does not conflict with user's cached statements.
func internalCachedUpdateStatement(sql: String) throws -> UpdateStatement {
try internalStatementCache.updateStatement(sql)
}
/// Executes one or several SQL statements, separated by semi-colons.
@@ -437,17 +121,23 @@ extension Database {
/// - arguments: Statement arguments.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws {
try execute(literal: SQL(sql: sql, arguments: arguments))
try execute(literal: SQLLiteral(sql: sql, arguments: arguments))
}
/// Executes one or several SQL statements, separated by semi-colons.
///
/// Literals allow you to safely embed raw values in your SQL, without any
/// risk of syntax errors or SQL injection:
/// try db.execute(literal: SQLLiteral(
/// sql: "INSERT INTO player (name) VALUES (:name)",
/// arguments: ["name": "Arthur"]))
///
/// try db.execute(literal: """
/// INSERT INTO player (name) VALUES (\("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"));
@@ -457,108 +147,86 @@ extension Database {
///
/// This method may throw a DatabaseError.
///
/// - parameter sqlLiteral: An `SQL` literal.
/// - parameter sqlLiteral: An SQLLiteral.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(literal sqlLiteral: SQL) throws {
let statements = try allStatements(literal: sqlLiteral)
while let statement = try statements.next() {
try statement.execute()
}
}
}
public class SQLStatementCursor: Cursor {
private let database: Database
/// C string
private let buffer: UnsafeBufferPointer<CChar>
private let prepFlags: CInt
private let initialArgumentCount: Int?
private let sqlEnd: UnsafePointer<CChar>?
private var statementStart: UnsafePointer<CChar>?
/// Nil when arguments are set later
private var arguments: StatementArguments?
init(database: Database, sql: String, arguments: StatementArguments?, prepFlags: CInt = 0) {
self.database = database
self.arguments = arguments
self.prepFlags = prepFlags
self.initialArgumentCount = arguments?.values.count
self.buffer = sql.utf8CString.withUnsafeBufferPointer { buffer in
let rawBuffer = UnsafeRawBufferPointer(buffer)
let copy = UnsafeMutableRawBufferPointer.allocate(
byteCount: rawBuffer.count,
alignment: MemoryLayout<CChar>.alignment)
copy.copyMemory(from: rawBuffer)
return UnsafeBufferPointer(copy.bindMemory(to: CChar.self))
}
if let sqlStart = buffer.baseAddress {
statementStart = sqlStart
sqlEnd = sqlStart + buffer.count // past \0
} else {
statementStart = nil
sqlEnd = nil
}
}
deinit {
buffer.deallocate()
}
public func next() throws -> Statement? {
guard let statementStart = statementStart,
let sqlEnd = sqlEnd,
statementStart < sqlEnd
else {
try checkArgumentsAreEmpty()
return nil
}
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.
//
// This job is performed by StatementArguments.extractBindings(forStatement:allowingRemainingValues:)
//
// And before we return, we'll check that all arguments were consumed.
var statementEnd: UnsafePointer<Int8>? = nil
let authorizer = StatementCompilationAuthorizer()
let statement = try database.withAuthorizer(authorizer) {
try Statement(
database: database,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: authorizer)
}
let context = SQLGenerationContext(self)
let sql = try sqlLiteral.sql(context)
var arguments = context.arguments
let initialValuesCount = arguments.values.count
self.statementStart = statementEnd!
if let statement = statement {
if arguments != nil {
// Build a C string (SQLite wants that), and execute SQL statements one
// after the other.
try 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 {
var statementEnd: UnsafePointer<Int8>? = nil
let nextStatement: UpdateStatement?
// Compile
do {
let authorizer = StatementCompilationAuthorizer()
nextStatement = try withAuthorizer(authorizer) {
try UpdateStatement(
database: self,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: 0,
authorizer: authorizer)
}
}
guard let statement = nextStatement else {
// End of SQL string
break
}
// Extract statement arguments
let bindings = try arguments!.extractBindings(forStatement: statement, allowingRemainingValues: true)
let bindings = try arguments.extractBindings(forStatement: statement, allowingRemainingValues: true)
// unsafe is OK because we just extracted the correct number of arguments
statement.setUncheckedArguments(StatementArguments(bindings))
// Execute
try statement.execute()
// Next
statementStart = statementEnd!
}
return statement
} else {
try checkArgumentsAreEmpty()
return nil
}
}
/// Check that all arguments were consumed: it is a programmer error to
/// provide arguments that do not match the statements.
private func checkArgumentsAreEmpty() throws {
if let arguments = arguments,
let initialArgumentCount = initialArgumentCount,
arguments.values.isEmpty == false
{
// 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: \(initialArgumentCount)")
message: "wrong number of statement arguments: \(initialValuesCount)")
}
}
}
extension Database {
func executeStatement(_ statement: Statement) throws {
let authorizer = try statementWillExecute(statement)
let sqliteStatement = statement.sqliteStatement
func executeUpdateStatement(_ statement: UpdateStatement) throws {
// Two things must prevent the statement from executing: aborted
// transactions, and database suspension.
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
try checkForSuspensionViolation(from: statement)
if _isRecordingSelectedRegion {
_selectedRegion.formUnion(statement.databaseRegion)
}
let authorizer = observationBroker.updateStatementWillExecute(statement)
let sqliteStatement = statement.sqliteStatement
var code: Int32 = SQLITE_OK
withAuthorizer(authorizer) {
while true {
@@ -591,44 +259,27 @@ extension Database {
// We can now move on further tasks.
if code == SQLITE_DONE {
try statementDidExecute(statement)
try updateStatementDidExecute(statement)
} else {
assert(code != SQLITE_ROW)
try statementDidFail(statement, withResultCode: code)
try updateStatementDidFail(statement)
throw DatabaseError(
resultCode: code,
message: lastErrorMessage,
sql: statement.sql,
arguments: statement.arguments)
}
}
/// Returns the authorizer that should be used during statement execution
/// (this allows preventing the truncate optimization when there exists a
/// transaction observer for row deletion).
@usableFromInline
func statementWillExecute(_ statement: Statement) throws -> StatementAuthorizer? {
// Two things must prevent the statement from executing: aborted
// transactions, and database suspension.
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
try checkForSuspensionViolation(from: statement)
if _isRecordingSelectedRegion {
_selectedRegion.formUnion(statement.databaseRegion)
}
return observationBroker.statementWillExecute(statement)
}
/// May throw a cancelled commit error, if a transaction observer cancels
/// an empty transaction.
@usableFromInline
func statementDidExecute(_ statement: Statement) throws {
private func updateStatementDidExecute(_ statement: UpdateStatement) throws {
if statement.invalidatesDatabaseSchemaCache {
clearSchemaCache()
}
try observationBroker.statementDidExecute(statement)
try observationBroker.updateStatementDidExecute(statement)
}
/// Always throws an error
@usableFromInline
func statementDidFail(_ statement: Statement, withResultCode resultCode: Int32) throws -> Never {
private func updateStatementDidFail(_ statement: UpdateStatement) throws {
// Failed statements can not be reused, because sqlite3_reset won't
// be able to restore the statement to its initial state:
// https://www.sqlite.org/c3ref/reset.html
@@ -637,29 +288,44 @@ extension Database {
internalStatementCache.remove(statement)
publicStatementCache.remove(statement)
/// Exposes the user-provided cancelled commit error, if a transaction
/// observer has cancelled a transaction.
try observationBroker.statementDidFail(statement)
try observationBroker.updateStatementDidFail(statement)
}
@inline(__always)
func selectStatementWillExecute(_ statement: SelectStatement) throws {
// Two things must prevent the statement from executing: aborted
// transactions, and database suspension.
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
try checkForSuspensionViolation(from: statement)
throw DatabaseError(
resultCode: resultCode,
message: lastErrorMessage,
sql: statement.sql,
arguments: statement.arguments)
if _isRecordingSelectedRegion {
_selectedRegion.formUnion(statement.databaseRegion)
}
}
func selectStatementDidFail(_ statement: SelectStatement) {
// Failed statements can not be reused, because sqlite3_reset won't
// be able to restore the statement to its initial state:
// https://www.sqlite.org/c3ref/reset.html
//
// So make sure we clear this statement from the cache.
internalStatementCache.remove(statement)
publicStatementCache.remove(statement)
}
}
/// A thread-unsafe statement cache
struct StatementCache {
unowned let db: Database
private var statements: [String: Statement] = [:]
private var selectStatements: [String: SelectStatement] = [:]
private var updateStatements: [String: UpdateStatement] = [:]
init(database: Database) {
self.db = database
}
mutating func statement(_ sql: String) throws -> Statement {
if let statement = statements[sql] {
mutating func selectStatement(_ sql: String) throws -> SelectStatement {
if let statement = selectStatements[sql] {
return statement
}
@@ -673,26 +339,61 @@ struct StatementCache {
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let statement = try db.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
let statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
let statement: Statement
let statement: SelectStatement
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
// SQLite 3.24.0 or more
statement = try db.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
} else {
// SQLite 3.19.3 or less
statement = try db.makeStatement(sql: sql)
statement = try db.makeSelectStatement(sql: sql)
}
#endif
statements[sql] = statement
selectStatements[sql] = statement
return statement
}
mutating func updateStatement(_ sql: String) throws -> UpdateStatement {
if let statement = updateStatements[sql] {
return statement
}
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
// > planner that the prepared statement will be retained for a long
// > time and probably reused many times.
//
// This looks like a perfect match for cached statements.
//
// However SQLITE_PREPARE_PERSISTENT was only introduced in
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
#if GRDBCUSTOMSQLITE || GRDBCIPHER
let statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
#else
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
}
mutating func clear() {
statements = [:]
updateStatements = [:]
selectStatements = [:]
}
mutating func remove(_ statement: Statement) {
statements.removeFirst { $0.value === statement }
mutating func remove(_ statement: SelectStatement) {
selectStatements.removeFirst { $0.value === statement }
}
mutating func remove(_ statement: UpdateStatement) {
updateStatements.removeFirst { $0.value === statement }
}
}
+73 -73
View File
@@ -6,7 +6,6 @@ public typealias SQLiteConnection = OpaquePointer
/// A raw SQLite function argument.
typealias SQLiteValue = OpaquePointer
@usableFromInline
let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_destructor_type.self)
/// A Database connection.
@@ -33,7 +32,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// The error logging function.
///
/// Quoting <https://www.sqlite.org/errlog.html>:
/// Quoting https://www.sqlite.org/errlog.html:
///
/// > SQLite can be configured to invoke a callback function containing an
/// > error code and a terse error message whenever anomalies occur. This
@@ -72,7 +71,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// If no row has ever been inserted using this database connection,
/// returns zero.
///
/// For more detailed information, see <https://www.sqlite.org/c3ref/last_insert_rowid.html>
/// For more detailed information, see https://www.sqlite.org/c3ref/last_insert_rowid.html
public var lastInsertedRowID: Int64 {
SchedulingWatchdog.preconditionValidQueue(self)
return sqlite3_last_insert_rowid(sqliteConnection)
@@ -81,7 +80,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// The number of rows modified, inserted or deleted by the most recent
/// successful INSERT, UPDATE or DELETE statement.
///
/// For more detailed information, see <https://www.sqlite.org/c3ref/changes.html>
/// For more detailed information, see https://www.sqlite.org/c3ref/changes.html
public var changesCount: Int {
SchedulingWatchdog.preconditionValidQueue(self)
return Int(sqlite3_changes(sqliteConnection))
@@ -91,7 +90,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// INSERT, UPDATE or DELETE statements since the database connection was
/// opened.
///
/// For more detailed information, see <https://www.sqlite.org/c3ref/total_changes.html>
/// For more detailed information, see https://www.sqlite.org/c3ref/total_changes.html
public var totalChangesCount: Int {
SchedulingWatchdog.preconditionValidQueue(self)
return Int(sqlite3_total_changes(sqliteConnection))
@@ -126,27 +125,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - Internal properties
// Caches
struct SchemaCache {
var schemaIdentifiers: [SchemaIdentifier]?
fileprivate var schemas: [SchemaIdentifier: DatabaseSchemaCache] = [:]
subscript(schemaID: SchemaIdentifier) -> DatabaseSchemaCache { // internal so that it can be tested
get {
schemas[schemaID] ?? DatabaseSchemaCache()
}
set {
schemas[schemaID] = newValue
}
}
mutating func clear() {
schemaIdentifiers = nil
schemas.removeAll()
}
}
var _lastSchemaVersion: Int32? // Support for clearSchemaCacheIfNeeded()
var schemaCache = SchemaCache()
var schemaCache: DatabaseSchemaCache // internal so that it can be tested
lazy var internalStatementCache = StatementCache(database: self)
lazy var publicStatementCache = StatementCache(database: self)
@@ -162,8 +142,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
/// If true, select statement execution is recorded.
/// Use recordingSelectedRegion(_:), see `statementWillExecute(_:)`
var _isRecordingSelectedRegion = false
/// Use recordingSelectedRegion(_:), see `selectStatementWillExecute(_:)`
var _isRecordingSelectedRegion: Bool = false
var _selectedRegion = DatabaseRegion()
/// Support for checkForAbortedTransaction()
@@ -183,18 +163,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
private var functions = Set<DatabaseFunction>()
private var collations = Set<DatabaseCollation>()
private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly
private var isClosed = false
private var isClosed: Bool = false
// MARK: - Initializer
init(
path: String,
description: String,
configuration: Configuration) throws
configuration: Configuration,
schemaCache: DatabaseSchemaCache) throws
{
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
self.description = description
self.configuration = configuration
self.schemaCache = schemaCache
}
deinit {
@@ -204,7 +186,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - Database Opening
private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection {
// See <https://www.sqlite.org/c3ref/open.html>
// See https://www.sqlite.org/c3ref/open.html
var sqliteConnection: SQLiteConnection? = nil
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
guard code == SQLITE_OK else {
@@ -365,7 +347,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
//
// So let's fail early if file is not a database, or encrypted with
// another passphrase.
try makeStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next()
try makeSelectStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next()
}
// MARK: - Database Closing
@@ -415,7 +397,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// try Player.deleteAll(db, keys: ids)
/// }
///
/// See <https://www.sqlite.org/limits.html>
/// See https://www.sqlite.org/limits.html
/// and `SQLITE_LIMIT_VARIABLE_NUMBER`.
public var maximumStatementArgumentCount: Int {
Int(sqlite3_limit(sqliteConnection, SQLITE_LIMIT_VARIABLE_NUMBER, -1))
@@ -467,7 +449,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}, nil)
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage))
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
}
}
@@ -486,7 +468,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
func beginReadOnly() throws {
if configuration.readonly { return }
if _readOnlyDepth == 0 {
try internalCachedStatement(sql: "PRAGMA query_only = 1").execute()
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute()
}
_readOnlyDepth += 1
}
@@ -495,7 +477,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
if configuration.readonly { return }
_readOnlyDepth -= 1
if _readOnlyDepth == 0 {
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute()
}
}
@@ -512,7 +494,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
#if SQLITE_ENABLE_SNAPSHOT
/// Returns a snapshot that must be freed with `sqlite3_snapshot_free`.
///
/// See <https://www.sqlite.org/c3ref/snapshot.html>
/// See https://www.sqlite.org/c3ref/snapshot.html
func takeVersionSnapshot() throws -> UnsafeMutablePointer<sqlite3_snapshot> {
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
let code = withUnsafeMutablePointer(to: &snapshot) {
@@ -592,7 +574,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// // Stop tracing
/// db.trace(options: [])
///
/// See <https://www.sqlite.org/c3ref/trace_v2.html> for more information.
/// See https://www.sqlite.org/c3ref/trace_v2.html for more information.
///
/// - parameter options: The set of desired event kinds. Defaults to
/// `.statement`, which notifies all executed database statements.
@@ -700,8 +682,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// Runs a WAL checkpoint.
///
/// See <https://www.sqlite.org/wal.html> and
/// <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html> for
/// See https://www.sqlite.org/wal.html and
/// https://www.sqlite.org/c3ref/wal_checkpoint_v2.html for
/// more information.
///
/// - parameter kind: The checkpoint mode (default passive)
@@ -731,7 +713,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// MARK: - Interrupt
// See <https://www.sqlite.org/c3ref/interrupt.html>
// See https://www.sqlite.org/c3ref/interrupt.html
func interrupt() {
sqlite3_interrupt(sqliteConnection)
}
@@ -752,7 +734,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// Suspends the database. A suspended database prevents database locks in
/// order to avoid the [`0xdead10cc`
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
///
/// This method can be called from any thread.
///
@@ -773,7 +755,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
// Interrupt the database because this may trigger an
// SQLITE_INTERRUPT error which may itself abort a transaction and
// release a lock. See <https://www.sqlite.org/c3ref/interrupt.html>
// release a lock. See https://www.sqlite.org/c3ref/interrupt.html
interrupt()
// Now what about the eventual remaining lock? We'll issue a
@@ -784,7 +766,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// Resumes the database. A resumed database stops preventing database locks
/// in order to avoid the [`0xdead10cc`
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
///
/// This method can be called from any thread.
///
@@ -816,7 +798,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// Throws SQLITE_ABORT for suspended databases, if statement would lock
/// the database, in order to avoid the [`0xdead10cc`
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
func checkForSuspensionViolation(from statement: Statement) throws {
try $isSuspended.read { isSuspended in
guard isSuspended else {
@@ -834,7 +816,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return
}
if statement.releasesDatabaseLock {
if let updateStatement = statement as? UpdateStatement,
updateStatement.releasesDatabaseLock
{
// Accept statements that release locks:
// - COMMIT
// - ROLLBACK
@@ -882,7 +866,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
arguments: @autoclosure () -> StatementArguments? = nil)
throws
{
if isInsideTransactionBlock && sqlite3_get_autocommit(sqliteConnection) != 0 {
if isInsideTransactionBlock && !isInsideTransaction {
throw DatabaseError(
resultCode: .SQLITE_ABORT,
message: "Transaction was aborted",
@@ -908,7 +892,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is configuration.defaultTransactionKind, which itself
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - block: A block that executes SQL statements and return either
/// .commit or .rollback.
@@ -1009,6 +993,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return
}
// If the savepoint is top-level, we'll use ROLLBACK TRANSACTION in
// order to perform the special error handling of rollbacks (see
// the rollback method).
let topLevelSavepoint = !isInsideTransaction
// Begin savepoint
//
// We use a single name for savepoints because there is no need
@@ -1042,7 +1031,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
isInsideTransactionBlock = wasInsideTransactionBlock
try execute(sql: "RELEASE SAVEPOINT grdb")
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
assert(!topLevelSavepoint || !isInsideTransaction)
needsRollback = false
case .rollback:
needsRollback = true
@@ -1054,11 +1043,15 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
if needsRollback {
do {
// Rollback, and release the savepoint.
// Rollback alone is not enough to clear the savepoint from
// the SQLite savepoint stack.
try execute(sql: "ROLLBACK TRANSACTION TO SAVEPOINT grdb")
try execute(sql: "RELEASE SAVEPOINT grdb")
if topLevelSavepoint {
try rollback()
} else {
// Rollback, and release the savepoint.
// Rollback alone is not enough to clear the savepoint from
// the SQLite savepoint stack.
try execute(sql: "ROLLBACK TRANSACTION TO SAVEPOINT grdb")
try execute(sql: "RELEASE SAVEPOINT grdb")
}
} catch {
if firstError == nil {
firstError = error
@@ -1075,13 +1068,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
///
/// - parameter kind: The transaction type (default nil). If nil, the
/// transaction type is configuration.defaultTransactionKind, which itself
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - throws: The error thrown by the block.
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
let kind = kind ?? configuration.defaultTransactionKind
try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION")
assert(sqlite3_get_autocommit(sqliteConnection) == 0)
assert(isInsideTransaction)
}
/// Rollbacks a database transaction.
@@ -1128,13 +1121,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
if isInsideTransaction {
try execute(sql: "ROLLBACK TRANSACTION")
}
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
assert(!isInsideTransaction)
}
/// Commits a database transaction.
public func commit() throws {
try execute(sql: "COMMIT TRANSACTION")
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
assert(!isInsideTransaction)
}
// MARK: - Memory Management
@@ -1253,7 +1246,7 @@ extension Database {
}
try usePassphrase(data)
}
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
///
/// Call this method from `Configuration.prepareDatabase`,
@@ -1282,7 +1275,7 @@ extension Database {
}
try changePassphrase(data)
}
/// Changes the passphrase used by an SQLCipher encrypted database.
public func changePassphrase(_ passphrase: Data) throws {
// FIXME: sqlite3_rekey is discouraged.
@@ -1309,7 +1302,7 @@ extension Database {
// MARK: - Database-Related Types
/// See BusyMode and <https://www.sqlite.org/c3ref/busy_handler.html>
/// See BusyMode and https://www.sqlite.org/c3ref/busy_handler.html
public typealias BusyCallback = (_ numberOfTries: Int) -> Bool
/// When there are several connections to a database, a connection may try
@@ -1334,10 +1327,10 @@ extension Database {
///
/// Relevant SQLite documentation:
///
/// - <https://www.sqlite.org/c3ref/busy_timeout.html>
/// - <https://www.sqlite.org/c3ref/busy_handler.html>
/// - <https://www.sqlite.org/lang_transaction.html>
/// - <https://www.sqlite.org/wal.html>
/// - https://www.sqlite.org/c3ref/busy_timeout.html
/// - https://www.sqlite.org/c3ref/busy_handler.html
/// - https://www.sqlite.org/lang_transaction.html
/// - https://www.sqlite.org/wal.html
public enum BusyMode {
/// The SQLITE_BUSY error is immediately returned to the connection that
/// tries to access the locked database.
@@ -1348,7 +1341,7 @@ extension Database {
case timeout(TimeInterval)
/// A custom callback that is called when a database is locked.
/// See <https://www.sqlite.org/c3ref/busy_handler.html>
/// See https://www.sqlite.org/c3ref/busy_handler.html
case callback(BusyCallback)
}
@@ -1369,7 +1362,7 @@ extension Database {
/// A built-in SQLite collation.
///
/// See <https://www.sqlite.org/datatype3.html#collation>
/// See https://www.sqlite.org/datatype3.html#collation
public struct CollationName: RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
@@ -1396,7 +1389,7 @@ extension Database {
/// t.column("title", .text)
/// }
///
/// See <https://www.sqlite.org/datatype3.html>
/// See https://www.sqlite.org/datatype3.html
public struct ColumnType: RawRepresentable, Hashable {
/// :nodoc:
public let rawValue: String
@@ -1433,7 +1426,7 @@ extension Database {
/// An SQLite conflict resolution.
///
/// See <https://www.sqlite.org/lang_conflict.html>
/// See https://www.sqlite.org/lang_conflict.html.
public enum ConflictResolution: String {
/// The `ROLLBACK` conflict resolution
case rollback = "ROLLBACK"
@@ -1453,7 +1446,7 @@ extension Database {
/// A foreign key action.
///
/// See <https://www.sqlite.org/foreignkeys.html>
/// See https://www.sqlite.org/foreignkeys.html
public enum ForeignKeyAction: String {
/// The `CASCADE` foreign key action
case cascade = "CASCADE"
@@ -1475,13 +1468,13 @@ extension Database {
public struct TracingOptions: OptionSet {
/// The raw "Trace Event Code".
///
/// See <https://www.sqlite.org/c3ref/c_trace.html>
/// See https://www.sqlite.org/c3ref/c_trace.html
public let rawValue: CInt
/// Creates a `TracingOptions` from a raw "Trace Event Code".
///
/// See:
/// - <https://www.sqlite.org/c3ref/c_trace.html>
/// - https://www.sqlite.org/c3ref/c_trace.html
/// - `Database.trace(options:_:)`
public init(rawValue: CInt) {
self.rawValue = rawValue
@@ -1582,8 +1575,15 @@ extension Database {
/// An event reported by `TracingOptions.statement`.
case statement(Statement)
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
/// An event reported by `TracingOptions.profile`.
case profile(statement: Statement, duration: TimeInterval)
#elseif os(Linux)
#else
/// An event reported by `TracingOptions.profile`.
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
case profile(statement: Statement, duration: TimeInterval)
#endif
public var description: String {
switch self {
@@ -1605,7 +1605,7 @@ extension Database {
case rollback
}
/// An SQLite transaction kind. See <https://www.sqlite.org/lang_transaction.html>
/// An SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html
public enum TransactionKind: String {
/// The `DEFERRED` transaction kind
case deferred = "DEFERRED"
@@ -1617,7 +1617,7 @@ extension Database {
case exclusive = "EXCLUSIVE"
}
/// An SQLite threading mode. See <https://www.sqlite.org/threadsafe.html>.
/// An SQLite threading mode. See https://www.sqlite.org/threadsafe.html.
enum ThreadingMode {
case `default`
case multiThread
+1 -1
View File
@@ -51,7 +51,7 @@ extension DatabaseCollation: Hashable {
/// Two collations are equal if they share the same name (case insensitive)
/// :nodoc:
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
// See <https://www.sqlite.org/c3ref/create_collation.html>
// See https://www.sqlite.org/c3ref/create_collation.html
return sqlite3_stricmp(lhs.name, rhs.name) == 0
}
}
+5 -10
View File
@@ -2,7 +2,7 @@ import Foundation
/// An SQLite result code.
///
/// See <https://www.sqlite.org/rescode.html>
/// See https://www.sqlite.org/rescode.html
public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
/// The raw SQLite result code
public let rawValue: CInt
@@ -13,7 +13,7 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
}
/// A result code limited to the least significant 8 bits of the receiver.
/// See <https://www.sqlite.org/rescode.html> for more information.
/// See https://www.sqlite.org/rescode.html for more information.
///
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
@@ -193,7 +193,7 @@ extension ResultCode {
public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
/// The SQLite error code (see
/// <https://www.sqlite.org/rescode.html#primary_result_code_list>).
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
///
/// do {
/// ...
@@ -203,7 +203,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
///
/// This property returns a "primary result code", that is to say the least
/// significant 8 bits of any SQLite result code. See
/// <https://www.sqlite.org/rescode.html> for more information.
/// https://www.sqlite.org/rescode.html for more information.
///
/// See also `extendedResultCode`.
public var resultCode: ResultCode {
@@ -211,7 +211,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
}
/// The SQLite extended error code (see
/// <https://www.sqlite.org/rescode.html#extended_result_code_list>).
/// https://www.sqlite.org/rescode.html#extended_result_code_list).
///
/// do {
/// ...
@@ -248,14 +248,9 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
///
/// This initializer is not public because library user is not supposed to
/// be exposed to raw result codes.
@usableFromInline
init(resultCode: CInt, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
}
static func noSuchTable(_ tableName: String) -> Self {
DatabaseError(message: "no such table: \(tableName)")
}
}
// Support for `catch DatabaseError.SQLITE_XXX`
+13 -25
View File
@@ -107,20 +107,8 @@ public final class DatabaseFunction: Hashable {
self.kind = .aggregate { Aggregate() }
}
/// Returns an SQL expression that applies the function.
///
/// See <https://github.com/groue/GRDB.swift/#sql-functions>
public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression {
switch kind {
case .aggregate:
return .function(name, arguments.map(\.sqlExpression))
case .function:
return .aggregate(name, arguments.map(\.sqlExpression))
}
}
/// Calls sqlite3_create_function_v2
/// See <https://sqlite.org/c3ref/create_function.html>
/// See https://sqlite.org/c3ref/create_function.html
func install(in db: Database) {
// Retain the function definition
let definition = kind.definition
@@ -142,12 +130,12 @@ public final class DatabaseFunction: Hashable {
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage))
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
}
}
/// Calls sqlite3_create_function_v2
/// See <https://sqlite.org/c3ref/create_function.html>
/// See https://sqlite.org/c3ref/create_function.html
func uninstall(in db: Database) {
let code = sqlite3_create_function_v2(
db.sqliteConnection,
@@ -158,13 +146,13 @@ public final class DatabaseFunction: Hashable {
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage))
fatalError(DatabaseError(resultCode: code, message: db.lastErrorMessage).description)
}
}
/// The way to compute the result of a function.
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
private class FunctionDefinition {
let compute: (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?
init(compute: @escaping (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?) {
@@ -174,7 +162,7 @@ public final class DatabaseFunction: Hashable {
/// The way to start an aggregate.
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
private class AggregateDefinition {
let makeAggregate: () -> DatabaseAggregate
init(makeAggregate: @escaping () -> DatabaseAggregate) {
@@ -192,7 +180,7 @@ public final class DatabaseFunction: Hashable {
}
/// A function kind: an "SQL function" or an "aggregate".
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
/// See http://sqlite.org/capi3ref.html#sqlite3_create_function
private enum Kind {
/// A regular function: SELECT f(1)
case function((Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?)
@@ -201,7 +189,7 @@ public final class DatabaseFunction: Hashable {
case aggregate(() -> DatabaseAggregate)
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
var definition: AnyObject {
switch self {
case .function(let compute):
@@ -212,7 +200,7 @@ public final class DatabaseFunction: Hashable {
}
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
guard case .function = self else { return nil }
return { (sqliteContext, argc, argv) in
@@ -230,7 +218,7 @@ public final class DatabaseFunction: Hashable {
}
/// Feeds the `xStep` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
guard case .aggregate = self else { return nil }
return { (sqliteContext, argc, argv) in
@@ -250,7 +238,7 @@ public final class DatabaseFunction: Hashable {
}
/// Feeds the `xFinal` parameter of sqlite3_create_function_v2
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
var xFinal: (@convention(c) (OpaquePointer?) -> Void)? {
guard case .aggregate = self else { return nil }
return { (sqliteContext) in
@@ -278,8 +266,8 @@ public final class DatabaseFunction: Hashable {
///
/// The result must be released when the aggregate concludes.
///
/// See <https://sqlite.org/c3ref/context.html>
/// See <https://sqlite.org/c3ref/aggregate_context.html>
/// See https://sqlite.org/c3ref/context.html
/// See https://sqlite.org/c3ref/aggregate_context.html
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
// > The first time the sqlite3_aggregate_context(C,N) routine is called
// > for a particular aggregate function, SQLite allocates N of memory,
+4 -18
View File
@@ -42,6 +42,7 @@ public final class DatabasePool: DatabaseWriter {
writer = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: "GRDB.DatabasePool",
purpose: "writer")
@@ -59,6 +60,7 @@ public final class DatabasePool: DatabaseWriter {
return try SerializedDatabase(
path: path,
configuration: readerConfiguration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(readerCount)")
})
@@ -715,22 +717,6 @@ extension DatabasePool: DatabaseReader {
}
}
/// Asynchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
/// Updates are guaranteed an exclusive access to the database. They wait
/// until all pending writes and reads are completed. They postpone all
/// other writes and reads until they are completed.
///
/// - important: Reads executed by concurrent *database snapshots* are not
/// considered: they can run concurrently with the barrier updates.
/// - parameter updates: The updates to the database.
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
readerPool.asyncBarrier {
self.writer.sync(updates)
}
}
/// Synchronously executes database updates in a protected dispatch queue,
/// wrapped inside a transaction, and returns the result.
///
@@ -754,7 +740,7 @@ extension DatabasePool: DatabaseReader {
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is configuration.defaultTransactionKind, which itself
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - updates: The updates to the database.
/// - throws: The error thrown by the updates, or by the
@@ -1072,7 +1058,7 @@ extension DatabasePool {
/// You can create as many snapshots as you need, regardless of the maximum
/// number of reader connections in the pool.
///
/// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html>
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
public func makeSnapshot() throws -> DatabaseSnapshot {
// Sanity check
if writer.onValidQueue {
+7 -38
View File
@@ -36,6 +36,7 @@ public final class DatabaseQueue: DatabaseWriter {
writer = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: "GRDB.DatabaseQueue")
setupSuspension()
@@ -59,6 +60,7 @@ public final class DatabaseQueue: DatabaseWriter {
writer = try! SerializedDatabase(
path: ":memory:",
configuration: configuration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: "GRDB.DatabaseQueue")
}
@@ -188,16 +190,9 @@ extension DatabaseQueue {
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block.
public func read<T>(_ block: (Database) throws -> T) throws -> T {
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
try writer.sync { db in
// The transaction guarantees snapshot isolation against eventual
// external connection.
var result: T?
try db.inTransaction(.deferred) {
result = try db.readOnly { try block(db) }
return .commit
}
return result!
try db.readOnly { try block(db) }
}
}
@@ -219,9 +214,6 @@ extension DatabaseQueue {
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
writer.async { db in
do {
// The transaction guarantees snapshot isolation against eventual
// external connection.
try db.beginTransaction(.deferred)
try db.beginReadOnly()
} catch {
block(.failure(error))
@@ -232,7 +224,6 @@ extension DatabaseQueue {
// Ignore error because we can not notify it.
try? db.endReadOnly()
try? db.commit()
}
}
@@ -245,9 +236,6 @@ extension DatabaseQueue {
}
do {
// The transaction guarantees snapshot isolation against eventual
// external connection.
try db.beginTransaction(.deferred)
try db.beginReadOnly()
} catch {
block(.failure(error))
@@ -258,7 +246,6 @@ extension DatabaseQueue {
// Ignore error because we can not notify it.
try? db.endReadOnly()
try? db.commit()
}
}
@@ -302,14 +289,9 @@ extension DatabaseQueue {
try writer.execute { db in
// ... and that no transaction is opened.
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
// The transaction guarantees snapshot isolation against eventual
// external connection.
var result: T?
try db.inTransaction(.deferred) {
result = try db.readOnly { try block(db) }
return .commit
return try db.readOnly {
try block(db)
}
return result!
}
})
}
@@ -324,7 +306,6 @@ extension DatabaseQueue {
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
do {
try db.beginTransaction(.deferred)
try db.beginReadOnly()
} catch {
block(.failure(error))
@@ -335,7 +316,6 @@ extension DatabaseQueue {
// Ignore error because we can not notify it.
try? db.endReadOnly()
try? db.commit()
}
}
@@ -361,7 +341,7 @@ extension DatabaseQueue {
/// - parameters:
/// - kind: The transaction type (default nil). If nil, the transaction
/// type is configuration.defaultTransactionKind, which itself
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
/// for more information.
/// - updates: The updates to the database.
/// - throws: The error thrown by the updates, or by the
@@ -406,17 +386,6 @@ extension DatabaseQueue {
try writer.sync(updates)
}
/// Asynchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
/// Eventual concurrent database accesses are postponed until the updates
/// are completed.
///
/// - parameter updates: The updates to the database.
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
writer.async(updates)
}
/// Synchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
+1 -1
View File
@@ -120,7 +120,7 @@ public protocol DatabaseReader: AnyObject {
/// database updates are not visible inside the block:
///
/// try reader.asyncRead { dbResult in
/// do {
/// do (
/// let db = try dbResult.get()
/// // Those two values are guaranteed to be equal, even if the
/// // `player` table is modified between the two requests:
+24 -44
View File
@@ -20,9 +20,9 @@
///
/// - `DatabaseRegion(table:)`: the region that covers one database table.
///
/// - `Statement.databaseRegion`:
/// - `SelectStatement.databaseRegion`:
///
/// let statement = try db.makeStatement(sql: "SELECT name, score FROM player")
/// let statement = try db.makeSelectStatement(sql: "SELECT name, score FROM player")
/// let region = statement.databaseRegion
///
/// - `FetchRequest.databaseRegion(_:)`
@@ -30,9 +30,9 @@
/// let request = Player.filter(key: 1)
/// let region = try request.databaseRegion(db)
public struct DatabaseRegion: CustomStringConvertible, Equatable {
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
private let tableRegions: [String: TableRegion]?
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
private init(tableRegions: [String: TableRegion]?) {
self.tableRegions = tableRegions
}
@@ -64,20 +64,16 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
///
/// - parameter table: A table name.
public init(table: String) {
let table = CaseInsensitiveIdentifier(rawValue: table)
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
}
/// Full columns in a table: (some columns in a table) × (all rows)
init(table: String, columns: Set<String>) {
let table = CaseInsensitiveIdentifier(rawValue: table)
let columns = Set(columns.map(CaseInsensitiveIdentifier.init))
self.init(tableRegions: [table: TableRegion(columns: columns, rowIds: nil)])
}
/// Full rows in a table: (all columns in a table) × (some rows)
init(table: String, rowIds: Set<Int64>) {
let table = CaseInsensitiveIdentifier(rawValue: table)
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: rowIds)])
}
@@ -90,7 +86,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
guard let tableRegions = tableRegions else { return other }
guard let otherTableRegions = other.tableRegions else { return self }
var tableRegionsIntersection: [CaseInsensitiveIdentifier: TableRegion] = [:]
var tableRegionsIntersection: [String: TableRegion] = [:]
for (table, tableRegion) in tableRegions {
guard let otherTableRegion = otherTableRegions
.first(where: { (otherTable, _) in otherTable == table })?
@@ -109,7 +105,6 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
return DatabaseRegion(table: table, rowIds: rowIds)
}
let table = CaseInsensitiveIdentifier(rawValue: table)
guard let tableRegion = tableRegions[table] else {
return self
}
@@ -128,7 +123,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
guard let tableRegions = tableRegions else { return .fullDatabase }
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
var tableRegionsUnion: [CaseInsensitiveIdentifier: TableRegion] = [:]
var tableRegionsUnion: [String: TableRegion] = [:]
let tableNames = Set(tableRegions.keys).union(Set(otherTableRegions.keys))
for table in tableNames {
let tableRegion = tableRegions[table]
@@ -153,39 +148,24 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
self = union(other)
}
/// Returns a region suitable for database observation
func observableRegion(_ db: Database) throws -> DatabaseRegion {
// SQLite does not expose schema changes to the
// TransactionObserver protocol. By removing internal SQLite tables from
// the observed region, we optimize database observation.
//
// And by canonicalizing table names, we remove views, and help the
// `isModified` methods.
try ignoringInternalSQLiteTables().canonicalTables(db)
}
/// Returns a region only made of actual tables with their canonical names.
/// Canonical names help the `isModified` methods.
/// Returns a region suitable for database observation by removing views.
///
/// This method removes views (assuming no table exists with the same name
/// as a view).
private func canonicalTables(_ db: Database) throws -> DatabaseRegion {
/// We can do it because modifications only happen in actual tables. And we
/// want to do it because we have a fast path for regions that span a
/// single table.
func ignoringViews(_ db: Database) throws -> DatabaseRegion {
guard let tableRegions = tableRegions else { return .fullDatabase }
var region = DatabaseRegion()
for (table, tableRegion) in tableRegions {
if let canonicalTableName = try db.canonicalTableName(table.rawValue) {
let table = CaseInsensitiveIdentifier(rawValue: canonicalTableName)
region.formUnion(DatabaseRegion(tableRegions: [table: tableRegion]))
}
}
return region
let viewNames = try db.schema().names(ofType: .view)
guard viewNames.isEmpty == false else { return self }
let filteredRegions = tableRegions.filter { viewNames.contains($0.key) == false }
return DatabaseRegion(tableRegions: filteredRegions)
}
/// Returns a region which doesn't contain any SQLite internal table.
private func ignoringInternalSQLiteTables() -> DatabaseRegion {
func ignoringInternalSQLiteTables() -> DatabaseRegion {
guard let tableRegions = tableRegions else { return .fullDatabase }
let filteredRegions = tableRegions.filter {
!Database.isSQLiteInternalTable($0.key.rawValue)
!Database.isSQLiteInternalTable($0.key)
}
return DatabaseRegion(tableRegions: filteredRegions)
}
@@ -212,7 +192,7 @@ extension DatabaseRegion {
return true
}
guard let tableRegion = tableRegions[CaseInsensitiveIdentifier(rawValue: event.tableName)] else {
guard let tableRegion = tableRegions[event.tableName] else {
// FTS4 (and maybe other virtual tables) perform unadvertised
// changes. For example, an "INSERT INTO document ..." statement
// advertises an insertion in the `document` table, but the
@@ -260,11 +240,11 @@ extension DatabaseRegion {
return "empty"
}
return tableRegions
.sorted(by: { (l, r) in l.key.rawValue < r.key.rawValue })
.sorted(by: { (l, r) in l.key < r.key })
.map({ (table, tableRegion) in
var desc = table.rawValue
var desc = table
if let columns = tableRegion.columns {
desc += "(" + columns.map(\.rawValue).sorted().joined(separator: ",") + ")"
desc += "(" + columns.sorted().joined(separator: ",") + ")"
} else {
desc += "(*)"
}
@@ -278,7 +258,7 @@ extension DatabaseRegion {
}
private struct TableRegion: Equatable {
var columns: Set<CaseInsensitiveIdentifier>? // nil means "all columns"
var columns: Set<String>? // nil means "all columns"
var rowIds: Set<Int64>? // nil means "all rowids"
var isEmpty: Bool {
@@ -288,7 +268,7 @@ private struct TableRegion: Equatable {
}
func intersection(_ other: TableRegion) -> TableRegion {
let columnsIntersection: Set<CaseInsensitiveIdentifier>?
let columnsIntersection: Set<String>?
switch (self.columns, other.columns) {
case let (nil, columns), let (columns, nil):
columnsIntersection = columns
@@ -308,7 +288,7 @@ private struct TableRegion: Equatable {
}
func union(_ other: TableRegion) -> TableRegion {
let columnsUnion: Set<CaseInsensitiveIdentifier>?
let columnsUnion: Set<String>?
switch (self.columns, other.columns) {
case (nil, _), (_, nil):
columnsUnion = nil
+1 -1
View File
@@ -91,7 +91,7 @@ extension DatabaseRegionObservation {
// Use unsafeReentrantWrite so that observation can start from any
// dispatch queue.
return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in
let region = try observedRegion(db).observableRegion(db)
let region = try observedRegion(db).ignoringViews(db)
let observer = DatabaseRegionObserver(region: region, onChange: onChange)
db.add(transactionObserver: observer, extent: extent)
return observer
+12 -32
View File
@@ -1,30 +1,10 @@
/// A thread-unsafe database schema cache
struct DatabaseSchemaCache {
/// A cached value
///
/// We cache both hits and misses, because we often query both the temp
/// schema and the main schema: not remembering misses would have us
/// perform too many database queries.
enum Presence<T> {
/// Value does not exist in the schema.
case missing
/// Value exists in the schema.
case value(T)
var value: T? {
switch self {
case .missing: return nil
case let .value(value): return value
}
}
}
var schemaInfo: SchemaInfo?
private var primaryKeys: [String: Presence<PrimaryKeyInfo>] = [:]
private var columns: [String: Presence<[ColumnInfo]>] = [:]
private var indexes: [String: Presence<[IndexInfo]>] = [:]
private var foreignKeys: [String: Presence<[ForeignKeyInfo]>] = [:]
private var primaryKeys: [String: PrimaryKeyInfo] = [:]
private var columns: [String: [ColumnInfo]] = [:]
private var indexes: [String: [IndexInfo]] = [:]
private var foreignKeys: [String: [ForeignKeyInfo]] = [:]
mutating func clear() {
primaryKeys = [:]
@@ -34,35 +14,35 @@ struct DatabaseSchemaCache {
schemaInfo = nil
}
func primaryKey(_ table: String) -> Presence<PrimaryKeyInfo>? {
func primaryKey(_ table: String) -> PrimaryKeyInfo? {
primaryKeys[table]
}
mutating func set(primaryKey: Presence<PrimaryKeyInfo>, forTable table: String) {
mutating func set(primaryKey: PrimaryKeyInfo, forTable table: String) {
primaryKeys[table] = primaryKey
}
func columns(in table: String) -> Presence<[ColumnInfo]>? {
func columns(in table: String) -> [ColumnInfo]? {
columns[table]
}
mutating func set(columns: Presence<[ColumnInfo]>, forTable table: String) {
mutating func set(columns: [ColumnInfo], forTable table: String) {
self.columns[table] = columns
}
func indexes(on table: String) -> Presence<[IndexInfo]>? {
func indexes(on table: String) -> [IndexInfo]? {
indexes[table]
}
mutating func set(indexes: Presence<[IndexInfo]>, forTable table: String) {
mutating func set(indexes: [IndexInfo], forTable table: String) {
self.indexes[table] = indexes
}
func foreignKeys(on table: String) -> Presence<[ForeignKeyInfo]>? {
func foreignKeys(on table: String) -> [ForeignKeyInfo]? {
foreignKeys[table]
}
mutating func set(foreignKeys: Presence<[ForeignKeyInfo]>, forTable table: String) {
mutating func set(foreignKeys: [ForeignKeyInfo], forTable table: String) {
self.foreignKeys[table] = foreignKeys
}
}
+3 -2
View File
@@ -5,7 +5,7 @@ import Dispatch
///
/// See DatabasePool.makeSnapshot()
///
/// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html>
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
public class DatabaseSnapshot: DatabaseReader {
private var serializedDatabase: SerializedDatabase
@@ -26,6 +26,7 @@ public class DatabaseSnapshot: DatabaseReader {
serializedDatabase = try SerializedDatabase(
path: path,
configuration: configuration,
schemaCache: DatabaseSchemaCache(),
defaultLabel: defaultLabel,
purpose: purpose)
@@ -40,7 +41,7 @@ public class DatabaseSnapshot: DatabaseReader {
try db.beginTransaction(.deferred)
// Acquire snapshot isolation
try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
try db.internalCachedSelectStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
#if SQLITE_ENABLE_SNAPSHOT
// We must expect an error: https://www.sqlite.org/c3ref/snapshot_get.html
+65 -22
View File
@@ -4,8 +4,8 @@ import Foundation
/// DatabaseValue is the intermediate type between SQLite and your values.
///
/// See <https://www.sqlite.org/datatype3.html>
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLSpecificExpressible {
/// See https://www.sqlite.org/datatype3.html
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLExpression {
/// The SQLite storage
public let storage: Storage
@@ -86,7 +86,6 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
// MARK: - Not Public
@inlinable
init(storage: Storage) {
self.storage = storage
}
@@ -116,7 +115,6 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
}
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
@usableFromInline
init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_NULL:
@@ -139,24 +137,69 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
fatalError("Unexpected SQLite column type: \(type)")
}
}
}
extension DatabaseValue: StatementBinding {
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
switch storage {
case .null:
return sqlite3_bind_null(sqliteStatement, index)
case .int64(let int64):
return int64.bind(to: sqliteStatement, at: index)
case .double(let double):
return double.bind(to: sqliteStatement, at: index)
case .string(let string):
return string.bind(to: sqliteStatement, at: index)
case .blob(let data):
return data.bind(to: sqliteStatement, at: index)
// MARK: SQLExpression
/// :nodoc:
public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
if isNull {
// fast path for NULL
return "NULL"
} else if context.append(arguments: [self]) {
// Use statement arguments
return "?"
} else {
// Quoting needed: just use SQLite, which knows better.
return try String.fetchOne(context.db, sql: "SELECT QUOTE(?)", arguments: [self])!
}
}
/// :nodoc:
public func _identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set<Int64>? {
if isNull || self == false.databaseValue {
// Those requests select no row:
// - WHERE NULL
// - WHERE 0
return []
}
return nil
}
// Specific boolean checks for null, true, and false
/// :nodoc:
public func _is(_ test: _SQLBooleanTest) -> SQLExpression {
switch storage {
case .null:
return DatabaseValue.null
case .int64(let int64) where int64 == 0 || int64 == 1:
switch test {
case .true:
return (int64 == 1).sqlExpression
case .false, .falsey:
return (int64 == 0).sqlExpression
}
default:
switch test {
case .true:
return SQLExpressionEqual(.equal, self, true.sqlExpression)
case .false:
return SQLExpressionEqual(.equal, self, false.sqlExpression)
case .falsey:
return SQLExpressionNot(self)
}
}
}
/// :nodoc:
public var _isConstantInRequest: Bool { true }
/// :nodoc:
public var _isTrue: Bool { self == true.databaseValue }
/// :nodoc:
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { self }
}
// MARK: - Hashable & Equatable
@@ -221,7 +264,6 @@ extension DatabaseValue {
// DatabaseValueConvertible
extension DatabaseValue {
/// Returns self
@inlinable
public var databaseValue: DatabaseValue {
self
}
@@ -234,8 +276,9 @@ extension DatabaseValue {
// SQLExpressible
extension DatabaseValue {
/// :nodoc:
public var sqlExpression: SQLExpression {
.databaseValue(self)
self
}
}
+315
View File
@@ -0,0 +1,315 @@
// MARK: - Conversion Context and Errors
/// A type that helps the user understanding value conversion errors
struct ValueConversionContext: Refinable {
private enum Column {
case columnIndex(Int)
case columnName(String)
}
var row: Row?
var sql: String?
var arguments: StatementArguments?
private var column: Column?
func atColumn(_ columnIndex: Int) -> Self {
with(\.column, .columnIndex(columnIndex))
}
func atColumn(_ columnName: String) -> Self {
with(\.column, .columnName(columnName))
}
var columnIndex: Int? {
guard let column = column else { return nil }
switch column {
case .columnIndex(let index):
return index
case .columnName(let name):
return row?.index(forColumn: name)
}
}
var columnName: String? {
guard let column = column else { return nil }
switch column {
case .columnIndex(let index):
guard let row = row else { return nil }
return Array(row.columnNames)[index]
case .columnName(let name):
return name
}
}
}
extension ValueConversionContext {
init(_ statement: SelectStatement) {
self.init(
row: Row(statement: statement).copy(),
sql: statement.sql,
arguments: statement.arguments,
column: nil)
}
init(_ row: Row) {
if let statement = row.statement {
self.init(
row: row.copy(),
sql: statement.sql,
arguments: statement.arguments,
column: nil)
} else if let sqliteStatement = row.sqliteStatement {
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators)
self.init(
row: row.copy(),
sql: sql,
arguments: nil,
column: nil)
} else {
self.init(
row: row.copy(),
sql: nil,
arguments: nil,
column: nil)
}
}
}
/// The canonical conversion error message
///
/// - parameter dbValue: nil means "missing column"
func conversionErrorMessage<T>(
to: T.Type,
from dbValue: DatabaseValue?,
conversionContext: ValueConversionContext?)
-> String
{
var message: String
var extras: [String] = []
if let dbValue = dbValue {
message = "could not convert database value \(dbValue) to \(T.self)"
if let columnName = conversionContext?.columnName {
extras.append("column: `\(columnName)`")
}
if let columnIndex = conversionContext?.columnIndex {
extras.append("column index: \(columnIndex)")
}
} else {
message = "could not read \(T.self) from missing column"
if let columnName = conversionContext?.columnName {
message += " `\(columnName)`"
}
}
if let row = conversionContext?.row {
extras.append("row: \(row)")
}
if let sql = conversionContext?.sql {
extras.append("sql: `\(sql)`")
if let arguments = conversionContext?.arguments, arguments.isEmpty == false {
extras.append("arguments: \(arguments)")
}
}
if extras.isEmpty == false {
message += " (" + extras.joined(separator: ", ") + ")"
}
return message
}
/// The canonical conversion fatal error
///
/// - parameter dbValue: nil means "missing column", for consistency with (row["missing"] as DatabaseValue? == nil)
func fatalConversionError<T>(
to: T.Type,
from dbValue: DatabaseValue?,
conversionContext: ValueConversionContext?,
file: StaticString = #file,
line: UInt = #line)
-> Never
{
fatalError(
conversionErrorMessage(
to: T.self,
from: dbValue,
conversionContext: conversionContext),
file: file,
line: line)
}
@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,
from: DatabaseValue(sqliteStatement: sqliteStatement, index: 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 {
@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
} else {
fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext())
}
}
@usableFromInline
static func decode(from row: Row, atUncheckedIndex index: Int) -> Self {
decode(
from: row.impl.databaseValue(atUncheckedIndex: index),
conversionContext: ValueConversionContext(row).atColumn(index))
}
@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) {
return value
} else if dbValue.isNull {
return nil
} else {
fatalConversionError(to: Self.self, from: dbValue, conversionContext: conversionContext())
}
}
@usableFromInline
static func decodeIfPresent(from row: Row, atUncheckedIndex index: Int) -> Self? {
decodeIfPresent(
from: row.impl.databaseValue(atUncheckedIndex: index),
conversionContext: ValueConversionContext(row).atColumn(index))
}
}
// MARK: - DatabaseValueConvertible & StatementColumnConvertible
/// Lossless conversions from database values and rows
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@inlinable
static func fastDecode(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
fatalConversionError(to: Self.self, sqliteStatement: sqliteStatement, index: index)
}
return self.init(sqliteStatement: sqliteStatement, index: index)
}
@inlinable
static func fastDecode(from row: Row, atUncheckedIndex index: Int) -> Self {
if let sqliteStatement = row.sqliteStatement {
return fastDecode(from: sqliteStatement, atUncheckedIndex: Int32(index))
}
return row.fastDecode(Self.self, atUncheckedIndex: index)
}
@inlinable
static func fastDecodeIfPresent(from sqliteStatement: SQLiteStatement, atUncheckedIndex index: Int32) -> Self? {
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
return self.init(sqliteStatement: sqliteStatement, index: index)
}
@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.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
}
}
// Support for @inlinable decoding
extension Row {
@usableFromInline
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
-> Value
{
impl.fastDecode(type, atUncheckedIndex: index)
}
@usableFromInline
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
-> Value?
{
impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
}
}
+43 -186
View File
@@ -8,118 +8,27 @@
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = try db.makeStatement(sql: "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?
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
public protocol DatabaseValueConvertible: SQLExpressible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
/// Returns a value initialized from `dbValue`, if possible.
/// Returns a value initialized from *dbValue*, if possible.
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
}
extension DatabaseValueConvertible {
/// :nodoc:
public var sqlExpression: SQLExpression {
.databaseValue(databaseValue)
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
databaseValue.bind(to: sqliteStatement, at: index)
databaseValue
}
}
// MARK: - Conversions
extension DatabaseValueConvertible {
static func decode(
fromDatabaseValue dbValue: DatabaseValue,
context: @autoclosure () -> RowDecodingContext)
throws -> Self
{
if let value = fromDatabaseValue(dbValue) {
return value
} else {
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
}
}
@usableFromInline
static func decode(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: Int32,
context: @autoclosure () -> RowDecodingContext)
throws -> Self
{
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
return try decode(fromDatabaseValue: dbValue, context: context())
}
@usableFromInline
static func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self {
if let sqliteStatement = row.sqliteStatement {
return try decode(
fromStatement: sqliteStatement,
atUncheckedIndex: Int32(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
return try decode(
fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
static func decodeIfPresent(
fromDatabaseValue dbValue: DatabaseValue,
context: @autoclosure () -> RowDecodingContext)
throws -> Self?
{
// Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
if let value = fromDatabaseValue(dbValue) {
return value
} else if dbValue.isNull {
return nil
} else {
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
}
}
@usableFromInline
static func decodeIfPresent(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: Int32,
context: @autoclosure () -> RowDecodingContext)
throws -> Self?
{
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
if let value = fromDatabaseValue(dbValue) {
return value
} else if dbValue.isNull {
return nil
} else {
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
}
}
@usableFromInline
static func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self? {
if let sqliteStatement = row.sqliteStatement {
return try decodeIfPresent(
fromStatement: sqliteStatement,
atUncheckedIndex: Int32(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
return try decodeIfPresent(
fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
}
// MARK: - Cursors
/// A cursor of database values extracted from a single column.
/// For example:
///
@@ -130,16 +39,12 @@ extension DatabaseValueConvertible {
/// }
/// }
public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
@usableFromInline enum _State {
case idle, busy, done, failed
}
@usableFromInline let _statement: Statement
@usableFromInline let _statement: SelectStatement
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline let _columnIndex: Int32
@usableFromInline var _state = _State.idle
@usableFromInline var _done = false
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
_statement = statement
_sqliteStatement = statement.sqliteStatement
if let adapter = adapter {
@@ -148,16 +53,13 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor
} else {
_columnIndex = 0
}
_statement.reset(withArguments: arguments)
// Assume cursor is created for immediate iteration: reset and set arguments
statement.reset(withArguments: arguments)
// Assume cursor is created for iteration
try statement.database.selectStatementWillExecute(statement)
}
deinit {
if _state == .busy {
try? _statement.database.statementDidExecute(_statement)
}
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? _statement.reset()
@@ -165,38 +67,19 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor
@inlinable
public func next() throws -> Value? {
switch _state {
case .done:
if _done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
case .idle:
guard try _statement.database.statementWillExecute(_statement) == nil else {
throw DatabaseError(
resultCode: SQLITE_MISUSE,
message: "Can't run statement that requires a customized authorizer from a cursor",
sql: _statement.sql,
arguments: _statement.arguments)
}
_state = .busy
default:
break
}
switch sqlite3_step(_sqliteStatement) {
case SQLITE_DONE:
_state = .done
try _statement.database.statementDidExecute(_statement)
_done = true
return nil
case SQLITE_ROW:
// TODO GRDB6: don't crash on decoding errors
return try! Value.decode(
fromStatement: _sqliteStatement,
atUncheckedIndex: _columnIndex,
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
return Value.decode(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
case let code:
_state = .failed
try _statement.database.statementDidFail(_statement, withResultCode: code)
try _statement.didFail(withResultCode: code)
}
}
}
@@ -211,16 +94,12 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor
/// }
/// }
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
@usableFromInline enum _State {
case idle, busy, done, failed
}
@usableFromInline let _statement: Statement
@usableFromInline let _statement: SelectStatement
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline let _columnIndex: Int32
@usableFromInline var _state = _State.idle
@usableFromInline var _done = false
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
_statement = statement
_sqliteStatement = statement.sqliteStatement
if let adapter = adapter {
@@ -229,16 +108,13 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
} else {
_columnIndex = 0
}
_statement.reset(withArguments: arguments)
// Assume cursor is created for immediate iteration: reset and set arguments
statement.reset(withArguments: arguments)
// Assume cursor is created for iteration
try statement.database.selectStatementWillExecute(statement)
}
deinit {
if _state == .busy {
try? _statement.database.statementDidExecute(_statement)
}
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? _statement.reset()
@@ -246,38 +122,19 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
@inlinable
public func next() throws -> Value?? {
switch _state {
case .done:
if _done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
case .idle:
guard try _statement.database.statementWillExecute(_statement) == nil else {
throw DatabaseError(
resultCode: SQLITE_MISUSE,
message: "Can't run statement that requires a customized authorizer from a cursor",
sql: _statement.sql,
arguments: _statement.arguments)
}
_state = .busy
default:
break
}
switch sqlite3_step(_sqliteStatement) {
case SQLITE_DONE:
_state = .done
try _statement.database.statementDidExecute(_statement)
_done = true
return nil
case SQLITE_ROW:
// TODO GRDB6: don't crash on decoding errors
return try! Value.decodeIfPresent(
fromStatement: _sqliteStatement,
atUncheckedIndex: _columnIndex,
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
return Value.decodeIfPresent(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
case let code:
_state = .failed
try _statement.database.statementDidFail(_statement, withResultCode: code)
try _statement.didFail(withResultCode: code)
}
}
}
@@ -289,7 +146,7 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
///
/// let statement = try db.makeStatement(sql: "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
@@ -297,11 +154,11 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
extension DatabaseValueConvertible {
// MARK: Fetching From Prepared Statement
// MARK: Fetching From SelectStatement
/// Returns a cursor over values fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "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
/// ...
@@ -319,7 +176,7 @@ extension DatabaseValueConvertible {
/// - returns: A cursor over fetched values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchCursor(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> DatabaseValueCursor<Self>
@@ -329,7 +186,7 @@ extension DatabaseValueConvertible {
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try String.fetchAll(statement) // [String]
///
/// - parameters:
@@ -339,7 +196,7 @@ extension DatabaseValueConvertible {
/// - returns: An array.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchAll(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
@@ -352,7 +209,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.makeStatement(sql: "SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let name = try String.fetchOne(statement) // String?
///
/// - parameters:
@@ -362,7 +219,7 @@ extension DatabaseValueConvertible {
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
@@ -376,7 +233,7 @@ extension DatabaseValueConvertible {
extension DatabaseValueConvertible where Self: Hashable {
/// Returns a set of values fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try String.fetchSet(statement) // Set<String>
///
/// - parameters:
@@ -386,7 +243,7 @@ extension DatabaseValueConvertible where Self: Hashable {
/// - returns: A set.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Set<Self>
@@ -647,18 +504,18 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
/// 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.makeStatement(sql: "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?]
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
extension Optional where Wrapped: DatabaseValueConvertible {
// MARK: Fetching From Prepared Statement
// MARK: Fetching From SelectStatement
/// Returns a cursor over optional values fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "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?
/// ...
@@ -676,7 +533,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(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> NullableDatabaseValueCursor<Wrapped>
@@ -686,7 +543,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
/// Returns an array of optional values fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try Optional<String>.fetchAll(statement) // [String?]
///
/// - parameters:
@@ -696,7 +553,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(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
@@ -708,7 +565,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
extension Optional where Wrapped: DatabaseValueConvertible & Hashable {
/// Returns a set of optional values fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try Optional<String>.fetchSet(statement) // Set<String?>
///
/// - parameters:
@@ -718,7 +575,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & Hashable {
/// - returns: A set of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Set<Wrapped?>
+1 -54
View File
@@ -70,16 +70,6 @@ public protocol DatabaseWriter: DatabaseReader {
/// - throws: The error thrown by the updates.
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
/// Asynchronously executes database updates in a protected dispatch queue,
/// outside of any transaction, and returns the result.
///
/// Updates are guaranteed an exclusive access to the database. They wait
/// until all pending writes and reads are completed. They postpone all
/// other writes and reads until they are completed.
///
/// - parameter updates: The updates to the database.
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
/// Asynchronously executes database updates in a protected dispatch queue,
/// wrapped inside a transaction.
///
@@ -315,50 +305,11 @@ extension DatabaseWriter {
/// Rebuilds the database file, repacking it into a minimal amount of
/// disk space.
///
/// See <https://www.sqlite.org/lang_vacuum.html> for more information.
/// See https://www.sqlite.org/lang_vacuum.html for more information.
public func vacuum() throws {
try writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
}
// VACUUM INTO was introduced in SQLite 3.27.0:
// https://www.sqlite.org/releaselog/3_27_0.html
//
// Old versions of SQLCipher won't have it, but I don't know how to perform
// availability checks that depend on the version of the SQLCipher CocoaPod
// chosen by the application. So let's just have the method fail at runtime.
//
// This method is declared on DatabaseWriter instead of DatabaseReader,
// so that it is not available on DatabaseSnaphot. VACUUM INTO is not
// available inside the transaction that is kept open by DatabaseSnaphot.
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Creates a new database file at the specified path with a minimum
/// amount of disk space.
///
/// Databases encrypted with SQLCipher are copied with the same password
/// and configuration as the original database.
///
/// See <https://www.sqlite.org/lang_vacuum.html#vacuuminto> for more information.
///
/// - Parameter filePath: file path for new database
public func vacuum(into filePath: String) throws {
try writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
}
}
#else
/// Creates a new database file at the specified path with a minimum
/// amount of disk space.
/// See <https://www.sqlite.org/lang_vacuum.html#vacuuminto> for more information.
///
/// - Parameter filePath: file path for new database
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
public func vacuum(into filePath: String) throws {
try writeWithoutTransaction {
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
}
}
#endif
// MARK: - Database Observation
/// A write-only observation only uses the serialized writer
@@ -669,10 +620,6 @@ public final class AnyDatabaseWriter: DatabaseWriter {
try base.barrierWriteWithoutTransaction(updates)
}
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
base.asyncBarrierWriteWithoutTransaction(updates)
}
public func asyncWrite<T>(
_ updates: @escaping (Database) throws -> T,
completion: @escaping (Database, Result<T, Error>) -> Void)
+113 -12
View File
@@ -1,5 +1,53 @@
// MARK: - FetchRequest
/// Implementation details of `FetchRequest`.
///
/// :nodoc:
public protocol _FetchRequest {
/// The number of columns selected by the request.
///
/// This method makes it possible to find the columns of a CTE in a request
/// that includes a CTE association:
///
/// // WITH cte AS (SELECT 1 AS a, 2 AS b)
/// // SELECT player.*, cte.*
/// // FROM player
/// // JOIN cte
/// let cte = CommonTableExpression<Void>(named: "cte", sql: "SELECT 1 AS a, 2 AS b")
/// let request = Player
/// .with(cte)
/// .including(required: Player.association(to: cte))
/// let row = try Row.fetchOne(db, request)!
///
/// // We know that "SELECT 1 AS a, 2 AS b" selects two columns,
/// // so we can find cte columns in the row:
/// row.scopes["cte"] // [a:1, b:2]
///
/// :nodoc:
func _selectedColumnCount(_ db: Database) throws -> Int
/// Returns the request SQL.
///
/// This method makes it possible to embed a request as a subquery:
///
/// // SELECT *
/// // FROM "player"
/// // WHERE "score" = (SELECT MAX("score") FROM "player")
/// let maxScore = Player.select(max(Column("score")))
/// let players = try Player
/// .filter(Column("score") == maxScore)
/// .fetchAll(db)
///
/// - parameter context: An SQL generation context.
/// - parameter singleResult: A hint that a single result row will be
/// consumed. Implementations can optionally use it to optimize the
/// generated SQL, for example by adding a `LIMIT 1` SQL clause.
/// - returns: An SQL string.
///
/// :nodoc:
func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String
}
/// The protocol for all requests that fetch database rows, and tell how those
/// rows should be interpreted.
///
@@ -10,7 +58,7 @@
/// try request.fetchSet(db) // Set<Player>
/// try request.fetchOne(db) // Player?
/// try request.fetchCount(db) // Int
public protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible {
public protocol FetchRequest: _FetchRequest, DatabaseRegionConvertible, SQLExpression, SQLCollection {
/// The type that tells how fetched database rows should be interpreted.
associatedtype RowDecoder
@@ -36,12 +84,45 @@ public protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible {
}
extension FetchRequest {
// MARK: DatabaseRegionConvertible
/// Returns the database region that the request feeds from.
///
/// - parameter db: A database connection.
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion
}
// MARK: SQLCollection
/// :nodoc:
public var _collectionExpressions: [SQLExpression]? { nil }
/// :nodoc:
public func _collectionSQL(_ context: SQLGenerationContext) throws -> String {
try "("
+ _requestSQL(context, forSingleResult: false)
+ ")"
}
public func contains(_ value: SQLExpressible) -> SQLExpression {
SQLExpressionContains(value, self)
}
/// :nodoc:
public func _qualifiedCollection(with alias: TableAlias) -> SQLCollection { self }
// MARK: SQLExpression
/// :nodoc:
public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
try "("
+ _requestSQL(context, forSingleResult: false)
+ ")"
}
/// :nodoc:
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression { self }
}
// MARK: - PreparedRequest
@@ -49,7 +130,7 @@ extension FetchRequest {
/// A PreparedRequest is a request that is ready to be executed.
public struct PreparedRequest {
/// A prepared statement
public var statement: Statement
public var statement: SelectStatement
/// An eventual adapter for rows fetched by the select statement
public var adapter: RowAdapter?
@@ -58,7 +139,7 @@ public struct PreparedRequest {
var supplementaryFetch: ((Database, [Row]) throws -> Void)?
init(
statement: Statement,
statement: SelectStatement,
adapter: RowAdapter?,
supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil)
{
@@ -93,10 +174,6 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
self.adapter = adapter
}
public var sqlSubquery: SQLSubquery {
base.sqlSubquery
}
public func fetchCount(_ db: Database) throws -> Int {
try base.fetchCount(db)
}
@@ -116,6 +193,16 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
return preparedRequest
}
/// :nodoc:
public func _selectedColumnCount(_ db: Database) throws -> Int {
try base._selectedColumnCount(db)
}
/// :nodoc:
public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
try base._requestSQL(context, forSingleResult: singleResult)
}
}
// MARK: - AnyFetchRequest
@@ -135,8 +222,9 @@ public struct AnyFetchRequest<RowDecoder>: FetchRequest {
AnyFetchRequest<RowDecoder>(request: request)
}
public var sqlSubquery: SQLSubquery {
request.sqlSubquery
/// :nodoc:
public func _selectedColumnCount(_ db: Database) throws -> Int {
try request._selectedColumnCount(db)
}
public func fetchCount(_ db: Database) throws -> Int {
@@ -150,6 +238,11 @@ public struct AnyFetchRequest<RowDecoder>: FetchRequest {
{
try request.makePreparedRequest(db, forSingleResult: singleResult)
}
/// :nodoc:
public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
try request._requestSQL(context, forSingleResult: singleResult)
}
}
extension AnyFetchRequest {
@@ -165,7 +258,7 @@ extension AnyFetchRequest {
private class FetchRequestEraser: FetchRequest {
typealias RowDecoder = Void
var sqlSubquery: SQLSubquery {
func _selectedColumnCount(_ db: Database) throws -> Int {
fatalError("subclass must override")
}
@@ -176,6 +269,10 @@ private class FetchRequestEraser: FetchRequest {
func fetchCount(_ db: Database) throws -> Int {
fatalError("subclass must override")
}
func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
fatalError("subclass must override")
}
}
private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequestEraser {
@@ -185,8 +282,8 @@ private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequ
self.request = request
}
override var sqlSubquery: SQLSubquery {
request.sqlSubquery
override func _selectedColumnCount(_ db: Database) throws -> Int {
try request._selectedColumnCount(db)
}
override func fetchCount(_ db: Database) throws -> Int {
@@ -196,4 +293,8 @@ private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequ
override func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
try request.makePreparedRequest(db, forSingleResult: singleResult)
}
override func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
try request._requestSQL(context, forSingleResult: singleResult)
}
}
+167 -630
View File
File diff suppressed because it is too large. Load diff
+7 -14
View File
@@ -141,7 +141,7 @@ public protocol _RowLayout {
func _layoutIndex(ofColumn name: String) -> Int?
}
extension Statement: _RowLayout {
extension SelectStatement: _RowLayout {
/// :nodoc:
public var _layoutColumns: [(Int, String)] {
Array(columnNames.enumerated())
@@ -494,30 +494,23 @@ struct AdaptedRowImpl: RowImpl {
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
throws -> Value
atUncheckedIndex index: Int) -> Value
{
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex)
return Value.fastDecode(from: base, atUncheckedIndex: mappedIndex)
}
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
_ type: Value.Type,
atUncheckedIndex index: Int)
throws -> Value?
atUncheckedIndex index: Int) -> Value?
{
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return try Value.fastDecodeIfPresent(fromRow: base, atUncheckedIndex: mappedIndex)
return Value.fastDecodeIfPresent(from: base, atUncheckedIndex: mappedIndex)
}
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
func dataNoCopy(atUncheckedIndex index: Int) -> Data? {
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return try base.impl.fastDecodeDataNoCopy(atUncheckedIndex: mappedIndex)
}
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
return try base.impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: mappedIndex)
return base.impl.dataNoCopy(atUncheckedIndex: mappedIndex)
}
func columnName(atUncheckedIndex index: Int) -> String {
-205
View File
@@ -1,205 +0,0 @@
/// A key that is used to decode a value in a row
@usableFromInline
enum RowKey: Hashable {
/// A column name
case columnName(String)
/// A column index
case columnIndex(Int)
/// A scope
case scope(String)
/// A key of prefetched rows
case prefetchKey(String)
}
/// A decoding error
@usableFromInline
enum RowDecodingError: Error {
@usableFromInline
struct Context: CustomDebugStringConvertible {
/// A description of what went wrong, for debugging purposes.
@usableFromInline
let debugDescription: String
/// The row that could not be decoded
let row: Row
/// Nil for RowDecodingError.keyNotFound, in order to avoid redundancy
let key: RowKey?
/// The SQL query
let sql: String?
/// The SQL query arguments
let statementArguments: StatementArguments?
@usableFromInline
init(decodingContext: RowDecodingContext, debugDescription: String) {
self.debugDescription = debugDescription
self.row = decodingContext.row
self.key = decodingContext.key
self.sql = decodingContext.sql
self.statementArguments = decodingContext.statementArguments
}
}
case keyNotFound(RowKey, Context)
case valueMismatch(Any.Type, Context)
var context: Context {
switch self {
case .keyNotFound(_, let context),
.valueMismatch(_, let context):
return context
}
}
/// Convenience method that builds the
/// `could not decode <Type> from database value <value>` error message.
static func valueMismatch(
_ type: Any.Type,
context: RowDecodingContext,
databaseValue: DatabaseValue)
-> Self
{
valueMismatch(
type,
RowDecodingError.Context(decodingContext: context, debugDescription: """
could not decode \(type) from database value \(databaseValue)
"""))
}
/// Convenience method that builds the
/// `could not decode <Type> from database value <value>` error message.
@usableFromInline
static func valueMismatch(
_ type: Any.Type,
sqliteStatement: SQLiteStatement,
index: Int32,
context: RowDecodingContext)
-> Self
{
valueMismatch(
type,
context: context,
databaseValue: DatabaseValue(sqliteStatement: sqliteStatement, index: index))
}
/// Convenience method that builds the
/// `could not decode <Type> from database value <value>` error message.
@usableFromInline
static func valueMismatch(
_ type: Any.Type,
statement: Statement,
index: Int)
-> Self
{
valueMismatch(
type,
context: RowDecodingContext(statement: statement, index: index),
databaseValue: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: Int32(index)))
}
/// Convenience method that builds the `column not found: <column>`
/// error message.
@usableFromInline
static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
keyNotFound(
.columnName(columnName),
RowDecodingError.Context(decodingContext: context, debugDescription: """
column not found: \(String(reflecting: columnName))
"""))
}
}
@usableFromInline
struct RowDecodingContext {
/// The row that is decoded
let row: Row
let key: RowKey?
/// The SQL query
let sql: String?
/// The SQL query arguments
let statementArguments: StatementArguments?
@usableFromInline
init(row: Row, key: RowKey? = nil) {
if let statement = row.statement {
self.key = key
self.row = row.copy()
self.sql = statement.sql
self.statementArguments = statement.arguments
} else if let sqliteStatement = row.sqliteStatement {
self.key = key
self.row = row.copy()
self.sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators)
self.statementArguments = nil // Can't rebuild them
} else {
self.key = key
self.row = row.copy()
self.sql = nil
self.statementArguments = nil
}
}
/// Convenience initializer
@usableFromInline
init(statement: Statement, index: Int) {
self.key = .columnIndex(index)
self.row = Row(copiedFromSQLiteStatement: statement.sqliteStatement, statement: statement)
self.sql = statement.sql
self.statementArguments = statement.arguments
}
}
extension RowDecodingError: CustomStringConvertible {
@usableFromInline
var description: String {
let context = self.context
let row = context.row
var chunks: [String] = []
if let key = context.key {
switch key {
case let .columnIndex(columnIndex):
let rowIndex = row.index(row.startIndex, offsetBy: columnIndex)
let columnName = row.columnNames[rowIndex]
chunks.append("column: \(String(reflecting: columnName))")
chunks.append("column index: \(columnIndex)")
case let .columnName(columnName):
if let columnIndex = row.index(forColumn: columnName) {
chunks.append("column: \(String(reflecting: columnName))")
chunks.append("column index: \(columnIndex)")
} else {
// column name is already mentionned in context.debugDescription
}
case .prefetchKey:
// key is already mentionned in context.debugDescription
break
case .scope:
// scope is already mentionned in context.debugDescription
break
}
}
chunks.append("row: \(row.description)")
if let sql = context.sql {
chunks.append("sql: `\(sql)`")
}
if let statementArguments = context.statementArguments {
chunks.append("arguments: \(statementArguments)")
}
return "\(context.debugDescription) - \(chunks.joined(separator: ", "))"
}
}
-259
View File
@@ -1,259 +0,0 @@
/// `SQL` helps you build SQL literal with
/// [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: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
/// try db.execute(literal: query)
/// }
public struct SQL {
/// `SQL` is an array of elements which can be qualified with table
/// aliases. This is how `SQL` can blend well in the query interface.
enum Element {
// Can't be qualified with a table alias
case sql(String, StatementArguments = StatementArguments())
// Does not need to be qualified with a table alias
case subquery(SQLSubquery)
// Cases below can be qualified with a table alias
case expression(SQLExpression)
case selection(SQLSelection)
case ordering(SQLOrdering)
var isEmpty: Bool {
switch self {
case let .sql(sql, _):
return sql.isEmpty
default:
return false
}
}
fileprivate func sql(_ context: SQLGenerationContext) throws -> String {
switch self {
case let .sql(sql, arguments):
if context.append(arguments: arguments) == false {
// We don't know how to look for `?` in sql and
// replace them with literals.
fatalError("Not implemented: turning an SQL parameter into an SQL literal value")
}
return sql
case let .subquery(subquery):
return try subquery.sql(context)
case let .expression(expression):
return try expression.sql(context)
case let .selection(selection):
return try selection.sql(context)
case let .ordering(ordering):
return try ordering.sql(context)
}
}
fileprivate func qualified(with alias: TableAlias) -> Element {
switch self {
case .sql:
// Can't qualify raw SQL string
return self
case .subquery:
// Subqueries don't need table alias
return self
case let .expression(expression):
return .expression(expression.qualified(with: alias))
case let .selection(selection):
return .selection(selection.qualified(with: alias))
case let .ordering(ordering):
return .ordering(ordering.qualified(with: alias))
}
}
}
private(set) var elements: [Element]
init(elements: [Element]) {
self.elements = elements
}
/// Creates an `SQL` literal from a plain SQL string, and
/// eventual arguments.
///
/// For example:
///
/// let query = SQL(
/// sql: "UPDATE player SET name = ? WHERE id = ?",
/// arguments: [name, id])
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
self.init(elements: [.sql(sql, arguments)])
}
/// Creates an `SQL` literal from an SQL expression.
///
/// For example:
///
/// let columnLiteral = SQL(Column("username"))
/// let suffixLiteral = SQL("@example.com".databaseValue)
/// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ")
/// let request = User.select(emailLiteral.sqlExpression)
/// let emails = try String.fetchAll(db, request)
public init(_ expression: SQLSpecificExpressible) {
self.init(elements: [.expression(expression.sqlExpression)])
}
/// Returns true if this literal generates an empty SQL string
public var isEmpty: Bool {
elements.allSatisfy(\.isEmpty)
}
/// Turn a `SQL` literal into raw SQL and arguments.
///
/// - parameter db: A database connection.
/// - returns: A tuple made of a raw SQL string, and statement arguments.
public func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) {
let context = SQLGenerationContext(db)
let sql = try self.sql(context)
return (sql: sql, arguments: context.arguments)
}
/// Returns the literal SQL string given an SQL generation context.
func sql(_ context: SQLGenerationContext) throws -> String {
try elements.map { try $0.sql(context) }.joined()
}
func qualified(with alias: TableAlias) -> SQL {
SQL(elements: elements.map { $0.qualified(with: alias) })
}
}
extension SQL {
/// Returns the `SQL` literal produced by the concatenation of two literals.
///
/// let name = "O'Brien"
/// let selection: SQL = "SELECT * FROM player "
/// let condition: SQL = "WHERE name = \(name)"
/// let query = selection + condition
public static func + (lhs: SQL, rhs: SQL) -> SQL {
var result = lhs
result += rhs
return result
}
/// Appends an `SQL` literal to the receiver.
///
/// let name = "O'Brien"
/// var query: SQL = "SELECT * FROM player "
/// query += "WHERE name = \(name)"
public static func += (lhs: inout SQL, rhs: SQL) {
lhs.elements += rhs.elements
}
/// Appends an `SQL` literal to the receiver.
///
/// let name = "O'Brien"
/// var query: SQL = "SELECT * FROM player "
/// query.append(literal: "WHERE name = \(name)")
public mutating func append(literal sqlLiteral: SQL) {
self += sqlLiteral
}
/// Appends a plain SQL string to the receiver, and eventual arguments.
///
/// let name = "O'Brien"
/// var query: SQL = "SELECT * FROM player "
/// query.append(sql: "WHERE name = ?", arguments: [name])
public mutating func append(sql: String, arguments: StatementArguments = StatementArguments()) {
self += SQL(sql: sql, arguments: arguments)
}
}
extension SQL: SQLSpecificExpressible {
/// Creates a literal SQL expression.
///
/// Use this property when you need an explicit `SQLExpression`.
/// For example:
///
/// func date(_ value: SQLExpressible) -> SQLExpression {
/// SQL("DATE(\(value))").sqlExpression
/// }
///
/// // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
/// let createdAt = Column("createdAt")
/// let request = Player.filter(date(createdAt) == "2020-01-23")
public var sqlExpression: SQLExpression {
.literal(self)
}
}
extension SQL: SQLSelectable {
public var sqlSelection: SQLSelection {
.literal(self)
}
}
extension SQL: SQLOrderingTerm {
public var sqlOrdering: SQLOrdering {
.literal(self)
}
}
extension Sequence where Element == SQL {
/// Returns the concatenated `SQL` literal of this sequence of literals,
/// inserting the given separator between each element.
///
/// let components: [SQL] = [
/// "UPDATE player",
/// "SET name = \(name)",
/// "WHERE id = \(id)"
/// ]
/// let query = components.joined(separator: " ")
public func joined(separator: String = "") -> SQL {
if separator.isEmpty {
return SQL(elements: flatMap(\.elements))
} else {
return SQL(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
}
}
}
extension Collection where Element == SQL {
/// Returns the concatenated `SQL` literal of this collection of literals,
/// inserting the given SQL separator between each element.
///
/// let components: [SQL] = [
/// "UPDATE player",
/// "SET name = \(name)",
/// "WHERE id = \(id)"
/// ]
/// let query = components.joined(separator: " ")
public func joined(separator: String = "") -> SQL {
if separator.isEmpty {
return SQL(elements: flatMap(\.elements))
} else {
return SQL(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
}
}
}
// MARK: - ExpressibleByStringInterpolation
extension SQL: 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(elements: sqlInterpolation.elements)
}
}
+5 -33
View File
@@ -1,52 +1,24 @@
/// :nodoc:
public struct SQLInterpolation: StringInterpolationProtocol {
var elements: [SQL.Element]
var elements: [SQLLiteral.Element]
public init(literalCapacity: Int, interpolationCount: Int) {
elements = []
elements.reserveCapacity(interpolationCount + 1)
}
/// "SELECT * FROM player"
public mutating func appendLiteral(_ sql: String) {
if sql.isEmpty { return }
elements.append(.sql(sql))
}
/// Appends a raw SQL snippet, with eventual arguments.
///
/// For example:
///
/// "SELECT * FROM \(sql: "player")"
/// "SELECT * FROM player WHERE \(sql: "name = ?", arguments: ["O'Brien"])"
/// "SELECT * FROM \(sql: "player")"
public mutating func appendInterpolation(sql: String, arguments: StatementArguments = StatementArguments()) {
elements.append(.sql(sql, arguments))
}
/// Appends a raw `SQL` literal.
///
/// For example:
///
/// "SELECT * FROM \(SQL("player"))"
/// "SELECT * FROM player WHERE \(SQL("name = \("O'Brien")"))"
public mutating func appendInterpolation(_ sqlLiteral: SQL) {
elements.append(contentsOf: sqlLiteral.elements)
}
/// Appends a String expression.
///
/// For example:
///
/// "SELECT * FROM player WHERE name = \("O'Brien")"
public mutating func appendInterpolation<S: StringProtocol>(_ string: S) {
elements.append(.expression(String(string).sqlExpression))
}
/// Appends a raw `SQL` literal.
///
/// For example:
///
/// "SELECT * FROM player WHERE \(literal: "name = \("O'Brien")")"
public mutating func appendInterpolation(literal sqlLiteral: SQL) {
/// "SELECT * FROM player WHERE \(literal: condition)"
public mutating func appendInterpolation(literal sqlLiteral: SQLLiteral) {
elements.append(contentsOf: sqlLiteral.elements)
}
}
+368
View File
@@ -0,0 +1,368 @@
/// 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 {
/// SQLLiteral is an array of elements which can be qualified with
/// table aliases.
enum Element {
// Can't be qualified with a table alias
case sql(String, StatementArguments = StatementArguments())
// Does not need to be qualified with a table alias
case subquery(DatabasePromise<_FetchRequest>)
// Cases below can be qualified with a table alias
case expression(SQLExpression)
case selectable(SQLSelectable)
case orderingTerm(SQLOrderingTerm)
var isEmpty: Bool {
switch self {
case let .sql(sql, _):
return sql.isEmpty
default:
return false
}
}
fileprivate func sql(_ context: SQLGenerationContext) throws -> String {
switch self {
case let .sql(sql, arguments):
if context.append(arguments: arguments) == false {
// We don't know how to look for `?` in sql and
// replace them with literals.
fatalError("Not implemented: turning an SQL parameter into an SQL literal value")
}
return sql
case let .subquery(requestPromise):
return try requestPromise.resolve(context.db)._requestSQL(context, forSingleResult: false)
case let .expression(expression):
return try expression._expressionSQL(context, wrappedInParenthesis: false)
case let .selectable(selectable):
return try selectable._resultColumnSQL(context)
case let .orderingTerm(orderingTerm):
return try orderingTerm._orderingTermSQL(context)
}
}
fileprivate func qualified(with alias: TableAlias) -> Element {
switch self {
case .sql:
// Can't qualify raw SQL string
return self
case .subquery:
// Subqueries don't need table alias
return self
case let .expression(expression):
return .expression(expression._qualifiedExpression(with: alias))
case let .selectable(selectable):
return .selectable(selectable._qualifiedSelectable(with: alias))
case let .orderingTerm(orderingTerm):
return .orderingTerm(orderingTerm._qualifiedOrdering(with: alias))
}
}
}
private(set) var elements: [Element]
init(elements: [Element]) {
self.elements = elements
}
/// 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.init(elements: [.sql(sql, arguments)])
}
/// Creates an SQLLiteral from an SQL expression.
///
/// For example:
///
/// let columnLiteral = SQLLiteral(Column("username"))
/// let suffixLiteral = SQLLiteral("@example.com".databaseValue)
/// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ")
/// let request = User.select(emailLiteral.sqlExpression)
/// let emails = try String.fetchAll(db, request)
public init(_ expression: SQLExpression) {
self.init(elements: [.expression(expression)])
}
/// Returns true if this literal generates an empty SQL string
public var isEmpty: Bool {
elements.allSatisfy(\.isEmpty)
}
/// Turn a SQLLiteral into raw SQL and arguments.
///
/// - parameter db: A database connection.
/// - returns: A tuple made of a raw SQL string, and statement arguments.
public func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) {
let context = SQLGenerationContext(db)
let sql = try self.sql(context)
return (sql: sql, arguments: context.arguments)
}
/// Returns the literal SQL string given an SQL generation context.
func sql(_ context: SQLGenerationContext) throws -> String {
try elements.map { try $0.sql(context) }.joined()
}
func qualified(with alias: TableAlias) -> SQLLiteral {
SQLLiteral(elements: elements.map { $0.qualified(with: alias) })
}
}
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.elements += rhs.elements
}
/// 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 SQLLiteral {
/// Creates a literal SQL expression.
///
/// SQLLiteral(sql: "1 + 2").sqlExpression
/// SQLLiteral(sql: "? + ?", arguments: [1, 2]).sqlExpression
/// SQLLiteral(sql: ":one + :two", arguments: ["one": 1, "two": 2]).sqlExpression
public var sqlExpression: SQLExpression {
SQLExpressionLiteral(sqlLiteral: self)
}
var sqlSelectable: SQLSelectable {
SQLSelectionLiteral(sqlLiteral: self)
}
var sqlOrderingTerm: SQLOrderingTerm {
SQLOrderingLiteral(sqlLiteral: self)
}
}
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 {
if separator.isEmpty {
return SQLLiteral(elements: flatMap(\.elements))
} else {
return SQLLiteral(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
}
}
}
extension Collection where Element == SQLLiteral {
/// Returns the concatenated SQLLiteral of this collection of literals,
/// inserting the given SQL 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 {
if separator.isEmpty {
return SQLLiteral(elements: flatMap(\.elements))
} else {
return SQLLiteral(elements: Array(map(\.elements).joined(separator: CollectionOfOne(.sql(separator)))))
}
}
}
// MARK: - ExpressibleByStringInterpolation
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(elements: sqlInterpolation.elements)
}
}
// MARK: - SQLExpressionLiteral
// TODO: remove public qualifier when GRDB5 fixits are removed.
/// `SQLExpressionLiteral` is an expression built from a raw SQL snippet.
///
/// To build one, use the `SQLiteral.sqlExpression` property:
///
/// let name = "O'Brien"
/// let column = Column("name")
/// let literal: SQLLiteral = "\(column) = \(name)"
/// let expression = literal.sqlExpression
///
/// Such expressions can feed query interface requests:
///
/// try dbQueue.read { db in
/// // SELECT * FROM player WHERE name = 'O''Brien'
/// let players = try Player
/// .filter(expression)
/// .fetchAll(db)
///
/// // SELECT player.*, team.*
/// // FROM player
/// // JOIN team WHERE team.id = player.teamID
/// // WHERE player.name = 'O''Brien'
/// let players = try Player
/// .including(required: Player.team)
/// .filter(expression)
/// .fetchAll(db)
/// }
///
/// See SQLLiteral for more information.
///
/// :nodoc:
public struct SQLExpressionLiteral: SQLExpression {
let sqlLiteral: SQLLiteral
// Prefer SQLLiteral.sqlExpression
fileprivate init(sqlLiteral: SQLLiteral) {
self.sqlLiteral = sqlLiteral
}
/// :nodoc:
public func _expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
var resultSQL = try sqlLiteral.sql(context)
if wrappedInParenthesis {
resultSQL = "(\(resultSQL))"
}
return resultSQL
}
/// :nodoc:
public func _qualifiedExpression(with alias: TableAlias) -> SQLExpression {
sqlLiteral.qualified(with: alias).sqlExpression
}
}
// MARK: - SQLSelectionLiteral
struct SQLSelectionLiteral: SQLSelectable {
let sqlLiteral: SQLLiteral
// Prefer SQLLiteral.sqlSelectable
fileprivate init(sqlLiteral: SQLLiteral) {
self.sqlLiteral = sqlLiteral
}
func _columnCount(_ db: Database) throws -> Int {
fatalError("""
Selection literals don't known how many columns they contain. \
To resolve this error, select one or several literal expressions instead. \
See SQLLiteral.sqlExpression.
""")
}
func _count(distinct: Bool) -> _SQLCount? { nil }
func _countedSQL(_ context: SQLGenerationContext) throws -> String {
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several literal expressions instead. \
See SQLLiteral.sqlExpression.
""")
}
func _qualifiedSelectable(with alias: TableAlias) -> SQLSelectable {
sqlLiteral.qualified(with: alias).sqlSelectable
}
func _resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
try sqlLiteral.sql(context)
}
}
// MARK: - SQLOrderingLiteral
struct SQLOrderingLiteral: SQLOrderingTerm {
let sqlLiteral: SQLLiteral
// Prefer SQLLiteral.sqlOrderingTerm
fileprivate init(sqlLiteral: SQLLiteral) {
self.sqlLiteral = sqlLiteral
}
func _orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
try sqlLiteral.sql(context)
}
func _qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
sqlLiteral.qualified(with: alias).sqlOrderingTerm
}
var _reversed: SQLOrderingTerm {
fatalError("""
Ordering literals can't be reversed. \
To resolve this error, order by expression literals instead.
""")
}
}
+55 -82
View File
@@ -15,22 +15,9 @@ public struct SQLRequest<RowDecoder> {
/// The request adapter
public var adapter: RowAdapter?
private(set) var sqlLiteral: SQL
private(set) var sqlLiteral: SQLLiteral
let cache: Cache?
private init(
literal sqlLiteral: SQL,
adapter: RowAdapter?,
fromCache cache: Cache?,
type: RowDecoder.Type)
{
self.sqlLiteral = sqlLiteral
self.adapter = adapter
self.cache = cache
}
}
extension SQLRequest {
/// Creates a request from an SQL string, optional arguments, and
/// optional row adapter.
///
@@ -55,95 +42,66 @@ extension SQLRequest {
cached: Bool = false)
{
self.init(
literal: SQL(sql: sql, arguments: arguments),
literal: SQLLiteral(sql: sql, arguments: arguments),
adapter: adapter,
fromCache: cached ? .public : nil,
type: RowDecoder.self)
fromCache: cached ? .public : nil)
}
/// Creates a request from an `SQL` literal, and optional row adapter.
/// Creates a request from an SQLLiteral, and optional row adapter.
///
/// Literals allow you to safely embed raw values in your SQL, without any
/// risk of syntax errors or SQL injection:
/// 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 name = "O'brien"
/// let request = SQLRequest<Player>(literal: """
/// SELECT * FROM player WHERE name = \(name)
/// SELECT * FROM player WHERE name = \("O'brien")
/// """)
///
/// - parameters:
/// - sqlLiteral: An `SQL` literal.
/// - 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: SQL, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(
literal: sqlLiteral,
adapter: adapter,
fromCache: cached ? .public : nil,
type: RowDecoder.self)
}
}
extension SQLRequest where RowDecoder == Row {
/// Creates a request from an SQL string, optional arguments, and
/// optional row adapter.
///
/// let request = SQLRequest(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: SQL(sql: sql, arguments: arguments),
adapter: adapter,
fromCache: cached ? .public : nil,
type: Row.self)
public init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil)
}
/// Creates a request from an `SQL` literal, and optional row adapter.
/// Creates a request from an SQLLiteral, and optional row adapter.
///
/// Literals allow you to safely embed raw values in your SQL, without any
/// risk of syntax errors or SQL injection:
/// 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"]))
///
/// let name = "O'brien"
/// let request = SQLRequest(literal: """
/// SELECT * FROM player WHERE name = \(name)
/// 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 `SQL` literal.
/// - sqlLiteral: An SQLLiteral.
/// - adapter: Optional RowAdapter.
/// - cached: Defaults to false. If true, the request reuses a cached
/// prepared statement.
/// - cache: The eventual cache
/// - returns: A SQLRequest
public init(literal sqlLiteral: SQL, adapter: RowAdapter? = nil, cached: Bool = false) {
self.init(
literal: sqlLiteral,
adapter: adapter,
fromCache: cached ? .public : nil,
type: Row.self)
init(literal sqlLiteral: SQLLiteral, adapter: RowAdapter? = nil, fromCache cache: Cache?) {
self.sqlLiteral = sqlLiteral
self.adapter = adapter
self.cache = cache
}
}
extension SQLRequest: FetchRequest {
public var sqlSubquery: SQLSubquery {
.literal(sqlLiteral)
}
public func fetchCount(_ db: Database) throws -> Int {
try SQLRequest<Int>("SELECT COUNT(*) FROM (\(self))").fetchOne(db)!
}
@@ -155,18 +113,33 @@ extension SQLRequest: FetchRequest {
{
let context = SQLGenerationContext(db)
let sql = try sqlLiteral.sql(context)
let statement: Statement
let statement: SelectStatement
switch cache {
case .none:
statement = try db.makeStatement(sql: sql)
statement = try db.makeSelectStatement(sql: sql)
case .public?:
statement = try db.cachedStatement(sql: sql)
statement = try db.cachedSelectStatement(sql: sql)
case .internal?:
statement = try db.internalCachedStatement(sql: sql)
statement = try db.internalCachedSelectStatement(sql: sql)
}
try statement.setArguments(context.arguments)
return PreparedRequest(statement: statement, adapter: adapter)
}
/// :nodoc
public func _selectedColumnCount(_ db: Database) throws -> Int {
// Compile request. We can freely use the statement cache because we
// do not execute the statement or modify its arguments.
let context = SQLGenerationContext(db)
let sql = try _requestSQL(context, forSingleResult: false)
let statement = try db.cachedSelectStatement(sql: sql)
return statement.columnCount
}
/// :nodoc:
public func _requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
try sqlLiteral.sql(context)
}
}
extension SQLRequest: ExpressibleByStringInterpolation {
@@ -187,6 +160,6 @@ extension SQLRequest: ExpressibleByStringInterpolation {
/// :nodoc:
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
self.init(literal: SQL(stringInterpolation: sqlInterpolation))
self.init(literal: SQLLiteral(stringInterpolation: sqlInterpolation))
}
}
+1 -1
View File
@@ -6,7 +6,7 @@ import Dispatch
///
/// Generally speaking, each connection has its own dispatch queue. But it's not
/// enough: users need to use two database connections at the same time:
/// <https://github.com/groue/GRDB.swift/issues/55>. To support this use case, a
/// https://github.com/groue/GRDB.swift/issues/55. To support this use case, a
/// single dispatch queue can be temporarily shared by two or more connections.
///
/// - SchedulingWatchdog.makeSerializedQueue(allowingDatabase:) creates a
+3 -1
View File
@@ -17,6 +17,7 @@ final class SerializedDatabase {
init(
path: String,
configuration: Configuration = Configuration(),
schemaCache: DatabaseSchemaCache,
defaultLabel: String,
purpose: String? = nil)
throws
@@ -46,7 +47,8 @@ final class SerializedDatabase {
self.db = try Database(
path: path,
description: identifier,
configuration: config)
configuration: config,
schemaCache: schemaCache)
self.queue = configuration.makeDispatchQueue(label: identifier)
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
try queue.sync {
+219 -131
View File
@@ -9,65 +9,34 @@ extension CharacterSet {
}
/// A statement represents an SQL query.
public final class Statement {
enum TransactionEffect {
case beginTransaction
case commitTransaction
case rollbackTransaction
case beginSavepoint(String)
case releaseSavepoint(String)
case rollbackSavepoint(String)
}
///
/// It is the base class of UpdateStatement that executes *update statements*,
/// and SelectStatement that fetches rows.
public class Statement {
/// The raw SQLite statement, suitable for the SQLite C API.
public let sqliteStatement: SQLiteStatement
/// The SQL query
public var sql: String {
SchedulingWatchdog.preconditionValidQueue(database)
// trim white space and semicolumn for homogeneous output
return String(cString: sqlite3_sql(sqliteStatement))
.trimmingCharacters(in: .sqlStatementSeparators)
}
/// The column names, ordered from left to right.
public lazy var columnNames: [String] = {
let sqliteStatement = self.sqliteStatement
return (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
}()
// Database region is computed during statement compilation, and maybe
// extended for select statements compiled by QueryInterfaceRequest, in
// order to perform focused database observation. See
// SQLQueryGenerator.makeStatement(_:)
// SQLQueryGenerator.makeSelectStatement(_:)
/// The database region that the statement looks into.
public internal(set) var databaseRegion = DatabaseRegion()
/// If true, the database schema cache gets invalidated after this statement
/// is executed.
private(set) var invalidatesDatabaseSchemaCache = false
private(set) var transactionEffect: TransactionEffect?
private(set) var databaseEventKinds: [DatabaseEventKind] = []
/// Returns true if and only if the prepared statement makes no direct
/// changes to the content of the database file.
///
/// See <https://www.sqlite.org/c3ref/stmt_readonly.html>.
public var isReadonly: Bool {
var isReadonly: Bool {
sqlite3_stmt_readonly(sqliteStatement) != 0
}
@usableFromInline
unowned let database: Database
/// Cache for index(ofColumn:). Keys are lowercase.
private lazy var columnIndexes: [String: Int] = {
Dictionary(
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}()
/// Creates a prepared statement. Returns nil if the compiled string is
/// blank or empty.
///
@@ -77,7 +46,7 @@ public final class Statement {
/// - parameter statementEnd: Upon success, the pointer to the next
/// 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>)
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
/// - parameter authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error.
required init?(
@@ -120,16 +89,12 @@ public final class Statement {
self.database = database
self.sqliteStatement = statement
self.databaseRegion = authorizer.selectedRegion
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.transactionEffect = authorizer.transactionEffect
self.databaseEventKinds = authorizer.databaseEventKinds
}
deinit {
sqlite3_finalize(sqliteStatement)
}
@usableFromInline
final func reset() throws {
SchedulingWatchdog.preconditionValidQueue(database)
let code = sqlite3_reset(sqliteStatement)
@@ -141,10 +106,7 @@ public final class Statement {
// MARK: Arguments
@usableFromInline
var argumentsNeedValidation = true
@usableFromInline
var _arguments = StatementArguments()
lazy var sqliteArgumentCount: Int = {
@@ -226,6 +188,8 @@ public final class Statement {
bind(value, at: index)
} else if let value = valuesIterator.next() {
bind(value, at: index)
} else {
bind(.null, at: index)
}
}
}
@@ -260,61 +224,157 @@ public final class Statement {
}
// 1-based index
@inlinable
func bind<T: StatementBinding>(_ value: T, at index: CInt) {
let code = value.bind(to: sqliteStatement, at: index)
private func bind(_ dbValue: DatabaseValue, at index: Int32) {
let code: Int32
switch dbValue.storage {
case .null:
code = sqlite3_bind_null(sqliteStatement, index)
case .int64(let int64):
code = sqlite3_bind_int64(sqliteStatement, index, int64)
case .double(let double):
code = sqlite3_bind_double(sqliteStatement, index, double)
case .string(let string):
code = sqlite3_bind_text(sqliteStatement, index, string, -1, SQLITE_TRANSIENT)
case .blob(let data):
code = data.withUnsafeBytes {
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
}
}
// It looks like sqlite3_bind_xxx() functions do not access the file system.
// They should thus succeed, unless a GRDB bug: there is no point throwing any error.
guard code == SQLITE_OK else {
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql))
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
}
}
// Don't make this one public unless we keep the arguments property in sync.
@usableFromInline
func clearBindings() {
private func clearBindings() {
// It looks like sqlite3_clear_bindings() does not access the file system.
// This function call should thus succeed, unless a GRDB bug: there is
// no point throwing any error.
let code = sqlite3_clear_bindings(sqliteStatement)
guard code == SQLITE_OK else {
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql))
fatalError(DatabaseError(resultCode: code, message: database.lastErrorMessage, sql: sql).description)
}
}
func reset(withArguments arguments: StatementArguments?) {
fileprivate func prepare(withArguments arguments: StatementArguments?) {
// Force arguments validity: it is a programmer error to provide
// arguments that do not match the statement.
if let arguments = arguments {
try! setArguments(arguments)
} else if argumentsNeedValidation {
try! reset()
try! validateArguments(self.arguments)
}
}
}
@available(*, deprecated, renamed: "Statement")
public typealias SelectStatement = Statement
// MARK: - Statement Preparation
@available(*, deprecated, renamed: "Statement")
public typealias UpdateStatement = Statement
extension Statement: CustomStringConvertible {
public var description: String {
"SQL: \(sql), Arguments: \(arguments)"
extension Statement {
// Static method instead of an initializer because initializer can't run
// inside `sqlCodeUnits.withUnsafeBufferPointer`.
static func prepare(_ db: Database, sql: String, prepFlags: Int32) throws -> Self {
let authorizer = StatementCompilationAuthorizer()
return try db.withAuthorizer(authorizer) {
try sql.utf8CString.withUnsafeBufferPointer { buffer in
let statementStart = buffer.baseAddress!
var statementEnd: UnsafePointer<Int8>? = nil
guard let statement = try self.init(
database: db,
statementStart: statementStart,
statementEnd: &statementEnd,
prepFlags: prepFlags,
authorizer: authorizer) else
{
throw DatabaseError(
resultCode: .SQLITE_ERROR,
message: "empty statement",
sql: sql)
}
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(sql:) instead.
""",
sql: sql)
}
return statement
}
}
}
}
// MARK: - Select Statements
// MARK: - SelectStatement
extension Statement {
/// A subclass of Statement that fetches database rows.
///
/// You create SelectStatement with the Database.makeSelectStatement() method:
///
/// try dbQueue.read { db in
/// 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 {
/// 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
/// containing SQL.
/// - parameter statementEnd: Upon success, the pointer to the next
/// 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)
/// - parameter authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
{
try super.init(
database: database,
statementStart: statementStart,
statementEnd: statementEnd,
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.")
}
/// The number of columns in the resulting rows.
public var columnCount: Int {
Int(sqlite3_column_count(self.sqliteStatement))
}
/// The column names, ordered from left to right.
public lazy var columnNames: [String] = {
let sqliteStatement = self.sqliteStatement
return (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
}()
/// Cache for index(ofColumn:). Keys are lowercase.
private lazy var columnIndexes: [String: Int] = {
Dictionary(
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
}()
/// Returns the index of the leftmost column named `name`, in a
/// case-insensitive way.
public func index(ofColumn name: String) -> Int? {
@@ -327,6 +387,23 @@ extension Statement {
func makeCursor(arguments: StatementArguments? = nil) throws -> StatementCursor {
try StatementCursor(statement: self, arguments: arguments)
}
/// Utility function for cursors
func reset(withArguments arguments: StatementArguments? = nil) {
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)
}
}
/// A cursor that iterates a database statement without producing any value.
@@ -335,33 +412,26 @@ extension Statement {
/// For example:
///
/// try dbQueue.read { db in
/// let statement = db.makeStatement(sql: "SELECT performSideEffect()")
/// let statement = db.makeSelectStatement(sql: "SELECT performSideEffect()")
/// let cursor = statement.makeCursor()
/// try cursor.next()
/// }
final class StatementCursor: Cursor {
@usableFromInline enum _State {
case idle, busy, done, failed
}
let _statement: Statement
let _statement: SelectStatement
let _sqliteStatement: SQLiteStatement
var _state = _State.idle
var _done = false
// Use Statement.makeCursor() instead
init(statement: Statement, arguments: StatementArguments? = nil) throws {
// Use SelectStatement.makeCursor() instead
init(statement: SelectStatement, arguments: StatementArguments? = nil) throws {
_statement = statement
_sqliteStatement = statement.sqliteStatement
_statement.reset(withArguments: arguments)
// Assume cursor is created for immediate iteration: reset and set arguments
statement.reset(withArguments: arguments)
// Assume cursor is created for iteration
try statement.database.selectStatementWillExecute(statement)
}
deinit {
if _state == .busy {
try? _statement.database.statementDidExecute(_statement)
}
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? _statement.reset()
@@ -370,41 +440,53 @@ final class StatementCursor: Cursor {
/// :nodoc:
@inlinable
func next() throws -> Void? {
switch _state {
case .done:
if _done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
case .idle:
guard try _statement.database.statementWillExecute(_statement) == nil else {
throw DatabaseError(
resultCode: SQLITE_MISUSE,
message: "Can't run statement that requires a customized authorizer from a cursor",
sql: _statement.sql,
arguments: _statement.arguments)
}
_state = .busy
default:
break
}
switch sqlite3_step(_sqliteStatement) {
case SQLITE_DONE:
_state = .done
try _statement.database.statementDidExecute(_statement)
_done = true
return nil
case SQLITE_ROW:
return .some(())
case let code:
_state = .failed
try _statement.database.statementDidFail(_statement, withResultCode: code)
try _statement.didFail(withResultCode: code)
}
}
}
// MARK: - Update Statements
extension Statement {
// MARK: - UpdateStatement
/// A subclass of Statement that executes SQL queries.
///
/// You create UpdateStatement with the Database.makeUpdateStatement() method:
///
/// try dbQueue.inTransaction { db in
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
/// try statement.execute(arguments: ["Arthur"])
/// try statement.execute(arguments: ["Barbara"])
/// return .commit
/// }
public final class UpdateStatement: Statement {
enum TransactionEffect {
case beginTransaction
case commitTransaction
case rollbackTransaction
case beginSavepoint(String)
case releaseSavepoint(String)
case rollbackSavepoint(String)
}
/// If true, the database schema cache gets invalidated after this statement
/// is executed.
private(set) var invalidatesDatabaseSchemaCache: Bool = false
private(set) var transactionEffect: TransactionEffect?
private(set) var databaseEventKinds: [DatabaseEventKind] = []
var releasesDatabaseLock: Bool {
guard let transactionEffect = transactionEffect else {
return false
@@ -424,38 +506,58 @@ extension Statement {
}
}
/// Executes the 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
/// containing SQL.
/// - parameter statementEnd: Upon success, the pointer to the next
/// 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)
/// - parameter authorizer: A StatementCompilationAuthorizer
/// - throws: DatabaseError in case of compilation error.
required init?(
database: Database,
statementStart: UnsafePointer<Int8>,
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
prepFlags: Int32,
authorizer: StatementCompilationAuthorizer) throws
{
try super.init(
database: database,
statementStart: statementStart,
statementEnd: statementEnd,
prepFlags: prepFlags,
authorizer: authorizer)
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.transactionEffect = authorizer.transactionEffect
self.databaseEventKinds = authorizer.databaseEventKinds
}
/// Executes the SQL query.
///
/// - parameter arguments: Optional statement arguments.
/// - throws: A DatabaseError whenever an SQLite error occurs.
public func execute(arguments: StatementArguments? = nil) throws {
SchedulingWatchdog.preconditionValidQueue(database)
reset(withArguments: arguments)
prepare(withArguments: arguments)
try reset()
// Statement does not know how to execute itself, because it does not
// know how to handle its errors, or if truncate optimisation should be
// prevented or not. Database knows.
try database.executeStatement(self)
try database.executeUpdateStatement(self)
}
}
// MARK: - StatementBinding
public protocol StatementBinding {
/// Binds a statement argument.
///
/// - parameter sqliteStatement: An SQLite statement.
/// - parameter index: 1-based index to statement arguments
/// - returns: the code returned by the `sqlite3_bind_xxx` function.
func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt
}
// MARK: - StatementArguments
/// StatementArguments provide values to argument placeholders in raw
/// SQL queries.
///
/// Placeholders can take several forms (see <https://www.sqlite.org/lang_expr.html#varparam>
/// Placeholders can take several forms (see https://www.sqlite.org/lang_expr.html#varparam
/// for more information):
///
/// - `?NNN` (e.g. `?2`): the NNN-th argument (starts at 1)
@@ -534,8 +636,8 @@ public protocol StatementBinding {
public struct StatementArguments: CustomStringConvertible, Equatable,
ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral
{
private(set) var values: [DatabaseValue]
private(set) var namedValues: [String: DatabaseValue]
private(set) var values: [DatabaseValue] = []
private(set) var namedValues: [String: DatabaseValue] = [:]
public var isEmpty: Bool {
values.isEmpty && namedValues.isEmpty
@@ -546,8 +648,6 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
/// Creates empty StatementArguments.
public init() {
values = .init()
namedValues = .init()
}
// MARK: Positional Arguments
@@ -561,7 +661,6 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
/// - returns: A StatementArguments.
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element == DatabaseValueConvertible? {
values = sequence.map { $0?.databaseValue ?? .null }
namedValues = .init()
}
/// Creates statement arguments from a sequence of optional values.
@@ -573,7 +672,6 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
/// - returns: A StatementArguments.
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element: DatabaseValueConvertible {
values = sequence.map(\.databaseValue)
namedValues = .init()
}
/// Creates statement arguments from any array. The result is nil unless all
@@ -592,11 +690,6 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
self.init(values)
}
@usableFromInline
mutating func set(databaseValues: [DatabaseValue]) {
self.values = databaseValues
namedValues.removeAll(keepingCapacity: true)
}
// MARK: Named Arguments
@@ -610,7 +703,6 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
/// - returns: A StatementArguments.
public init(_ dictionary: [String: DatabaseValueConvertible?]) {
namedValues = dictionary.mapValues { $0?.databaseValue ?? .null }
values = .init()
}
/// Creates statement arguments from a sequence of (key, value) pairs, such
@@ -624,11 +716,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
public init<Sequence>(_ sequence: Sequence)
where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?)
{
namedValues = .init(minimumCapacity: sequence.underestimatedCount)
for (key, value) in sequence {
namedValues[key] = value?.databaseValue ?? .null
}
values = .init()
namedValues = Dictionary(uniqueKeysWithValues: sequence.map { ($0.0, $0.1?.databaseValue ?? .null) })
}
/// Creates statement arguments from [AnyHashable: Any].
+2 -3
View File
@@ -3,7 +3,6 @@ import Glibc
#endif
/// A protocol around sqlite3_set_authorizer
@usableFromInline
protocol StatementAuthorizer: AnyObject {
func authorize(
_ actionCode: Int32,
@@ -29,7 +28,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
/// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or
/// savepoint statement.
var transactionEffect: Statement.TransactionEffect?
var transactionEffect: UpdateStatement.TransactionEffect?
private var isDropStatement = false
@@ -56,7 +55,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
invalidatesDatabaseSchemaCache = true
return SQLITE_OK
case SQLITE_ATTACH, SQLITE_DETACH, SQLITE_ALTER_TABLE,
case SQLITE_ALTER_TABLE, SQLITE_DETACH,
SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE,
SQLITE_CREATE_TEMP_INDEX, SQLITE_CREATE_TEMP_TABLE,
SQLITE_CREATE_TEMP_TRIGGER, SQLITE_CREATE_TEMP_VIEW,
+48 -174
View File
@@ -1,6 +1,6 @@
/// The `StatementColumnConvertible` protocol grants access to the low-level C
/// interface that extracts values from query results:
/// <https://www.sqlite.org/c3ref/column_blob.html>. It can bring performance
/// https://www.sqlite.org/c3ref/column_blob.html. It can bring performance
/// improvements.
///
/// To use it, have a value type adopt both `StatementColumnConvertible` and
@@ -18,107 +18,32 @@
/// score = row["score"] // there
/// }
/// }
///
/// `StatementColumnConvertible` is already adopted by all Swift integer types,
/// `Float`, `Double`, `String`, and `Bool`.
public protocol StatementColumnConvertible {
/// Initializes a value from a raw SQLite statement pointer, if possible.
/// Initializes a value from a raw SQLite statement pointer.
///
/// For example, here is the how Int64 adopts StatementColumnConvertible:
///
/// extension Int64: StatementColumnConvertible {
/// init?(sqliteStatement: SQLiteStatement, index: Int32) {
/// init(sqliteStatement: SQLiteStatement, index: Int32) {
/// self = sqlite3_column_int64(sqliteStatement, index)
/// }
/// }
///
/// This initializer is never called for NULL database values. Just return
/// `nil` for failed conversions: GRDB will interpret a nil result as a
/// decoding failure.
/// This initializer is never called for NULL database values: don't perform
/// any extra check.
///
/// See <https://www.sqlite.org/c3ref/column_blob.html> for more information.
/// See https://www.sqlite.org/c3ref/column_blob.html for more information.
///
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
init?(sqliteStatement: SQLiteStatement, index: Int32)
init(sqliteStatement: SQLiteStatement, index: Int32)
}
// MARK: - Conversions
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
@inlinable
static func fastDecode(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: Int32,
context: @autoclosure () -> RowDecodingContext)
throws -> Self
{
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL,
let value = self.init(sqliteStatement: sqliteStatement, index: index)
else {
throw RowDecodingError.valueMismatch(
Self.self,
sqliteStatement: sqliteStatement,
index: index,
context: context())
}
return value
}
@inlinable
static func fastDecode(
fromRow row: Row,
atUncheckedIndex index: Int)
throws -> Self
{
if let sqliteStatement = row.sqliteStatement {
return try fastDecode(
fromStatement: sqliteStatement,
atUncheckedIndex: Int32(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
// Support for fast decoding from adapted rows
return try row.fastDecode(Self.self, atUncheckedIndex: index)
}
@inlinable
static func fastDecodeIfPresent(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: Int32,
context: @autoclosure () -> RowDecodingContext)
throws -> Self?
{
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
return nil
}
guard let value = self.init(sqliteStatement: sqliteStatement, index: index) else {
throw RowDecodingError.valueMismatch(
Self.self,
sqliteStatement: sqliteStatement,
index: index,
context: context())
}
return value
}
@inlinable
static func fastDecodeIfPresent(
fromRow row: Row,
atUncheckedIndex index: Int)
throws -> Self?
{
if let sqliteStatement = row.sqliteStatement {
return try fastDecodeIfPresent(
fromStatement: sqliteStatement,
atUncheckedIndex: Int32(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
// Support for fast decoding from adapted rows
return try row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
}
}
// MARK: - Cursors
/// A cursor of database values extracted from a single column.
/// For example:
///
@@ -129,16 +54,12 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// }
/// }
public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
@usableFromInline enum _State {
case idle, busy, done, failed
}
@usableFromInline let _statement: Statement
@usableFromInline let _statement: SelectStatement
@usableFromInline let _columnIndex: Int32
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline var _state = _State.idle
@usableFromInline var _done = false
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
_statement = statement
_sqliteStatement = statement.sqliteStatement
if let adapter = adapter {
@@ -147,16 +68,13 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
} else {
_columnIndex = 0
}
_statement.reset(withArguments: arguments)
// Assume cursor is created for immediate iteration: reset and set arguments
statement.reset(withArguments: arguments)
// Assume cursor is created for iteration
try statement.database.selectStatementWillExecute(statement)
}
deinit {
if _state == .busy {
try? _statement.database.statementDidExecute(_statement)
}
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? _statement.reset()
@@ -164,38 +82,19 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
@inlinable
public func next() throws -> Value? {
switch _state {
case .done:
if _done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
case .idle:
guard try _statement.database.statementWillExecute(_statement) == nil else {
throw DatabaseError(
resultCode: SQLITE_MISUSE,
message: "Can't run statement that requires a customized authorizer from a cursor",
sql: _statement.sql,
arguments: _statement.arguments)
}
_state = .busy
default:
break
}
switch sqlite3_step(_sqliteStatement) {
case SQLITE_DONE:
_state = .done
try _statement.database.statementDidExecute(_statement)
_done = true
return nil
case SQLITE_ROW:
// TODO GRDB6: don't crash on decoding errors
return try! Value.fastDecode(
fromStatement: _sqliteStatement,
atUncheckedIndex: _columnIndex,
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
return Value.fastDecode(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
case let code:
_state = .failed
try _statement.database.statementDidFail(_statement, withResultCode: code)
try _statement.didFail(withResultCode: code)
}
}
}
@@ -213,16 +112,12 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
public final class FastNullableDatabaseValueCursor<Value>: Cursor
where Value: DatabaseValueConvertible & StatementColumnConvertible
{
@usableFromInline enum _State {
case idle, busy, done, failed
}
@usableFromInline let _statement: Statement
@usableFromInline let _statement: SelectStatement
@usableFromInline let _columnIndex: Int32
@usableFromInline let _sqliteStatement: SQLiteStatement
@usableFromInline var _state = _State.idle
@usableFromInline var _done = false
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
_statement = statement
_sqliteStatement = statement.sqliteStatement
if let adapter = adapter {
@@ -231,16 +126,13 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
} else {
_columnIndex = 0
}
_statement.reset(withArguments: arguments)
// Assume cursor is created for immediate iteration: reset and set arguments
statement.reset(withArguments: arguments)
// Assume cursor is created for iteration
try statement.database.selectStatementWillExecute(statement)
}
deinit {
if _state == .busy {
try? _statement.database.statementDidExecute(_statement)
}
// Statement reset fails when sqlite3_step has previously failed.
// Just ignore reset error.
try? _statement.reset()
@@ -248,38 +140,19 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
@inlinable
public func next() throws -> Value?? {
switch _state {
case .done:
if _done {
// make sure this instance never yields a value again, even if the
// statement is reset by another cursor.
return nil
case .idle:
guard try _statement.database.statementWillExecute(_statement) == nil else {
throw DatabaseError(
resultCode: SQLITE_MISUSE,
message: "Can't run statement that requires a customized authorizer from a cursor",
sql: _statement.sql,
arguments: _statement.arguments)
}
_state = .busy
default:
break
}
switch sqlite3_step(_sqliteStatement) {
case SQLITE_DONE:
_state = .done
try _statement.database.statementDidExecute(_statement)
_done = true
return nil
case SQLITE_ROW:
// TODO GRDB6: don't crash on decoding errors
return try! Value.fastDecodeIfPresent(
fromStatement: _sqliteStatement,
atUncheckedIndex: _columnIndex,
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
return Value.fastDecodeIfPresent(from: _sqliteStatement, atUncheckedIndex: _columnIndex)
case let code:
_state = .failed
try _statement.database.statementDidFail(_statement, withResultCode: code)
try _statement.didFail(withResultCode: code)
}
}
}
@@ -291,11 +164,12 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
/// See DatabaseValueConvertible for more information.
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
// MARK: Fetching From Prepared Statement
// MARK: Fetching From SelectStatement
/// Returns a cursor over values fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "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
/// ...
@@ -313,7 +187,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(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastDatabaseValueCursor<Self>
@@ -323,7 +197,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns an array of values fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try String.fetchAll(statement) // [String]
///
/// - parameters:
@@ -333,7 +207,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(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Self]
@@ -343,7 +217,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// Returns a single value fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let name = try String.fetchOne(statement) // String?
///
/// - parameters:
@@ -353,7 +227,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
/// - returns: An optional value.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchOne(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Self?
@@ -370,7 +244,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable {
/// Returns a set of values fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try String.fetchSet(statement) // Set<String>
///
/// - parameters:
@@ -380,7 +254,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
/// - returns: A set of values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Set<Self>
@@ -637,18 +511,18 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
/// 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.makeStatement(sql: "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?]
///
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
// MARK: Fetching From Prepared Statement
// MARK: Fetching From SelectStatement
/// Returns a cursor over optional values fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "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?
/// ...
@@ -666,7 +540,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(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> FastNullableDatabaseValueCursor<Wrapped>
@@ -676,7 +550,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// Returns an array of optional values fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try Optional<String>.fetchAll(statement) // [String?]
///
/// - parameters:
@@ -686,7 +560,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(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> [Wrapped?]
@@ -698,7 +572,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable {
/// Returns a set of optional values fetched from a prepared statement.
///
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
/// let names = try Optional<String>.fetchSet(statement) // Set<String?>
///
/// - parameters:
@@ -708,7 +582,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
/// - returns: A set of optional values.
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
public static func fetchSet(
_ statement: Statement,
_ statement: SelectStatement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> Set<Wrapped?>
+1 -83
View File
@@ -13,7 +13,6 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
DatabaseValue(storage: .blob(self))
}
@@ -26,91 +25,10 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
return data
case .string(let string):
// Implicit conversion from string to blob, just as SQLite does
// See <https://www.sqlite.org/c3ref/column_blob.html>
// See https://www.sqlite.org/c3ref/column_blob.html
return string.data(using: .utf8)
default:
return nil
}
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
withUnsafeBytes {
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
}
}
}
// MARK: - Conversions
extension Data {
@inlinable
static func fastDecodeNoCopy(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: Int32,
context: @autoclosure () -> RowDecodingContext)
throws -> Data
{
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
throw RowDecodingError.valueMismatch(
Data.self,
sqliteStatement: sqliteStatement,
index: index,
context: context())
}
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
return Data()
}
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
}
@inlinable
static func fastDecodeNoCopy(
fromRow row: Row,
atUncheckedIndex index: Int)
throws -> Data
{
if let sqliteStatement = row.sqliteStatement {
return try fastDecodeNoCopy(
fromStatement: sqliteStatement,
atUncheckedIndex: Int32(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
// Support for fast decoding from adapted rows
return try row.fastDecodeDataNoCopy(atUncheckedIndex: index)
}
@inlinable
static func fastDecodeNoCopyIfPresent(
fromStatement sqliteStatement: SQLiteStatement,
atUncheckedIndex index: Int32,
context: @autoclosure () -> RowDecodingContext)
-> Data?
{
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
return nil
}
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
return Data()
}
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
}
@inlinable
static func fastDecodeNoCopyIfPresent(
fromRow row: Row,
atUncheckedIndex index: Int)
throws -> Data?
{
if let sqliteStatement = row.sqliteStatement {
return fastDecodeNoCopyIfPresent(
fromStatement: sqliteStatement,
atUncheckedIndex: Int32(index),
context: RowDecodingContext(row: row, key: .columnIndex(index)))
}
// Support for fast decoding from adapted rows
return try row.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index)
}
}
@@ -69,9 +69,9 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
/// - parameters:
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
return nil
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
}
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
let optionalComponents = cString.withMemoryRebound(
@@ -80,7 +80,7 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
SQLiteDateParser().components(cString: cString, length: length)
}
guard let components = optionalComponents else {
return nil
fatalConversionError(to: DatabaseDateComponents.self, sqliteStatement: sqliteStatement, index: index)
}
self.dateComponents = components.dateComponents
self.format = components.format
+5 -6
View File
@@ -119,19 +119,18 @@ extension Date: StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER, SQLITE_FLOAT:
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index))
case SQLITE_TEXT:
guard let components = DatabaseDateComponents(sqliteStatement: sqliteStatement, index: index),
let date = Date(databaseDateComponents: components)
else {
return nil
let databaseDateComponents = DatabaseDateComponents(sqliteStatement: sqliteStatement, index: index)
guard let date = Date(databaseDateComponents: databaseDateComponents) else {
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
}
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate)
default:
return nil
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
}
}
}
@@ -1,46 +0,0 @@
#if !os(Linux)
import Foundation
/// Decimal adopts DatabaseValueConvertible
extension Decimal: DatabaseValueConvertible {
public var databaseValue: DatabaseValue {
NSDecimalNumber(decimal: self)
.description(withLocale: Locale(identifier: "en_US_POSIX"))
.databaseValue
}
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
switch dbValue.storage {
case .int64(let int64):
return self.init(int64)
case .double(let double):
return self.init(double)
case let .string(string):
// Must match NSNumber.fromDatabaseValue(_:)
return self.init(string: string, locale: posixLocale)
default:
return nil
}
}
}
/// Decimal adopts StatementColumnConvertible
extension Decimal: StatementColumnConvertible {
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_INTEGER:
self.init(sqlite3_column_int64(sqliteStatement, index))
case SQLITE_FLOAT:
self.init(sqlite3_column_double(sqliteStatement, index))
case SQLITE_TEXT:
self.init(
string: String(cString: sqlite3_column_text(sqliteStatement, index)!),
locale: posixLocale)
default:
return nil
}
}
}
private let posixLocale = Locale(identifier: "en_US_POSIX")
#endif
@@ -71,15 +71,9 @@ extension NSNumber: DatabaseValueConvertible {
return self.init(value: int64)
case .double(let double):
return self.init(value: double)
case let .string(string):
// Must match Decimal.fromDatabaseValue(_:)
guard let decimal = Decimal(string: string, locale: posixLocale) else { return nil }
return NSDecimalNumber(decimal: decimal) as? Self
default:
return nil
}
}
}
private let posixLocale = Locale(identifier: "en_US_POSIX")
#endif
+4 -4
View File
@@ -50,23 +50,23 @@ extension UUID: DatabaseValueConvertible {
extension UUID: StatementColumnConvertible {
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
switch sqlite3_column_type(sqliteStatement, index) {
case SQLITE_TEXT:
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
guard let uuid = UUID(uuidString: string) else {
return nil
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
}
self.init(uuid: uuid.uuid)
case SQLITE_BLOB:
guard sqlite3_column_bytes(sqliteStatement, index) == 16,
let blob = sqlite3_column_blob(sqliteStatement, index) else
{
return nil
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
}
self.init(uuid: blob.assumingMemoryBound(to: uuid_t.self).pointee)
default:
return nil
fatalConversionError(to: UUID.self, sqliteStatement: sqliteStatement, index: index)
}
}
}
@@ -1,5 +1,3 @@
import Foundation
private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
let dbValue: DatabaseValue
let codingPath: [CodingKey]
@@ -157,13 +155,15 @@ private struct DatabaseValueDecoder: Decoder {
var userInfo: [CodingUserInfoKey: Any] { [:] }
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
// We need to switch to JSON decoding
throw JSONRequiredError()
throw DecodingError.typeMismatch(
type,
DecodingError.Context(codingPath: codingPath, debugDescription: "keyed decoding is not supported"))
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
// We need to switch to JSON decoding
throw JSONRequiredError()
throw DecodingError.typeMismatch(
UnkeyedDecodingContainer.self,
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
}
func singleValueContainer() throws -> SingleValueDecodingContainer {
@@ -173,20 +173,7 @@ private struct DatabaseValueDecoder: Decoder {
extension DatabaseValueConvertible where Self: Decodable {
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
do {
return try self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
} catch is JSONRequiredError {
guard let data = Data.fromDatabaseValue(databaseValue) else {
return nil
}
let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base64
decoder.dateDecodingStrategy = .millisecondsSince1970
decoder.nonConformingFloatDecodingStrategy = .throw
return try? decoder.decode(Self.self, from: data)
} catch {
return nil
}
try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
}
}
@@ -1,5 +1,3 @@
import Foundation
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
let encode: (DatabaseValue) -> Void
@@ -42,18 +40,13 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
// This allows us to encode Date as String, for example.
encode(dbValueConvertible.databaseValue)
} else {
try DatabaseValueEncoder(encode: encode).encode(value)
try value.encode(to: DatabaseValueEncoder(encode: encode))
}
}
}
private class DatabaseValueEncoder: Encoder {
private struct DatabaseValueEncoder: Encoder {
let encode: (DatabaseValue) -> Void
var requiresJSON = false
init(encode: @escaping (DatabaseValue) -> Void) {
self.encode = encode
}
/// The path of coding keys taken to get to this point in encoding.
/// A `nil` value indicates an unkeyed container.
@@ -70,14 +63,7 @@ private class DatabaseValueEncoder: Encoder {
/// - precondition: May not be called after a value has been encoded through
/// a previous `self.singleValueContainer()` call.
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
// We need to perform JSON encoding. Unfortunately we can't access the
// inner container of Foundation's JSONEncoder. At this point we must
// throw an error so that the caller can retry encoding from scratch.
// Unfortunately (bis), we can't throw right from here, so let's
// return a JSONRequiredEncoder that will throw as soon as possible.
requiresJSON = true
let container = JSONRequiredEncoder.KeyedContainer<Key>(codingPath: codingPath)
return KeyedEncodingContainer(container)
fatalError("keyed encoding is not supported")
}
/// Returns an encoding container appropriate for holding multiple unkeyed values.
@@ -87,13 +73,7 @@ private class DatabaseValueEncoder: Encoder {
/// - precondition: May not be called after a value has been encoded through
/// a previous `self.singleValueContainer()` call.
func unkeyedContainer() -> UnkeyedEncodingContainer {
// We need to perform JSON encoding. Unfortunately we can't access the
// inner container of Foundation's JSONEncoder. At this point we must
// throw an error so that the caller can retry encoding from scratch.
// Unfortunately (bis), we can't throw right from here, so let's
// return a JSONRequiredEncoder that will throw as soon as possible.
requiresJSON = true
return JSONRequiredEncoder(codingPath: codingPath)
fatalError("unkeyed encoding is not supported")
}
/// Returns an encoding container appropriate for holding a single primitive value.
@@ -106,41 +86,13 @@ private class DatabaseValueEncoder: Encoder {
func singleValueContainer() -> SingleValueEncodingContainer {
DatabaseValueEncodingContainer(encode: encode)
}
func encode<T: Encodable>(_ value: T) throws {
do {
try value.encode(to: self)
if requiresJSON {
// Here we handle empty arrays and dictionaries.
throw JSONRequiredError()
}
} catch is JSONRequiredError {
let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base64
encoder.dateEncodingStrategy = .millisecondsSince1970
encoder.nonConformingFloatEncodingStrategy = .throw
if #available(watchOS 4.0, OSX 10.13, iOS 11.0, tvOS 11.0, *) {
// guarantee some stability in order to ease value comparison
encoder.outputFormatting = .sortedKeys
}
let jsonData = try encoder.encode(value)
// Store JSON String in the database for easier debugging and
// database inspection. Thanks to SQLite weak typing, we won't
// have any trouble decoding this string into data when we
// eventually perform JSON decoding.
// TODO: possible optimization: avoid this conversion to string,
// and store raw data bytes as an SQLite string
let jsonString = String(data: jsonData, encoding: .utf8)!
try jsonString.encode(to: self)
}
}
}
extension DatabaseValueConvertible where Self: Encodable {
public var databaseValue: DatabaseValue {
var dbValue: DatabaseValue! = nil
try! DatabaseValueEncoder(encode: { dbValue = $0 }).encode(self)
let encoder = DatabaseValueEncoder(encode: { dbValue = $0 })
try! self.encode(to: encoder)
return dbValue
}
}
@@ -1,15 +1,15 @@
extension SQLSelectable where Self: RawRepresentable, Self.RawValue: SQLSelectable {
public var sqlSelection: SQLSelection {
rawValue.sqlSelection
}
}
extension SQLOrderingTerm where Self: RawRepresentable, Self.RawValue: SQLOrderingTerm {
public var sqlOrdering: SQLOrdering {
rawValue.sqlOrdering
}
}
/// SQLExpressible is free for RawRepresentable types whose raw value
/// is itself SQLExpressible.
///
/// // If the RawValue adopts SQLExpressible...
/// enum Color : Int {
/// case red
/// case white
/// case rose
/// }
///
/// // ... then the RawRepresentable type can freely adopt SQLExpressible:
/// extension Color : SQLExpressible { /* empty */ }
extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpressible {
/// Returns the raw value as an SQL expression.
public var sqlExpression: SQLExpression {
@@ -17,15 +17,8 @@ extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpress
}
}
extension StatementBinding where Self: RawRepresentable, Self.RawValue: StatementBinding {
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
rawValue.bind(to: sqliteStatement, at: index)
}
}
/// `DatabaseValueConvertible` is free for `RawRepresentable` types whose raw
/// value is itself `DatabaseValueConvertible`.
/// DatabaseValueConvertible is free for RawRepresentable types whose raw value
/// is itself DatabaseValueConvertible.
///
/// // If the RawValue adopts DatabaseValueConvertible...
/// enum Color : Int {
@@ -34,15 +27,16 @@ extension StatementBinding where Self: RawRepresentable, Self.RawValue: Statemen
/// case rose
/// }
///
/// // ... then the RawRepresentable type can freely
/// // adopt DatabaseValueConvertible:
/// extension Color: DatabaseValueConvertible { }
/// // ... then the RawRepresentable type can freely adopt DatabaseValueConvertible:
/// extension Color : DatabaseValueConvertible { /* empty */ }
extension DatabaseValueConvertible where Self: RawRepresentable, Self.RawValue: DatabaseValueConvertible {
@inlinable
/// Returns a value that can be stored in the database.
public var databaseValue: DatabaseValue {
rawValue.databaseValue
}
/// Returns a value initialized from *dbValue*, if possible.
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
RawValue.fromDatabaseValue(dbValue).flatMap { self.init(rawValue: $0) }
}
@@ -1,97 +0,0 @@
struct JSONRequiredError: Error { }
/// The encoder that always ends up with a JSONRequiredError
struct JSONRequiredEncoder: Encoder {
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
let container = KeyedContainer<Key>(codingPath: codingPath)
return KeyedEncodingContainer(container)
}
func unkeyedContainer() -> UnkeyedEncodingContainer { self }
func singleValueContainer() -> SingleValueEncodingContainer { self }
struct KeyedContainer<KeyType: CodingKey>: KeyedEncodingContainerProtocol {
var codingPath: [CodingKey]
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
// swiftlint:disable comma
func encodeNil(forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Bool, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Int, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Int8, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Int16, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Int32, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Int64, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: UInt, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: UInt8, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: UInt16, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: UInt32, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: UInt64, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() }
func encode<T>(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() }
// swiftlint:enable comma
func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: KeyType)
-> KeyedEncodingContainer<NestedKey>
where NestedKey: CodingKey
{
let container = KeyedContainer<NestedKey>(codingPath: codingPath + [key])
return KeyedEncodingContainer(container)
}
func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer {
JSONRequiredEncoder(codingPath: codingPath)
}
func superEncoder() -> Encoder {
JSONRequiredEncoder(codingPath: codingPath)
}
func superEncoder(forKey key: KeyType) -> Encoder {
JSONRequiredEncoder(codingPath: codingPath)
}
}
}
extension JSONRequiredEncoder: SingleValueEncodingContainer {
func encodeNil() throws { throw JSONRequiredError() }
func encode(_ value: Bool ) throws { throw JSONRequiredError() }
func encode(_ value: Int ) throws { throw JSONRequiredError() }
func encode(_ value: Int8 ) throws { throw JSONRequiredError() }
func encode(_ value: Int16 ) throws { throw JSONRequiredError() }
func encode(_ value: Int32 ) throws { throw JSONRequiredError() }
func encode(_ value: Int64 ) throws { throw JSONRequiredError() }
func encode(_ value: UInt ) throws { throw JSONRequiredError() }
func encode(_ value: UInt8 ) throws { throw JSONRequiredError() }
func encode(_ value: UInt16) throws { throw JSONRequiredError() }
func encode(_ value: UInt32) throws { throw JSONRequiredError() }
func encode(_ value: UInt64) throws { throw JSONRequiredError() }
func encode(_ value: Float ) throws { throw JSONRequiredError() }
func encode(_ value: Double) throws { throw JSONRequiredError() }
func encode(_ value: String) throws { throw JSONRequiredError() }
func encode<T>(_ value: T) throws where T: Encodable { throw JSONRequiredError() }
}
extension JSONRequiredEncoder: UnkeyedEncodingContainer {
var count: Int { 0 }
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type)
-> KeyedEncodingContainer<NestedKey>
where NestedKey: CodingKey
{
let container = KeyedContainer<NestedKey>(codingPath: codingPath)
return KeyedEncodingContainer(container)
}
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self }
mutating func superEncoder() -> Encoder { self }
}
@@ -14,7 +14,6 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
(self ? 1 : 0).databaseValue
}
@@ -86,11 +85,6 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
return nil
}
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, self ? 1 : 0)
}
}
/// Int adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -102,14 +96,16 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = Int(exactly: int64) else { return nil }
self = v
if let v = Int(exactly: int64) {
self = v
} else {
fatalConversionError(to: Int.self, sqliteStatement: sqliteStatement, index: index)
}
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
Int64(self).databaseValue
}
@@ -118,11 +114,6 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int? {
Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
/// Int8 adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -134,14 +125,16 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = Int8(exactly: int64) else { return nil }
self = v
if let v = Int8(exactly: int64) {
self = v
} else {
fatalConversionError(to: Int8.self, sqliteStatement: sqliteStatement, index: index)
}
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
Int64(self).databaseValue
}
@@ -150,11 +143,6 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int8? {
Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
/// Int16 adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -166,14 +154,16 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = Int16(exactly: int64) else { return nil }
self = v
if let v = Int16(exactly: int64) {
self = v
} else {
fatalConversionError(to: Int16.self, sqliteStatement: sqliteStatement, index: index)
}
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
Int64(self).databaseValue
}
@@ -182,11 +172,6 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int16? {
Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
/// Int32 adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -198,14 +183,16 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = Int32(exactly: int64) else { return nil }
self = v
if let v = Int32(exactly: int64) {
self = v
} else {
fatalConversionError(to: Int32.self, sqliteStatement: sqliteStatement, index: index)
}
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
Int64(self).databaseValue
}
@@ -214,11 +201,6 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Int32? {
Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
/// Int64 adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -235,7 +217,6 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
DatabaseValue(storage: .int64(self))
}
@@ -253,11 +234,6 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
return nil
}
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, self)
}
}
/// UInt adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -269,14 +245,16 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = UInt(exactly: int64) else { return nil }
self = v
if let v = UInt(exactly: int64) {
self = v
} else {
fatalConversionError(to: UInt.self, sqliteStatement: sqliteStatement, index: index)
}
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
Int64(self).databaseValue
}
@@ -285,11 +263,6 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt? {
Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
/// UInt8 adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -301,14 +274,16 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = UInt8(exactly: int64) else { return nil }
self = v
if let v = UInt8(exactly: int64) {
self = v
} else {
fatalConversionError(to: UInt8.self, sqliteStatement: sqliteStatement, index: index)
}
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
Int64(self).databaseValue
}
@@ -317,11 +292,6 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt8? {
Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
/// UInt16 adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -333,14 +303,16 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = UInt16(exactly: int64) else { return nil }
self = v
if let v = UInt16(exactly: int64) {
self = v
} else {
fatalConversionError(to: UInt16.self, sqliteStatement: sqliteStatement, index: index)
}
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
Int64(self).databaseValue
}
@@ -349,11 +321,6 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt16? {
Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
/// UInt32 adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -365,14 +332,16 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = UInt32(exactly: int64) else { return nil }
self = v
if let v = UInt32(exactly: int64) {
self = v
} else {
fatalConversionError(to: UInt32.self, sqliteStatement: sqliteStatement, index: index)
}
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
Int64(self).databaseValue
}
@@ -381,11 +350,6 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt32? {
Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
/// UInt64 adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -397,14 +361,16 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
/// - sqliteStatement: A pointer to an SQLite statement.
/// - index: The column index.
@inlinable
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
public init(sqliteStatement: SQLiteStatement, index: Int32) {
let int64 = sqlite3_column_int64(sqliteStatement, index)
guard let v = UInt64(exactly: int64) else { return nil }
self = v
if let v = UInt64(exactly: int64) {
self = v
} else {
fatalConversionError(to: UInt64.self, sqliteStatement: sqliteStatement, index: index)
}
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
Int64(self).databaseValue
}
@@ -413,11 +379,6 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> UInt64? {
Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
}
}
/// Double adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -434,7 +395,6 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
DatabaseValue(storage: .double(self))
}
@@ -450,11 +410,6 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
return nil
}
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_double(sqliteStatement, index, self)
}
}
/// Float adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -471,7 +426,6 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
Double(self).databaseValue
}
@@ -487,11 +441,6 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
return nil
}
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_double(sqliteStatement, index, Double(self))
}
}
/// String adopts DatabaseValueConvertible and StatementColumnConvertible.
@@ -508,7 +457,6 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
}
/// Returns a value that can be stored in the database.
@inlinable
public var databaseValue: DatabaseValue {
DatabaseValue(storage: .string(self))
}
@@ -518,7 +466,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
switch dbValue.storage {
case .blob(let data):
// Implicit conversion from blob to string, just as SQLite does
// See <https://www.sqlite.org/c3ref/column_blob.html>
// See https://www.sqlite.org/c3ref/column_blob.html
return String(data: data, encoding: .utf8)
case .string(let string):
return string
@@ -526,11 +474,6 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
return nil
}
}
@inlinable
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT)
}
}
+101 -101
View File
@@ -164,7 +164,7 @@ class DatabaseObservationBroker {
private var statementObservations: [StatementObservation] = [] {
didSet { observesDatabaseChanges = !statementObservations.isEmpty }
}
private var observesDatabaseChanges = false {
private var observesDatabaseChanges: Bool = false {
didSet {
if observesDatabaseChanges == oldValue { return }
if observesDatabaseChanges {
@@ -200,93 +200,99 @@ class DatabaseObservationBroker {
/// Setups observation of changes that are about to be performed by the
/// statement, and returns the authorizer that should be used during
/// statement execution (this allows preventing the truncate optimization
/// when there exists a transaction observer for row deletion).
func statementWillExecute(_ statement: Statement) -> StatementAuthorizer? {
/// statement execution.
func updateStatementWillExecute(_ statement: UpdateStatement) -> StatementAuthorizer? {
// As statement executes, it may trigger database changes that will
// be notified to transaction observers. As a consequence, observers
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
//
// This method takes no argument, and requires access to the "current
// broker", which is a per-thread global stored in
// SchedulingWatchdog.current:
SchedulingWatchdog.current!.databaseObservationBroker = self
// Fill statementObservations with observations that are interested in
// the kind of events performed by the statement.
//
// Those statementObservations will be notified of individual changes
// in databaseWillChange() and databaseDidChange().
let eventKinds = statement.databaseEventKinds
// If any observer observes row deletions, we'll have to disable
// [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
// so that observers are notified.
var observesRowDeletion = false
if transactionObservations.isEmpty == false {
// As statement executes, it may trigger database changes that will
// be notified to transaction observers. As a consequence, observers
// may disable themselves with stopObservingDatabaseChangesUntilNextTransaction()
switch eventKinds.count {
case 0:
// Statement has no effect on any database table.
//
// This method takes no argument, and requires access to the "current
// broker", which is a per-thread global stored in
// SchedulingWatchdog.current:
SchedulingWatchdog.current!.databaseObservationBroker = self
// Fill statementObservations with observations that are interested in
// the kind of events performed by the statement.
// For example: PRAGMA foreign_keys = ON
statementObservations = []
case 1:
// We'll execute a simple statement without any side effect.
// Eventual database events will thus all have the same kind. All
// detabase events can be notified to interested observations.
//
// Those statementObservations will be notified of individual changes
// in databaseWillChange() and databaseDidChange().
let eventKinds = statement.databaseEventKinds
switch eventKinds.count {
case 0:
// Statement has no effect on any database table.
//
// For example: PRAGMA foreign_keys = ON
statementObservations = []
case 1:
// We'll execute a simple statement without any side effect.
// Eventual database events will thus all have the same kind. All
// detabase events can be notified to interested observations.
//
// For example, if one observes all deletions in the table T, then
// all individual deletions of DELETE FROM T are notified:
let eventKind = eventKinds[0]
statementObservations = transactionObservations.compactMap { observation in
guard observation.observes(eventsOfKind: eventKind) else {
// observation is not interested
return nil
}
// For example, if one observes all deletions in the table T, then
// all individual deletions of DELETE FROM T are notified:
let eventKind = eventKinds[0]
statementObservations = transactionObservations.compactMap { observation in
guard observation.observes(eventsOfKind: eventKind) else {
// observation is not interested
return nil
}
if case .delete = eventKind {
observesRowDeletion = true
}
// observation will be notified of all individual events
return (observation, DatabaseEventPredicate.true)
}
default:
// We'll execute a complex statement with side effects performed by
// an SQL trigger or a foreign key action. Eventual database events
// may not all have the same kind: we need to filter them before
// notifying interested observations.
//
// For example, if DELETE FROM T1 generates deletions in T1 and T2
// by the mean of a foreign key action, then when one only observes
// deletions in T1, one must not be notified of deletions in T2:
statementObservations = transactionObservations.compactMap { observation in
let observedKinds = eventKinds.filter(observation.observes)
if observedKinds.isEmpty {
// observation is not interested
return nil
}
for eventKind in observedKinds {
if case .delete = eventKind {
observesRowDeletion = true
break
}
// observation will be notified of all individual events
return (observation, DatabaseEventPredicate.true)
}
default:
// We'll execute a complex statement with side effects performed by
// an SQL trigger or a foreign key action. Eventual database events
// may not all have the same kind: we need to filter them before
// notifying interested observations.
//
// For example, if DELETE FROM T1 generates deletions in T1 and T2
// by the mean of a foreign key action, then when one only observes
// deletions in T1, one must not be notified of deletions in T2:
statementObservations = transactionObservations.compactMap { observation in
let observedKinds = eventKinds.filter(observation.observes)
if observedKinds.isEmpty {
// observation is not interested
return nil
}
for eventKind in observedKinds {
if case .delete = eventKind {
observesRowDeletion = true
break
}
}
// observation will only be notified of individual events that
// match one of the observed kinds.
return (
observation,
DatabaseEventPredicate.matching(
observedKinds: observedKinds,
advertisedKinds: eventKinds))
}
// observation will only be notified of individual events that
// match one of the observed kinds.
return (
observation,
DatabaseEventPredicate.matching(
observedKinds: observedKinds,
advertisedKinds: eventKinds))
}
}
transactionState = .none
switch transactionState {
case .none:
break
default:
// May happen after "PRAGMA journal_mode = WAL" executed with a
// SelectStatement.
// TODO: Maybe this state machine should be run for *all* statements,
// not ony update statements.
transactionState = .none
}
if observesRowDeletion {
return TruncateOptimizationBlocker()
@@ -295,10 +301,8 @@ class DatabaseObservationBroker {
}
}
/// May throw a cancelled commit error, if a transaction observer cancels
/// a transaction.
func statementDidFail(_ statement: Statement) throws {
// Undo statementWillExecute
func updateStatementDidFail(_ statement: UpdateStatement) throws {
// Undo updateStatementWillExecute
statementObservations = []
SchedulingWatchdog.current!.databaseObservationBroker = nil
@@ -321,14 +325,10 @@ class DatabaseObservationBroker {
}
}
/// May throw a cancelled commit error, if a transaction observer cancels
/// an empty transaction.
func statementDidExecute(_ statement: Statement) throws {
// Undo statementWillExecute
if transactionObservations.isEmpty == false {
statementObservations = []
SchedulingWatchdog.current!.databaseObservationBroker = nil
}
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
// Undo updateStatementWillExecute
statementObservations = []
SchedulingWatchdog.current!.databaseObservationBroker = nil
// Has statement any effect on transaction/savepoints?
if let transactionEffect = statement.transactionEffect {
@@ -439,7 +439,7 @@ class DatabaseObservationBroker {
}
}
// Called from statementDidExecute
// Called from updateStatementDidExecute
private func databaseDidCommit() {
savepointStack.clear()
@@ -449,9 +449,7 @@ class DatabaseObservationBroker {
databaseDidEndTransaction()
}
// Called from statementDidExecute
/// May throw a cancelled commit error, if a transaction observer cancels
/// the empty transaction.
// Called from updateStatementDidExecute
private func databaseDidCommitEmptyDeferredTransaction() throws {
// A statement that ends a transaction has been executed. But for
// SQLite, no transaction at all has started, and sqlite3_commit_hook
@@ -494,7 +492,7 @@ class DatabaseObservationBroker {
}
}
// Called from statementDidExecute or statementDidFail
// Called from updateStatementDidExecute or updateStatementDidFails
private func databaseDidRollback(notifyTransactionObservers: Bool) {
savepointStack.clear()
@@ -529,7 +527,7 @@ class DatabaseObservationBroker {
//
// Normally, notifyBufferedEvents() is called as part of statement
// execution, and the current broker has been set in
// statementWillExecute(). An assertion should be enough:
// updateStatementWillExecute(). An assertion should be enough:
//
// assert(SchedulingWatchdog.current?.databaseObservationBroker != nil)
//
@@ -537,8 +535,10 @@ class DatabaseObservationBroker {
//
// let journalMode = String.fetchOne(db, sql: "PRAGMA journal_mode = wal")
//
// It triggers the commit hook when the "PRAGMA journal_mode = wal"
// statement is finalized, long after it has executed:
// It runs a SelectStatement, not an UpdateStatement. But this not why
// this case is particular. What is unexpected is that it triggers
// the commit hook when the "PRAGMA journal_mode = wal" statement is
// finalized, long after it has executed:
//
// 1. Statement.deinit()
// 2. sqlite3_finalize()
@@ -551,7 +551,7 @@ class DatabaseObservationBroker {
// journal mode would trigger the commit hook in sqlite3_step(),
// not in sqlite3_finalize().
//
// Anyway: in this scenario, statementWillExecute() has not been
// Anyway: in this scenario, updateStatementWillExecute() has not been
// called, and the current broker is nil.
//
// Let's not try to outsmart SQLite, and build a complex state machine.
@@ -586,7 +586,7 @@ class DatabaseObservationBroker {
do {
try broker.databaseWillCommit()
broker.transactionState = .commit
// Next step: statementDidExecute()
// Next step: updateStatementDidExecute()
return 0
} catch {
broker.transactionState = .cancelledCommit(error)
@@ -599,11 +599,11 @@ class DatabaseObservationBroker {
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
switch broker.transactionState {
case .cancelledCommit:
// Next step: statementDidFail()
// Next step: updateStatementDidFail()
break
default:
broker.transactionState = .rollback
// Next step: statementDidExecute()
// Next step: updateStatementDidExecute()
}
}, brokerPointer)
}
@@ -737,7 +737,7 @@ public protocol TransactionObserver: AnyObject {
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
/// does not have this enabled, so you'll need to compile your own
/// version of SQLite:
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md>
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md
///
/// The databaseDidChangeWithEvent callback is always available,
/// and may provide most/all of what you need.
@@ -796,7 +796,7 @@ final class TransactionObservation {
// A disabled observation is not interested in individual database changes.
// It is still interested in transactions commits & rollbacks.
var isDisabled = false
var isDisabled: Bool = false
private weak var weakObserver: TransactionObserver?
private var strongObserver: TransactionObserver?
@@ -1346,7 +1346,7 @@ enum DatabaseEventPredicate {
// MARK: - SavepointStack
/// The SQLite savepoint stack is described at
/// <https://www.sqlite.org/lang_savepoint.html>
/// https://www.sqlite.org/lang_savepoint.html
///
/// This class reimplements the SQLite stack, so that we can:
///
+2 -10
View File
@@ -8,7 +8,7 @@ public struct FTS3: VirtualTableModule {
/// Options for Latin script characters. Matches the raw "remove_diacritics"
/// tokenizer argument.
///
/// See <https://www.sqlite.org/fts3.html>
/// 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.
@@ -45,18 +45,10 @@ public struct FTS3: VirtualTableModule {
/// The virtual table module name
public let moduleName = "fts3"
// TODO: remove when `makeTableDefinition()` is no longer a requirement
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
public func makeTableDefinition() -> FTS3TableDefinition {
preconditionFailure()
}
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS3TableDefinition {
FTS3TableDefinition()
}
@@ -101,7 +93,7 @@ public final class FTS3TableDefinition {
/// try db.create(virtualTable: "document", using: FTS3()) { t in
/// t.tokenizer = .porter
/// }
/// See <https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables>
/// See https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables
public var tokenizer: FTS3TokenizerDescriptor?
/// Appends a table column.
+1 -1
View File
@@ -7,7 +7,7 @@ public struct FTS3Pattern {
/// Creates a pattern from a raw pattern string; throws DatabaseError on
/// invalid syntax.
///
/// The pattern syntax is documented at <https://www.sqlite.org/fts3.html#full_text_index_queries>
/// The pattern syntax is documented at https://www.sqlite.org/fts3.html#full_text_index_queries
///
/// try FTS3Pattern(rawPattern: "and") // OK
/// try FTS3Pattern(rawPattern: "AND") // malformed MATCH expression: [AND]
+4 -4
View File
@@ -4,7 +4,7 @@
/// t.tokenizer = .simple // FTS3TokenizerDescriptor
/// }
///
/// See <https://www.sqlite.org/fts3.html#tokenizer>
/// See https://www.sqlite.org/fts3.html#tokenizer
public struct FTS3TokenizerDescriptor {
let name: String
let arguments: [String]
@@ -20,7 +20,7 @@ public struct FTS3TokenizerDescriptor {
/// t.tokenizer = .simple
/// }
///
/// See <https://www.sqlite.org/fts3.html#tokenizer>
/// See https://www.sqlite.org/fts3.html#tokenizer
public static let simple = FTS3TokenizerDescriptor("simple")
/// The "porter" tokenizer.
@@ -29,7 +29,7 @@ public struct FTS3TokenizerDescriptor {
/// t.tokenizer = .porter
/// }
///
/// See <https://www.sqlite.org/fts3.html#tokenizer>
/// See https://www.sqlite.org/fts3.html#tokenizer
public static let porter = FTS3TokenizerDescriptor("porter")
/// The "unicode61" tokenizer.
@@ -46,7 +46,7 @@ public struct FTS3TokenizerDescriptor {
/// - tokenCharacters: Unless empty (the default), SQLite will consider
/// these characters as token characters.
///
/// See <https://www.sqlite.org/fts3.html#tokenizer>
/// See https://www.sqlite.org/fts3.html#tokenizer
public static func unicode61(
diacritics: FTS3.Diacritics = .removeLegacy,
separators: Set<Character> = [],
+18 -37
View File
@@ -5,7 +5,7 @@
/// t.column("content")
/// }
///
/// See <https://www.sqlite.org/fts3.html>
/// See https://www.sqlite.org/fts3.html
public struct FTS4: VirtualTableModule {
/// Creates a FTS4 module suitable for the Database
@@ -16,7 +16,7 @@ public struct FTS4: VirtualTableModule {
/// t.column("content")
/// }
///
/// See <https://www.sqlite.org/fts3.html>
/// See https://www.sqlite.org/fts3.html
public init() {
}
@@ -25,19 +25,11 @@ public struct FTS4: VirtualTableModule {
/// The virtual table module name
public let moduleName = "fts4"
// TODO: remove when `makeTableDefinition()` is no longer a requirement
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
public func makeTableDefinition() -> FTS4TableDefinition {
preconditionFailure()
}
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS4TableDefinition {
FTS4TableDefinition(configuration: configuration)
FTS4TableDefinition()
}
/// Reserved; part of the VirtualTableModule protocol.
@@ -121,26 +113,20 @@ public struct FTS4: VirtualTableModule {
let oldRowID = "old.\(rowIDColumn.quotedDatabaseIdentifier)"
let ifNotExists = definition.configuration.ifNotExists
? "IF NOT EXISTS "
: ""
// swiftlint:disable line_length
try db.execute(sql: """
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
END;
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
END;
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
END;
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
END;
""")
// swiftlint:enable line_length
// https://www.sqlite.org/fts3.html#*fts4rebuidcmd
@@ -158,14 +144,13 @@ public struct FTS4: VirtualTableModule {
/// t.column("content")
/// }
///
/// See <https://www.sqlite.org/fts3.html>
/// See https://www.sqlite.org/fts3.html
public final class FTS4TableDefinition {
enum ContentMode {
case raw(content: String?)
case synchronized(contentTable: String)
}
fileprivate let configuration: VirtualTableConfiguration
fileprivate var columns: [FTS4ColumnDefinition] = []
fileprivate var contentMode: ContentMode = .raw(content: nil)
@@ -175,7 +160,7 @@ public final class FTS4TableDefinition {
/// t.tokenizer = .porter
/// }
///
/// See <https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables>
/// See https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables
public var tokenizer: FTS3TokenizerDescriptor?
/// The FTS4 `content` option
@@ -187,7 +172,7 @@ public final class FTS4TableDefinition {
/// Setting this property invalidates any synchronization previously
/// established with the `synchronize(withTable:)` method.
///
/// See <https://www.sqlite.org/fts3.html#the_content_option_>
/// See https://www.sqlite.org/fts3.html#the_content_option_
public var content: String? {
get {
switch contentMode {
@@ -204,17 +189,17 @@ public final class FTS4TableDefinition {
/// The FTS4 `compress` option
///
/// See <https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options>
/// See https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options
public var compress: String?
/// The FTS4 `uncompress` option
///
/// See <https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options>
/// See https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options
public var uncompress: String?
/// The FTS4 `matchinfo` option
///
/// See <https://www.sqlite.org/fts3.html#the_matchinfo_option>
/// See https://www.sqlite.org/fts3.html#the_matchinfo_option
public var matchinfo: String?
/// Support for the FTS5 `prefix` option
@@ -225,13 +210,9 @@ public final class FTS4TableDefinition {
/// t.column("content")
/// }
///
/// See <https://www.sqlite.org/fts3.html#the_prefix_option>
/// See https://www.sqlite.org/fts3.html#the_prefix_option
public var prefixes: Set<Int>?
init(configuration: VirtualTableConfiguration) {
self.configuration = configuration
}
/// Appends a table column.
///
/// try db.create(virtualTable: "document", using: FTS4()) { t in
@@ -253,7 +234,7 @@ public final class FTS4TableDefinition {
/// 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>
/// See https://sqlite.org/fts5.html#external_content_tables
public func synchronize(withTable tableName: String) {
contentMode = .synchronized(contentTable: tableName)
}
@@ -268,7 +249,7 @@ public final class FTS4TableDefinition {
/// t.column("content") // FTS4ColumnDefinition
/// }
///
/// See <https://www.sqlite.org/fts3.html>
/// See https://www.sqlite.org/fts3.html
public final class FTS4ColumnDefinition {
fileprivate let name: String
fileprivate var isIndexed: Bool
@@ -287,7 +268,7 @@ public final class FTS4ColumnDefinition {
/// t.column("b").notIndexed()
/// }
///
/// See <https://www.sqlite.org/fts3.html#the_notindexed_option>
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
///
/// - returns: Self so that you can further refine the column definition.
@discardableResult
@@ -303,7 +284,7 @@ public final class FTS4ColumnDefinition {
/// t.column("lid").asLanguageId()
/// }
///
/// See <https://www.sqlite.org/fts3.html#the_languageid_option>
/// See https://www.sqlite.org/fts3.html#the_languageid_option
///
/// - returns: Self so that you can further refine the column definition.
@discardableResult
+18 -39
View File
@@ -8,12 +8,12 @@ import Foundation
/// t.column("content")
/// }
///
/// See <https://www.sqlite.org/fts5.html>
/// 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>
/// 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.
@@ -43,7 +43,7 @@ public struct FTS5: VirtualTableModule {
/// t.column("content")
/// }
///
/// See <https://www.sqlite.org/fts5.html>
/// See https://www.sqlite.org/fts5.html
public init() {
}
@@ -52,19 +52,9 @@ public struct FTS5: VirtualTableModule {
/// The virtual table module name
public let moduleName = "fts5"
// TODO: remove when `makeTableDefinition()` is no longer a requirement
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
/// Don't use this method.
public func makeTableDefinition() -> FTS5TableDefinition {
preconditionFailure()
}
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS5TableDefinition {
FTS5TableDefinition(configuration: configuration)
FTS5TableDefinition()
}
/// Don't use this method.
@@ -160,24 +150,18 @@ public struct FTS5: VirtualTableModule {
.map { "old.\($0.quotedDatabaseIdentifier)" }
.joined(separator: ", ")
let ifNotExists = definition.configuration.ifNotExists
? "IF NOT EXISTS "
: ""
// swiftlint:disable line_length
try db.execute(sql: """
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
END;
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
END;
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
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;
""")
// swiftlint:enable line_length
// https://sqlite.org/fts5.html#the_rebuild_command
@@ -259,14 +243,13 @@ public struct FTS5: VirtualTableModule {
/// t.column("content")
/// }
///
/// See <https://www.sqlite.org/fts5.html>
/// See https://www.sqlite.org/fts5.html
public final class FTS5TableDefinition {
enum ContentMode {
case raw(content: String?, contentRowID: String?)
case synchronized(contentTable: String)
}
fileprivate let configuration: VirtualTableConfiguration
fileprivate var columns: [FTS5ColumnDefinition] = []
fileprivate var contentMode: ContentMode = .raw(content: nil, contentRowID: nil)
@@ -276,7 +259,7 @@ public final class FTS5TableDefinition {
/// t.tokenizer = .porter()
/// }
///
/// See <https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization>
/// See https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization
public var tokenizer: FTS5TokenizerDescriptor?
/// The FTS5 `content` option
@@ -288,7 +271,7 @@ public final class FTS5TableDefinition {
/// 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>
/// See https://www.sqlite.org/fts5.html#external_content_and_contentless_tables
public var content: String? {
get {
switch contentMode {
@@ -317,7 +300,7 @@ public final class FTS5TableDefinition {
/// Setting this property invalidates any synchronization previously
/// established with the `synchronize(withTable:)` method.
///
/// See <https://sqlite.org/fts5.html#external_content_tables>
/// See https://sqlite.org/fts5.html#external_content_tables
public var contentRowID: String? {
get {
switch contentMode {
@@ -339,23 +322,19 @@ public final class FTS5TableDefinition {
/// Support for the FTS5 `prefix` option
///
/// See <https://www.sqlite.org/fts5.html#prefix_indexes>
/// 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>
/// 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>
/// https://www.sqlite.org/fts5.html#the_detail_option
public var detail: String?
init(configuration: VirtualTableConfiguration) {
self.configuration = configuration
}
/// Appends a table column.
///
/// try db.create(virtualTable: "document", using: FTS5()) { t in
@@ -377,7 +356,7 @@ public final class FTS5TableDefinition {
/// 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>
/// See https://sqlite.org/fts5.html#external_content_tables
public func synchronize(withTable tableName: String) {
contentMode = .synchronized(contentTable: tableName)
}
@@ -392,7 +371,7 @@ public final class FTS5TableDefinition {
/// t.column("content") // FTS5ColumnDefinition
/// }
///
/// See <https://www.sqlite.org/fts5.html>
/// See https://www.sqlite.org/fts5.html
public final class FTS5ColumnDefinition {
fileprivate let name: String
fileprivate var isIndexed: Bool
@@ -409,7 +388,7 @@ public final class FTS5ColumnDefinition {
/// t.column("b").notIndexed()
/// }
///
/// See <https://www.sqlite.org/fts5.html#the_unindexed_column_option>
/// See https://www.sqlite.org/fts5.html#the_unindexed_column_option
///
/// - returns: Self so that you can further refine the column definition.
@discardableResult
+1 -1
View File
@@ -161,7 +161,7 @@ extension Database {
}
guard code == SQLITE_OK else {
// Assume a GRDB bug: there is no point throwing any error.
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage))
fatalError(DatabaseError(resultCode: code, message: lastErrorMessage).description)
}
}
}
+2 -2
View File
@@ -93,7 +93,7 @@ public struct FTS5Pattern {
}
}
}
try db.makeStatement(sql: "SELECT * FROM document WHERE document MATCH ?")
try db.makeSelectStatement(sql: "SELECT * FROM document WHERE document MATCH ?")
.makeCursor(arguments: [rawPattern])
.next() // error on next() for invalid patterns
}
@@ -114,7 +114,7 @@ extension Database {
/// 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>
/// 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]
Loaded 100 of 268 files, more files were not shown because too many files have changed in this diff. Show more