mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a88067a815 | ||
|
|
df4d5b8603 | ||
|
|
a7b8a73dba | ||
|
|
278c18adfc | ||
|
|
cbd494e3b9 | ||
|
|
c73fb0dd9b | ||
|
|
c966eb3ecf | ||
|
|
217b0a3f3e | ||
|
|
e604a10860 | ||
|
|
ac4f4c6611 | ||
|
|
162da80e4f | ||
|
|
315496928b | ||
|
|
d82cbb6853 | ||
|
|
5fed231856 | ||
|
|
45dfe7d7f1 | ||
|
|
c7d1cca023 | ||
|
|
615f4159d6 | ||
|
|
8057572357 | ||
|
|
da63037948 | ||
|
|
2d3dafad7d | ||
|
|
7ed967b502 | ||
|
|
f545789205 | ||
|
|
79373d5b74 | ||
|
|
f97088d63a | ||
|
|
860faf19f7 | ||
|
|
0f54779386 | ||
|
|
6f125bd3d7 | ||
|
|
4483f037a4 | ||
|
|
20296652dd | ||
|
|
d80922954a | ||
|
|
d67814ef61 | ||
|
|
fb550d30a0 |
No files matched your search
@@ -3,7 +3,6 @@ included:
|
||||
|
||||
disabled_rules:
|
||||
- cyclomatic_complexity
|
||||
- duplicate_enum_cases
|
||||
- file_length
|
||||
- force_cast
|
||||
- force_try
|
||||
|
||||
+85
-19
@@ -30,113 +30,179 @@ jobs:
|
||||
###########################################
|
||||
## Test GRDB Xcode 11.4
|
||||
|
||||
- name: "Test GRDB Xcode 11.4 - GRDBOSX"
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 5.1, macOS)
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 11.4 - GRDBWatchOS"
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 4.2, macOS)
|
||||
script: make test_framework_GRDBOSX_minSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBWatchOS (watchOS)
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS maxTarget"
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 11.4 - GRDBiOS iOS minTarget"
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBiOS_maxTarget_minSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- name: "Test GRDB Xcode 11.4 - GRDBtvOS maxTarget"
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5.1, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 11.4 - GRDBtvOS minTarget"
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 4.2, tvOS <MAX>)
|
||||
script: make test_framework_GRDBtvOS_maxTarget_minSwift
|
||||
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBtvOS (Swift 5.1, tvOS <MIN>)
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- name: "Test GRDB Xcode 11.4 - SPM"
|
||||
- stage: Test GRDB Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDB [SPM] (macOS)
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDBCustom Xcode 11.4
|
||||
|
||||
- name: "Test GRDBCustom Xcode 11.4 - GRDBOSX"
|
||||
- stage: Test GRDBCustom Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBOSX (Swift 5.1, macOS)
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
- name: "Test GRDBCustom Xcode 11.4 - GRDBiOS maxTarget"
|
||||
- stage: Test GRDBCustom Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDBCustom Xcode 11.4 - GRDBiOS minTarget"
|
||||
- stage: Test GRDBCustom Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 4.2, iOS <MAX>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_minSwift
|
||||
|
||||
- stage: Test GRDBCustom Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=GRDBiOS (Swift 5.1, iOS <MIN>)
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test SQLCipher Xcode 11.4
|
||||
|
||||
- name: "Test SQLCipher Xcode 11.4 - SQLCipher 3"
|
||||
- stage: Test SQLCipher Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=SQLCipher 3
|
||||
script: make test_framework_SQLCipher3
|
||||
|
||||
- name: "Test SQLCipher Xcode 11.4 - SQLCipher 4"
|
||||
- stage: Test SQLCipher Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=SQLCipher 4
|
||||
script: make test_framework_SQLCipher4
|
||||
|
||||
###########################################
|
||||
## Test Installation Xcode 11.4
|
||||
|
||||
# Manual Install
|
||||
- name: "Test Installation Xcode 11.4 - Manual Install"
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=Manual Install
|
||||
script: make test_install_manual
|
||||
|
||||
# CocoaPods Lint
|
||||
- name: "Test Installation Xcode 11.4 - CocoaPods Lint"
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=CocoaPods Lint
|
||||
script: make test_CocoaPodsLint_GRDB
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- name: "Test Installation Xcode 11.4 - CocoaPods Framework"
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=CocoaPods GRDB (framework)
|
||||
script: make test_install_GRDB_CocoaPods_framework
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- name: "Test Installation Xcode 11.4 - CocoaPods Static"
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=CocoaPods GRDB (static)
|
||||
script: make test_install_GRDB_CocoaPods_static
|
||||
|
||||
# SPM Install
|
||||
- name: "Test Installation Xcode 11.4 - SPM Package"
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=SPM Package
|
||||
script: make test_install_SPM_Package
|
||||
|
||||
# SPM Install
|
||||
- name: "Test Installation Xcode 11.4 - SPM Package in Xcode Project"
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=SPM Package in Xcode Project
|
||||
script: make test_install_SPM_Project
|
||||
|
||||
# Custom SQLite Install
|
||||
- name: "Test Installation Xcode 11.4 - Custom SQLite"
|
||||
- stage: Test Installation Xcode 11.4
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode11.4
|
||||
env:
|
||||
- TID=Custom SQLite
|
||||
script: make test_install_customSQLite
|
||||
@@ -4,18 +4,6 @@ Here is a list of people who were happy to meet GRDB :-)
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/stephencelis/status/1263518304980918274
|
||||
|
||||
> GRDB.swift is great! (I say this as the person that started SQLite.swift long ago.) And @groue’s very helpful and friendly.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/peres/status/1262682199482142720
|
||||
|
||||
> GRDB in already in my top3 when it comes to documentation. Clearly and pragmatically explained.GRDB in already in my top3 when it comes to documentation. Clearly and pragmatically explained.
|
||||
|
||||
---
|
||||
|
||||
https://twitter.com/layoutsubviews/status/1249940744929816582
|
||||
|
||||
> Mixing SQLite / GRDB with Combine is my whole world right now, and it is delightful.
|
||||
|
||||
+8
-147
@@ -5,13 +5,15 @@ All notable changes to this project will be documented in this file.
|
||||
|
||||
GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library.
|
||||
|
||||
|
||||
<!--
|
||||
[Next Release](#next-release)
|
||||
-->
|
||||
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.0.0` Betas - [5.0.0-beta](#500-beta) | [5.0.0-beta.2](#500-beta2) | [5.0.0-beta.3](#500-beta3) | [5.0.0-beta.4](#500-beta4) | [5.0.0-beta.5](#500-beta5)
|
||||
- `5.0.x` Development - [GRDB5 Branch](#grdb5-branch)
|
||||
|
||||
|
||||
#### 4.x Releases
|
||||
@@ -74,148 +76,14 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
## Next Release
|
||||
-->
|
||||
|
||||
## 5.0.0-beta.5
|
||||
|
||||
Released June 15, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.4...v5.0.0-beta.5)
|
||||
|
||||
- **Breaking Change** [#795](https://github.com/groue/GRDB.swift/pull/795): Enhanced support for WAL Checkpoints
|
||||
- **New**: `Database.maximumStatementArgumentCount` returns the maximum number of arguments accepted by an SQLite statement.
|
||||
- **New**: Optimize DatabasePool handling of ValueObservation when SQLite is compiled with the SQLITE_ENABLE_SNAPSHOT option. We are now able to avoid fetching the observed value when we can prove that the database wasn't changed between the initial fetch and the beginning of transaction tracking. This optimization avoids duplicate notifications.
|
||||
- **New**: The query interface now exposes the primary key through `TableRecord.primaryKey`, as well as the `selectPrimaryKey(as:)` method.
|
||||
## GRDB5 Branch
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- The [Demo Application](Documentation/DemoApps/GRDBDemoiOS) was updated for better conformance with the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) Guide.
|
||||
|
||||
- A new [FAQ: Associations](README.md#faq-associations) addresses three frequent questions:
|
||||
- [How do I filter records and only keep those that are associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record)
|
||||
- [How do I filter records and only keep those that are NOT associated to another record?](README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record)
|
||||
- [How do I select only one column of an associated record?](README.md#how-do-i-select-only-one-column-of-an-associated-record)
|
||||
|
||||
- The guide for [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) now recommends enabling the `SQLITE_ENABLE_SNAPSHOT` option.
|
||||
|
||||
|
||||
## 5.0.0-beta.4
|
||||
|
||||
Released June 6, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.3...v5.0.0-beta.4)
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) was updated for RxGRDB and GRDBCombine 1.0 beta 2, which haved change their way to configure how ValueObservation schedules fresh database values.
|
||||
- The [SQL Functions](README.md#sql-functions) chapter was updated for the new `julianDay` and `dateTime` functions.
|
||||
|
||||
### New
|
||||
|
||||
- [#794](https://github.com/groue/GRDB.swift/pull/794): Name of Database Connections
|
||||
- Add the `julianDay` and `dateTime` functions
|
||||
|
||||
|
||||
## 5.0.0-beta.3
|
||||
|
||||
Released June 1, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta.2...v5.0.0-beta.3)
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- Updated FAQ: [How do I print a request as SQL?](README.md#how-do-i-print-a-request-as-sql)
|
||||
- New FAQ: [How do I monitor the duration of database statements execution?](README.md#how-do-i-monitor-the-duration-of-database-statements-execution)
|
||||
|
||||
### Fixed
|
||||
|
||||
- [#784](https://github.com/groue/GRDB.swift/pull/784): Fix observation of eager-loaded to-many associations
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- [#790](https://github.com/groue/GRDB.swift/pull/790): Bump required iOS version to 10.0
|
||||
- [#791](https://github.com/groue/GRDB.swift/pull/791): Extend tracing of statement execution
|
||||
|
||||
|
||||
## 5.0.0-beta.2
|
||||
|
||||
Released May 11, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v5.0.0-beta...v5.0.0-beta.2)
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) describes the sunsetting of custom `FetchRequest` types.
|
||||
- The [Sharing a Database](Documentation/SharingADatabase.md) guide has an updated recommendation for opening writer connections to a shared database.
|
||||
|
||||
### New
|
||||
|
||||
- [#772](https://github.com/groue/GRDB.swift/pull/772): Update the Database Sharing Guide with mention of the persistent WAL mode
|
||||
- [#775](https://github.com/groue/GRDB.swift/pull/775): DatabaseMigrator can check if it has been superseded
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- [#774](https://github.com/groue/GRDB.swift/pull/774): All requests are usable as SQL expressions and collections
|
||||
|
||||
### Fixed
|
||||
|
||||
- [#773](https://github.com/groue/GRDB.swift/pull/773): Allow subqueries to refer to outer tables
|
||||
|
||||
|
||||
## 5.0.0-beta
|
||||
|
||||
Released May 2, 2020 • [diff](https://github.com/groue/GRDB.swift/compare/v4.14.0...v5.0.0-beta)
|
||||
|
||||
GRDB 5 is a release focused on **Swift 5.2**, and **removing technical debt**.
|
||||
|
||||
There are breaking changes, though as few as possible. They open the door for future library improvements. And they have GRDB, [GRDBCombine](http://github.com/groue/GRDBCombine), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) offer a common behavior.
|
||||
|
||||
New features include support for SQL subqueries, and a simplified handling of database errors. The most demanding users will also find it easier to switch between the system SQLite, SQLCipher, and custom SQLite builds.
|
||||
|
||||
<details>
|
||||
<summary>A glimpse on the new features</summary>
|
||||
|
||||
All requests can now be used as subqueries:
|
||||
|
||||
```swift
|
||||
// Define a request with the query interface or raw SQL
|
||||
let maximumScore = Player.select(max(Column("score")))
|
||||
let maximumScore: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
|
||||
// Use the request as a subquery in the query interface
|
||||
let request = Player.filter(Column("score") == maximumScore)
|
||||
let bestPlayers = try request.fetchAll(db)
|
||||
|
||||
// Use the request as a subquery in SQL requests
|
||||
let request: SQLRequest<Player> = "SELECT * FROM player WHERE score = (\(maximumScore))"
|
||||
let bestPlayers = try request.fetchAll(db)
|
||||
```
|
||||
|
||||
Catch specific SQLite error codes in a simplified fashion:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try ...
|
||||
} catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
// foreign key constraint error
|
||||
} catch DatabaseError.SQLITE_CONSTRAINT {
|
||||
// any other constraint error
|
||||
} catch {
|
||||
// any other database error
|
||||
}
|
||||
```
|
||||
|
||||
Reuse the same code for system SQLite, SQLCipher, and custom SQLite builds:
|
||||
|
||||
```swift
|
||||
// Supported in all GRDB flavors
|
||||
import GRDB
|
||||
let sqliteVersion = String(cString: sqlite3_libversion())
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
### Documentation Diff
|
||||
|
||||
- **[Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)**: how to upgrade your apps, and deal with breaking changes.
|
||||
- [ValueObservation](README.md#valueobservation): this chapter describes the new ValueObservation behaviors.
|
||||
- [DatabaseError](README.md#databaseerror): learn how to catch and match DatabaseError on their codes, in a fashion similar to `CocoaError`.
|
||||
- [Batch Updates](README.md#update-requests): this chapter is updated for the new `set(to:)` method.
|
||||
- [SQL Operators](README.md#sql-operators): introduces support for SQL and query interface subqueries.
|
||||
- [How do I print a request as SQL?](README.md#how-do-i-print-a-request-as-sql) This FAQ was updated for GRDB 5.
|
||||
- [SQL Interpolation](Documentation/SQLInterpolation.md): this guide now describes how to embed subqueries and record columns in your SQL literals.
|
||||
- [Joined Queries Support](README.md#joined-queries-support): describes the GRDB 5 way of dealing with complex and hand-crafted SQL queries.
|
||||
- [Raw SQLite Pointers](README.md#raw-sqlite-pointers) and [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md): `import GRDB` now provides access to the full [C SQLite API](https://www.sqlite.org/capi3ref.html), and custom SQLite builds.
|
||||
- The [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md) Guide helps migrating your apps and turn your attention where it needs to focus during the upgrade.
|
||||
- The [ValueObservation](README.md#valueobservation) chapter has been fully rewritten and describes the new ValueObservation behaviors.
|
||||
- The [DatabaseError](README.md#databaseerror) chapter demonstrates the new way to catch and match DatabaseError on their codes, in a fashion similar to CocoaError et al.
|
||||
- The [Batch Updates](README.md#update-requests) chapter has been updated for the new `set(to:)` method.
|
||||
|
||||
### New
|
||||
|
||||
@@ -240,13 +108,6 @@ let sqliteVersion = String(cString: sqlite3_libversion())
|
||||
- [#747](https://github.com/groue/GRDB.swift/pull/747): Rename GRDBCustomSQLite to GRDB
|
||||
- [#750](https://github.com/groue/GRDB.swift/pull/750): Batch updates do not need any operator
|
||||
- [#752](https://github.com/groue/GRDB.swift/pull/752): Remove ValueObservation.combine
|
||||
- [#770](https://github.com/groue/GRDB.swift/pull/770): Subqueries
|
||||
|
||||
### Fixed
|
||||
|
||||
- [#601](https://github.com/groue/GRDB.swift/pull/601): ValueObservation won't start until concurrent write transaction has ended
|
||||
- [#697](https://github.com/groue/GRDB.swift/pull/697): `SQLInterpolation` could not work with `QueryInterfaceRequest`
|
||||
- [#743](https://github.com/groue/GRDB.swift/pull/743): Rename GRDBCustomSQLite to GRDB for compatibility with dependents?
|
||||
|
||||
|
||||
## 4.14.0
|
||||
|
||||
@@ -1,4 +1,250 @@
|
||||
Sharing a Database in an App Group Container
|
||||
============================================
|
||||
|
||||
This guide [has moved](SharingADatabase.md).
|
||||
On iOS, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati).
|
||||
|
||||
A shared database is accessed from several SQLite connections, from several processes. This creates challenges at various levels:
|
||||
|
||||
1. **Database setup** may be attempted by multiple processes, concurrently.
|
||||
2. **SQLite** may throw `SQLITE_BUSY` errors, code 5, "database is locked".
|
||||
3. **iOS** may kill your application with a `0xDEAD10CC` exception.
|
||||
4. **GRDB** database observation misses changes performed by external processes.
|
||||
|
||||
We'll address all of those challenges below.
|
||||
|
||||
- [Use a Database Pool]
|
||||
- [How to limit the `SQLITE_BUSY` error]
|
||||
- [How to limit the `0xDEAD10CC` exception]
|
||||
- [How to perform cross-process database observation]
|
||||
|
||||
|
||||
## Use a Database Pool
|
||||
|
||||
In order to access a shared database, use a [Database Pool]. It opens the database in the [WAL mode](https://www.sqlite.org/wal.html), which helps sharing a database.
|
||||
|
||||
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
|
||||
|
||||
- In a process that can create and write in the database, use this sample code:
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL
|
||||
func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError, byAccessor: { url in
|
||||
do {
|
||||
dbPool = try openDatabase(at: url)
|
||||
} catch {
|
||||
dbError = error
|
||||
}
|
||||
})
|
||||
if let error = dbError ?? coordinatorError {
|
||||
throw error
|
||||
}
|
||||
return dbPool!
|
||||
}
|
||||
|
||||
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
let dbPool = try DatabasePool(path: databaseURL.path)
|
||||
|
||||
// Perform here other database setups, such as defining
|
||||
// the database schema with a DatabaseMigrator.
|
||||
try migrator.migrate(dbPool)
|
||||
return dbPool
|
||||
}
|
||||
```
|
||||
|
||||
- In a process that only reads in the database, use this sample code:
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL,
|
||||
/// or nil if the database is not created yet, or does not have the required
|
||||
/// schema version.
|
||||
func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError, byAccessor: { url in
|
||||
do {
|
||||
dbPool = try openReadOnlyDatabase(at: url)
|
||||
} catch {
|
||||
dbError = error
|
||||
}
|
||||
})
|
||||
if let error = dbError ?? coordinatorError {
|
||||
throw error
|
||||
}
|
||||
return dbPool
|
||||
}
|
||||
|
||||
private func openReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
do {
|
||||
var configuration = Configuration()
|
||||
configuration.readonly = true
|
||||
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
|
||||
// Check here if the database schema is correct, for example
|
||||
// with a DatabaseMigrator.
|
||||
if try dbPool.read(migrator.hasCompletedMigrations) {
|
||||
return dbPool
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
} catch {
|
||||
if FileManager.default.fileExists(atPath: databaseURL.path) {
|
||||
throw error
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## How to limit the `SQLITE_BUSY` error
|
||||
|
||||
> The SQLITE_BUSY result code indicates that the database file could not be written (or in some cases read) because of concurrent activity by some other database connection, usually a database connection in a separate process.
|
||||
|
||||
See https://www.sqlite.org/rescode.html#busy for more information about this error.
|
||||
|
||||
If several processes want to write in the database, configure the database pool of each process that wants to write:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.busyMode = .timeout(/* a TimeInterval */)
|
||||
configuration.defaultTransactionKind = .immediate
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
With such a setup, you may still get `SQLITE_BUSY` (5, "database is locked") errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout.
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbPool.write { db in ... }
|
||||
} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
|
||||
// Another process won't let you write. Deal with it.
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: In order to be nice to other processes, measure the duration of your longest writes, and attempt at optimizing the ones that last for too long.
|
||||
|
||||
|
||||
## How to limit the `0xDEAD10CC` exception
|
||||
|
||||
> 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/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 from your database preparation function:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase = { (db: Database) in
|
||||
try db.usePassphrase("secret")
|
||||
try db.execute(sql: "PRAGMA cipher_plaintext_header_size = 32")
|
||||
}
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
Set the `observesSuspensionNotifications` configuration flag:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.suspendsOnBackgroundTimeExpiration = true
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
Post `Database.suspendNotification` when the application is about to be [suspended](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle). You can for example post this notification from `UIApplicationDelegate.applicationDidEnterBackground(_:)`, or in the expiration handler of a [background task](https://forums.developer.apple.com/thread/85066).
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func applicationDidEnterBackground(_ application: UIApplication) {
|
||||
// Suspend databases
|
||||
NotificationCenter.default.post(name: Database.suspendNotification, object: self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Post `Database.resumeNotification` from `UIApplicationDelegate.applicationWillEnterForeground(_:)` (or `SceneDelegate.sceneWillEnterForeground(_:)` for scene-based applications):
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func applicationWillEnterForeground(_ application: UIApplication) {
|
||||
// Resume databases
|
||||
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If the application uses the background modes supported by iOS, post `Database.resumeNotification` method from each and every background mode callback that may use the database. For example, if your application supports background fetches:
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
|
||||
// Resume databases
|
||||
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
|
||||
// Proceed with background fetch
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception are greatly reduced. If you see one in your crash logs, please open an issue!
|
||||
|
||||
In exchange, you will get `SQLITE_INTERRUPT` (9) or `SQLITE_ABORT` (4) errors, with messages "Database is suspended", "Transaction was aborted", or "interrupted", for any attempt at writing in the database when it is suspended.
|
||||
|
||||
You can catch those errors:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbPool.write { db in ... }
|
||||
} catch let error as DatabaseError where error.isInterruptionError {
|
||||
// Oops, the database is suspended.
|
||||
// Maybe try again after database is resumed?
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## How to perform cross-process database observation
|
||||
|
||||
GRDB [Database Observation] features, as well as [GRDBCombine] and [RxGRDB], are not able to notify database changes performed by other processes.
|
||||
|
||||
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
|
||||
|
||||
You can trigger those notifications automatically with [DatabaseRegionObservation]:
|
||||
|
||||
```swift
|
||||
// Notify all changes made to the "player" and "team" database tables
|
||||
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
|
||||
let observer = try observation.start(in: dbPool) { (db: Database) in
|
||||
// Notify other processes
|
||||
}
|
||||
|
||||
// Notify all changes made to the database
|
||||
let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
|
||||
let observer = try observation.start(in: dbPool) { (db: Database) in
|
||||
// Notify other processes
|
||||
}
|
||||
```
|
||||
|
||||
[Use a Database Pool]: #use-a-database-pool
|
||||
[How to limit the `SQLITE_BUSY` error]: #how-to-limit-the-sqlite_busy-error
|
||||
[How to limit the `0xDEAD10CC` exception]: #how-to-limit-the-0xdead10cc-exception
|
||||
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
|
||||
[Database Pool]: ../README.md#database-pools
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[GRDBCombine]: http://github.com/groue/GRDBCombine
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
|
||||
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
@@ -39,14 +39,7 @@ GRDB Associations
|
||||
- [Aggregate Operations]
|
||||
- [Isolation of Multiple Aggregates]
|
||||
- [DerivableRequest Protocol]
|
||||
|
||||
**[FAQ]**
|
||||
|
||||
- [How do I filter records and only keep those that are associated to another record?](../README.md#how-do-i-filter-records-and-only-keep-those-that-are-associated-to-another-record)
|
||||
- [How do I filter records and only keep those that are NOT associated to another record?](../README.md#how-do-i-filter-records-and-only-keep-those-that-are-not-associated-to-another-record)
|
||||
- [How do I select only one column of an associated record?](../README.md#how-do-i-select-only-one-column-of-an-associated-record)
|
||||
|
||||
**[Known Issues]**
|
||||
- [Known Issues]
|
||||
|
||||
|
||||
## Associations Benefits
|
||||
@@ -1837,7 +1830,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
}
|
||||
|
||||
// SELECT author.*,
|
||||
// COUNT(DISTINCT book.id) AS bookCount,
|
||||
// COUNT(DISTINCT book.rowid) AS bookCount,
|
||||
// MAX(book.year) AS maxBookYear,
|
||||
// FROM author
|
||||
// LEFT JOIN book ON book.authorId = author.id
|
||||
@@ -1930,7 +1923,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
|
||||
FROM author
|
||||
LEFT JOIN book ON book.authorId = author.id
|
||||
GROUP BY author.id
|
||||
HAVING COUNT(DISTINCT book.id) = 0
|
||||
HAVING COUNT(DISTINCT book.rowid) = 0
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -1949,7 +1942,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
|
||||
FROM author
|
||||
LEFT JOIN book ON book.authorId = author.id
|
||||
GROUP BY author.id
|
||||
HAVING COUNT(DISTINCT book.id) > 0
|
||||
HAVING COUNT(DISTINCT book.rowid) > 0
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -1968,7 +1961,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
|
||||
FROM author
|
||||
LEFT JOIN book ON book.authorId = author.id
|
||||
GROUP BY author.id
|
||||
HAVING COUNT(DISTINCT book.id) >= 2
|
||||
HAVING COUNT(DISTINCT book.rowid) >= 2
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -2006,7 +1999,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
|
||||
FROM author
|
||||
LEFT JOIN book ON book.authorId = author.id AND book.kind = 'novel'
|
||||
GROUP BY author.id
|
||||
HAVING COUNT(DISTINCT book.id) > 0
|
||||
HAVING COUNT(DISTINCT book.rowid) > 0
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -2027,7 +2020,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
|
||||
LEFT JOIN book ON book.authorId = author.id
|
||||
LEFT JOIN painting ON painting.authorId = author.id
|
||||
GROUP BY author.id
|
||||
HAVING COUNT(DISTINCT book.id) > COUNT(DISTINCT painting.id)
|
||||
HAVING COUNT(DISTINCT book.rowid) > COUNT(DISTINCT painting.rowid)
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -2047,7 +2040,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
|
||||
LEFT JOIN book ON book.authorId = author.id
|
||||
LEFT JOIN painting ON painting.authorId = author.id
|
||||
GROUP BY author.id
|
||||
HAVING ((COUNT(DISTINCT book.id) = 0) AND (COUNT(DISTINCT painting.id) > 0))
|
||||
HAVING ((COUNT(DISTINCT book.rowid) = 0) AND (COUNT(DISTINCT painting.rowid) > 0))
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -2072,7 +2065,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
LEFT JOIN book ON book.authorId = author.id
|
||||
LEFT JOIN painting ON painting.authorId = author.id
|
||||
GROUP BY author.id
|
||||
HAVING ((COUNT(DISTINCT book.id) = 0) AND (COUNT(DISTINCT painting.id) = 0))
|
||||
HAVING ((COUNT(DISTINCT book.rowid) = 0) AND (COUNT(DISTINCT painting.rowid) = 0))
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -2108,8 +2101,8 @@ Aggregates can be modified and combined with Swift operators:
|
||||
|
||||
```sql
|
||||
SELECT author.*,
|
||||
(COUNT(DISTINCT book.id) +
|
||||
COUNT(DISTINCT painting.id)) AS workCount
|
||||
(COUNT(DISTINCT book.rowid) +
|
||||
COUNT(DISTINCT painting.rowid)) AS workCount
|
||||
FROM author
|
||||
LEFT JOIN book ON book.authorId = author.id
|
||||
LEFT JOIN painting ON painting.authorId = author.id
|
||||
@@ -2190,7 +2183,7 @@ In this other example, the `Author.books` and `Author.paintings` have the distin
|
||||
|
||||
```sql
|
||||
SELECT author.*,
|
||||
(COUNT(DISTINCT book.id) + COUNT(DISTINCT painting.id)) AS workCount
|
||||
(COUNT(DISTINCT book.rowid) + COUNT(DISTINCT painting.rowid)) AS workCount
|
||||
FROM author
|
||||
LEFT JOIN book ON book.authorId = author.id
|
||||
LEFT JOIN painting ON painting.authorId = author.id
|
||||
@@ -2225,8 +2218,8 @@ But in the following example, we use the same association `Author.books` twice,
|
||||
|
||||
```sql
|
||||
SELECT author.*,
|
||||
COUNT(DISTINCT book1.id) AS novelCount,
|
||||
COUNT(DISTINCT book2.id) AS theatrePlayCount
|
||||
COUNT(DISTINCT book1.rowid) AS novelCount,
|
||||
COUNT(DISTINCT book2.rowid) AS theatrePlayCount
|
||||
FROM author
|
||||
LEFT JOIN book book1 ON book1.authorId = author.id AND book1.kind = 'novel'
|
||||
LEFT JOIN book book2 ON book2.authorId = author.id AND book2.kind = 'theatrePlay'
|
||||
@@ -2265,8 +2258,8 @@ But in the following example, we use the same association `Author.books` twice,
|
||||
|
||||
```sql
|
||||
SELECT author.*,
|
||||
COUNT(DISTINCT book.id) AS novelCount,
|
||||
COUNT(DISTINCT book.id) AS theatrePlayCount
|
||||
COUNT(DISTINCT book.rowid) AS novelCount,
|
||||
COUNT(DISTINCT book.rowid) AS theatrePlayCount
|
||||
FROM author
|
||||
LEFT JOIN book ON book.authorId = author.id
|
||||
AND (book.kind = 'novel' AND book.kind = 'theatrePlay')
|
||||
@@ -2429,7 +2422,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[Ordered Associations]: #ordered-associations
|
||||
[The Types of Associations]: #the-types-of-associations
|
||||
[FetchableRecord]: ../README.md#fetchablerecord-protocols
|
||||
[migration]: Migrations.md
|
||||
[migration]: ../README.md#migrations
|
||||
[Record]: ../README.md#records
|
||||
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
|
||||
[Associations and the Database Schema]: #associations-and-the-database-schema
|
||||
@@ -2475,4 +2468,3 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[persistence methods]: ../README.md#persistence-methods
|
||||
[database observation tools]: ../README.md#database-changes-observation
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[FAQ]: ../README.md#faq-associations
|
||||
@@ -19,9 +19,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
git submodule update --init SQLiteCustom/src
|
||||
```
|
||||
|
||||
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
|
||||
|
||||
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](../README.md#valueobservation) when you use a [Database Pool](../README.md#database-pools).
|
||||
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5` and `SQLITE_ENABLE_PREUPDATE_HOOK`.
|
||||
|
||||
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
|
||||
|
||||
@@ -32,7 +30,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
```xcconfig
|
||||
// As many -D options as there are custom SQLite compilation options
|
||||
// Note: there is no space between -D and the option name.
|
||||
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_SNAPSHOT -DSQLITE_ENABLE_FTS5
|
||||
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_PREUPDATE_HOOK
|
||||
```
|
||||
|
||||
- `GRDBCustomSQLite-USER.xcconfig`: this file lets GRDB know about extra compilation flags, and enables extra GRDB APIs.
|
||||
@@ -40,15 +38,15 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
```xcconfig
|
||||
// As many -D options as there are custom SQLite compilation options
|
||||
// Note: there is one space between -D and the option name.
|
||||
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_SNAPSHOT -D SQLITE_ENABLE_FTS5
|
||||
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
```
|
||||
|
||||
- `GRDBCustomSQLite-USER.h`: this file lets your application know about extra compilation flags.
|
||||
|
||||
```c
|
||||
// As many #define as there are custom SQLite compilation options
|
||||
#define SQLITE_ENABLE_SNAPSHOT
|
||||
#define SQLITE_ENABLE_FTS5
|
||||
#define SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
```
|
||||
|
||||
- `GRDBCustomSQLite-INSTALL.sh`: this file installs the three other files.
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; };
|
||||
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; };
|
||||
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; };
|
||||
56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */; };
|
||||
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -181,7 +181,7 @@
|
||||
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = "<group>"; };
|
||||
56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
|
||||
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = "<group>"; };
|
||||
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewController.swift; sourceTree = "<group>"; };
|
||||
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayersViewController.swift; sourceTree = "<group>"; };
|
||||
56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
@@ -273,15 +273,15 @@
|
||||
56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56B036121E8D9EBE003B6DA4 /* Info.plist */,
|
||||
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
|
||||
56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */,
|
||||
56B036191E8D9F38003B6DA4 /* AppDatabase.swift */,
|
||||
56B0361A1E8D9F38003B6DA4 /* Player.swift */,
|
||||
56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */,
|
||||
56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */,
|
||||
56B036201E8D9F4C003B6DA4 /* PlayersViewController.swift */,
|
||||
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
|
||||
56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */,
|
||||
56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */,
|
||||
56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */,
|
||||
56B036121E8D9EBE003B6DA4 /* Info.plist */,
|
||||
);
|
||||
path = GRDBDemoiOS;
|
||||
sourceTree = "<group>";
|
||||
@@ -507,7 +507,7 @@
|
||||
56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */,
|
||||
56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */,
|
||||
56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */,
|
||||
56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */,
|
||||
56B036241E8D9F4C003B6DA4 /* PlayersViewController.swift in Sources */,
|
||||
56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
|
||||
@@ -1,22 +1,26 @@
|
||||
import GRDB
|
||||
|
||||
/// AppDatabase lets the application access the database.
|
||||
/// A type responsible for initializing the application database.
|
||||
///
|
||||
/// It applies the pratices recommended at
|
||||
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
final class AppDatabase {
|
||||
private let dbQueue: DatabaseQueue
|
||||
/// See AppDelegate.setupDatabase()
|
||||
struct AppDatabase {
|
||||
|
||||
/// Creates an AppDatabase and updates its schema if necessary.
|
||||
init(_ dbQueue: DatabaseQueue) throws {
|
||||
self.dbQueue = dbQueue
|
||||
/// Creates a fully initialized database at path
|
||||
static func openDatabase(atPath path: String) throws -> DatabaseQueue {
|
||||
// Connect to the database
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let dbQueue = try DatabaseQueue(path: path)
|
||||
|
||||
// Define the database schema
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
return dbQueue
|
||||
}
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
|
||||
private var migrator: DatabaseMigrator {
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#migrations
|
||||
static var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
migrator.registerMigration("createPlayer") { db in
|
||||
@@ -50,107 +54,3 @@ final class AppDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Access
|
||||
//
|
||||
// This extension defines methods that fulfill application needs, both in terms
|
||||
// of writes and reads.
|
||||
|
||||
extension AppDatabase {
|
||||
|
||||
// MARK: Writes
|
||||
|
||||
/// Save (insert or update) a player.
|
||||
func savePlayer(_ player: inout Player) throws {
|
||||
try dbQueue.write { db in
|
||||
try player.save(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete one player
|
||||
func deletePlayer(_ player: Player) throws {
|
||||
try dbQueue.write { db in
|
||||
_ = try player.delete(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Delete all players
|
||||
func deleteAllPlayers() throws {
|
||||
try dbQueue.write { db in
|
||||
_ = try Player.deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
/// Refresh all players (by performing some random changes, for demo purpose).
|
||||
func refreshPlayers() throws {
|
||||
try dbQueue.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
// Insert new random players
|
||||
for _ in 0..<8 {
|
||||
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
|
||||
try player.insert(db)
|
||||
}
|
||||
} else {
|
||||
// Insert a player
|
||||
if Bool.random() {
|
||||
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
|
||||
try player.insert(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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Reads
|
||||
|
||||
/// Tracks changes in the number of players
|
||||
func observePlayerCount(
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Int) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
ValueObservation
|
||||
.tracking(Player.fetchCount)
|
||||
.start(
|
||||
in: dbQueue,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
/// Tracks changes in players ordered by name
|
||||
func observePlayersOrderedByName(
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping ([Player]) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
ValueObservation
|
||||
.tracking(Player.all().orderedByName().fetchAll)
|
||||
.start(
|
||||
in: dbQueue,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
|
||||
/// Tracks changes in players ordered by score
|
||||
func observePlayersOrderedByScore(
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping ([Player]) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
ValueObservation
|
||||
.tracking(Player.all().orderedByScore().fetchAll)
|
||||
.start(
|
||||
in: dbQueue,
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
// The shared application database
|
||||
var appDatabase: AppDatabase!
|
||||
// The shared database queue
|
||||
var dbQueue: DatabaseQueue!
|
||||
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
@@ -14,14 +14,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
}
|
||||
|
||||
private func setupDatabase(_ application: UIApplication) throws {
|
||||
// AppDelegate is responsible for choosing the location of the database file.
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let databaseURL = try FileManager.default
|
||||
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
.appendingPathComponent("db.sqlite")
|
||||
let dbQueue = try DatabaseQueue(path: databaseURL.path)
|
||||
|
||||
// Create the shared application database
|
||||
appDatabase = try AppDatabase(dbQueue)
|
||||
dbQueue = try AppDatabase.openDatabase(atPath: databaseURL.path)
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="16097" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
|
||||
<device id="retina6_1" orientation="portrait" appearance="light"/>
|
||||
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15505" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="UAh-8N-CM8">
|
||||
<device id="retina4_7" orientation="portrait" appearance="light"/>
|
||||
<dependencies>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="16087"/>
|
||||
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15510"/>
|
||||
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
|
||||
</dependencies>
|
||||
<scenes>
|
||||
@@ -10,25 +10,25 @@
|
||||
<scene sceneID="Juk-Ad-tZ2">
|
||||
<objects>
|
||||
<tableViewController id="iNr-Oe-muq" customClass="PlayerEditionViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="insetGrouped" separatorStyle="none" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="-1" estimatedSectionHeaderHeight="-1" sectionFooterHeight="-1" estimatedSectionFooterHeight="-1" id="vlV-lc-eQA">
|
||||
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" dataMode="static" style="plain" separatorStyle="none" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="28" sectionFooterHeight="28" id="vlV-lc-eQA">
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<sections>
|
||||
<tableViewSection headerTitle="Name" id="Nzq-eO-jT3">
|
||||
<tableViewSection id="Nzq-eO-jT3">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="2gb-gB-918">
|
||||
<rect key="frame" x="20" y="55.5" width="374" height="44"/>
|
||||
<rect key="frame" x="0.0" y="28" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="2gb-gB-918" id="iyM-TJ-JB4">
|
||||
<rect key="frame" x="0.0" y="0.0" width="374" height="44"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
|
||||
<rect key="frame" x="20" y="11" width="334" height="22"/>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Name" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="m5m-Zs-j0z">
|
||||
<rect key="frame" x="16" y="11.5" width="343" height="21"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<textInputTraits key="textInputTraits" autocapitalizationType="words" autocorrectionType="no" spellCheckingType="no" returnKeyType="next"/>
|
||||
<connections>
|
||||
<action selector="textFieldDidChange:" destination="iNr-Oe-muq" eventType="editingChanged" id="EmC-Rp-f6S"/>
|
||||
<outlet property="delegate" destination="iNr-Oe-muq" id="K2p-7d-teD"/>
|
||||
</connections>
|
||||
</textField>
|
||||
@@ -40,24 +40,17 @@
|
||||
</constraints>
|
||||
</tableViewCellContentView>
|
||||
</tableViewCell>
|
||||
</cells>
|
||||
</tableViewSection>
|
||||
<tableViewSection headerTitle="Score" id="Urb-uF-sj1">
|
||||
<cells>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="none" indentationWidth="10" id="vp3-Ft-Gth">
|
||||
<rect key="frame" x="20" y="155" width="374" height="44"/>
|
||||
<rect key="frame" x="0.0" y="72" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="vp3-Ft-Gth" id="ccO-0O-u72">
|
||||
<rect key="frame" x="0.0" y="0.0" width="374" height="44"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="0" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
|
||||
<rect key="frame" x="20" y="11" width="334" height="22"/>
|
||||
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" horizontalCompressionResistancePriority="250" contentHorizontalAlignment="left" contentVerticalAlignment="center" placeholder="Score" adjustsFontForContentSizeCategory="YES" minimumFontSize="17" clearButtonMode="whileEditing" translatesAutoresizingMaskIntoConstraints="NO" id="rZ9-Fa-cyr">
|
||||
<rect key="frame" x="16" y="11.5" width="343" height="21"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<textInputTraits key="textInputTraits" autocorrectionType="no" spellCheckingType="no" keyboardType="numberPad" returnKeyType="done"/>
|
||||
<connections>
|
||||
<action selector="textFieldDidChange:" destination="iNr-Oe-muq" eventType="editingChanged" id="ebo-2z-Z9P"/>
|
||||
</connections>
|
||||
</textField>
|
||||
</subviews>
|
||||
<constraints>
|
||||
@@ -108,7 +101,7 @@
|
||||
<objects>
|
||||
<navigationController id="ein-Sr-i8w" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="zIT-dB-Mfo">
|
||||
<rect key="frame" x="0.0" y="0.0" width="414" height="56"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="56"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
@@ -124,7 +117,7 @@
|
||||
<objects>
|
||||
<navigationController id="UAh-8N-CM8" sceneMemberID="viewController">
|
||||
<navigationBar key="navigationBar" contentMode="scaleToFill" id="U7d-1C-GnL">
|
||||
<rect key="frame" x="0.0" y="44" width="414" height="44"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="44"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
</navigationBar>
|
||||
<connections>
|
||||
@@ -138,27 +131,27 @@
|
||||
<!--Hall Of Fame-->
|
||||
<scene sceneID="9su-ms-vdJ">
|
||||
<objects>
|
||||
<tableViewController id="PJp-Eq-ZjA" customClass="PlayerListViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableViewController id="PJp-Eq-ZjA" customClass="PlayersViewController" customModule="GRDBDemoiOS" customModuleProvider="target" sceneMemberID="viewController">
|
||||
<tableView key="view" clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="-1" estimatedRowHeight="-1" sectionHeaderHeight="-1" estimatedSectionHeaderHeight="-1" sectionFooterHeight="-1" estimatedSectionFooterHeight="-1" id="tX0-ON-WSI">
|
||||
<rect key="frame" x="0.0" y="0.0" width="414" height="896"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
|
||||
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
|
||||
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
|
||||
<prototypes>
|
||||
<tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" accessoryType="disclosureIndicator" indentationWidth="10" reuseIdentifier="Player" textLabel="G8y-VE-YRu" detailTextLabel="NNc-J4-xiE" style="IBUITableViewCellStyleValue1" id="bFj-Hd-fwd">
|
||||
<rect key="frame" x="0.0" y="28" width="414" height="43.5"/>
|
||||
<rect key="frame" x="0.0" y="28" width="375" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="bFj-Hd-fwd" id="kDf-TZ-xhb">
|
||||
<rect key="frame" x="0.0" y="0.0" width="383" height="43.5"/>
|
||||
<rect key="frame" x="0.0" y="0.0" width="348" height="43.5"/>
|
||||
<autoresizingMask key="autoresizingMask"/>
|
||||
<subviews>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Title" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" id="G8y-VE-YRu">
|
||||
<rect key="frame" x="20" y="12" width="33.5" height="20.5"/>
|
||||
<rect key="frame" x="16" y="12" width="33.5" height="20.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<nil key="highlightedColor"/>
|
||||
</label>
|
||||
<label opaque="NO" multipleTouchEnabled="YES" contentMode="left" text="Detail" textAlignment="right" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontForContentSizeCategory="YES" adjustsFontSizeToFit="NO" id="NNc-J4-xiE">
|
||||
<rect key="frame" x="331" y="12" width="44" height="20.5"/>
|
||||
<rect key="frame" x="296" y="12" width="44" height="20.5"/>
|
||||
<autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
|
||||
<fontDescription key="fontDescription" style="UICTFontTextStyleBody"/>
|
||||
<color key="textColor" systemColor="secondaryLabelColor" red="0.23529411759999999" green="0.23529411759999999" blue="0.26274509800000001" alpha="0.59999999999999998" colorSpace="custom" customColorSpace="sRGB"/>
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
import GRDB
|
||||
|
||||
/// The Player struct
|
||||
// A plain Player struct
|
||||
struct Player {
|
||||
var id: Int64? // Use Int64 for auto-incremented database ids
|
||||
// Prefer Int64 for auto-incremented database ids
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
/// Hashable conformance supports tableView diffing
|
||||
// Hashable conformance supports tableView diffing
|
||||
extension Player: Hashable { }
|
||||
|
||||
// MARK: - Persistence
|
||||
|
||||
/// Make Player a Codable Record.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
|
||||
// Turn Player into a Codable Record.
|
||||
// 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 {
|
||||
private enum Columns {
|
||||
static let id = Column(CodingKeys.id)
|
||||
static let name = Column(CodingKeys.name)
|
||||
static let score = Column(CodingKeys.score)
|
||||
@@ -29,33 +29,17 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Player Requests
|
||||
// MARK: - Database access
|
||||
|
||||
/// 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
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// A request of players ordered by name
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// try Player.all().orderedByName().fetchAll(db)
|
||||
/// }
|
||||
func orderedByName() -> Self {
|
||||
order(Player.Columns.name)
|
||||
// Define some useful player requests.
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
|
||||
extension Player {
|
||||
static func orderedByName() -> QueryInterfaceRequest<Player> {
|
||||
Player.order(Columns.name)
|
||||
}
|
||||
|
||||
/// A request of players ordered by score
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// try Player.all().orderedByScore().fetchAll(db)
|
||||
/// }
|
||||
func orderedByScore() -> Self {
|
||||
order(Player.Columns.score.desc, Player.Columns.name)
|
||||
static func orderedByScore() -> QueryInterfaceRequest<Player> {
|
||||
Player.order(Columns.score.desc, Columns.name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,44 +2,55 @@ import UIKit
|
||||
|
||||
class PlayerEditionViewController: UITableViewController {
|
||||
enum Presentation {
|
||||
/// Modal presentation: edition ends with the "Commit" unwind segue.
|
||||
/// Modal presentation: edition ends with the "Commit" segue.
|
||||
case modal
|
||||
|
||||
/// Push presentation: edition ends when user hits the back button.
|
||||
case push
|
||||
}
|
||||
|
||||
/// The edited player
|
||||
var player: Player! {
|
||||
didSet {
|
||||
configureForm()
|
||||
}
|
||||
}
|
||||
|
||||
/// The presentation mode
|
||||
var presentation: Presentation! {
|
||||
didSet {
|
||||
configureNavigationItem()
|
||||
}
|
||||
}
|
||||
|
||||
@IBOutlet private weak var cancelBarButtonItem: UIBarButtonItem!
|
||||
@IBOutlet private weak var commitBarButtonItem: UIBarButtonItem!
|
||||
@IBOutlet private weak var nameCell: UITableViewCell!
|
||||
@IBOutlet private weak var nameTextField: UITextField!
|
||||
@IBOutlet private weak var scoreCell: UITableViewCell!
|
||||
@IBOutlet private weak var scoreTextField: UITextField!
|
||||
var player: Player! { didSet { configureView() } }
|
||||
var presentation: Presentation! { didSet { configureView() } }
|
||||
|
||||
@IBOutlet fileprivate weak var cancelBarButtonItem: UIBarButtonItem!
|
||||
@IBOutlet fileprivate weak var commitBarButtonItem: UIBarButtonItem!
|
||||
@IBOutlet fileprivate weak var nameCell: UITableViewCell!
|
||||
@IBOutlet fileprivate weak var nameTextField: UITextField!
|
||||
@IBOutlet fileprivate weak var scoreCell: UITableViewCell!
|
||||
@IBOutlet fileprivate weak var scoreTextField: UITextField!
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
configureForm()
|
||||
configureNavigationItem()
|
||||
configureView()
|
||||
}
|
||||
|
||||
fileprivate func configureView() {
|
||||
guard isViewLoaded else { return }
|
||||
|
||||
nameTextField.text = player.name
|
||||
|
||||
if player.score == 0 && player.id == nil {
|
||||
scoreTextField.text = ""
|
||||
} else {
|
||||
scoreTextField.text = "\(player.score)"
|
||||
}
|
||||
|
||||
switch presentation! {
|
||||
case .modal:
|
||||
navigationItem.leftBarButtonItem = cancelBarButtonItem
|
||||
navigationItem.rightBarButtonItem = commitBarButtonItem
|
||||
case .push:
|
||||
navigationItem.leftBarButtonItem = nil
|
||||
navigationItem.rightBarButtonItem = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PlayerEditionViewController {
|
||||
|
||||
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
|
||||
// Force keyboard to dismiss early
|
||||
view.endEditing(true)
|
||||
@@ -55,31 +66,24 @@ extension PlayerEditionViewController {
|
||||
override func willMove(toParent parent: UIViewController?) {
|
||||
super.willMove(toParent: parent)
|
||||
|
||||
if case .push = presentation, parent == nil {
|
||||
// Self is popping from its navigation controller
|
||||
saveChanges()
|
||||
}
|
||||
}
|
||||
|
||||
private func configureNavigationItem() {
|
||||
guard isViewLoaded else { return }
|
||||
|
||||
if let presentation = presentation {
|
||||
switch presentation {
|
||||
case .modal:
|
||||
navigationItem.leftBarButtonItem = cancelBarButtonItem
|
||||
navigationItem.rightBarButtonItem = commitBarButtonItem
|
||||
case .push:
|
||||
navigationItem.leftBarButtonItem = nil
|
||||
navigationItem.rightBarButtonItem = nil
|
||||
switch presentation! {
|
||||
case .modal:
|
||||
break
|
||||
case .push:
|
||||
if parent == nil {
|
||||
// Self is popping from its navigation controller
|
||||
saveChanges()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Form
|
||||
|
||||
extension PlayerEditionViewController: UITextFieldDelegate {
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
nameTextField.becomeFirstResponder()
|
||||
@@ -102,32 +106,16 @@ extension PlayerEditionViewController: UITextFieldDelegate {
|
||||
return false
|
||||
}
|
||||
|
||||
@IBAction func textFieldDidChange(_ textField: UITextField) {
|
||||
// User has edited the player: prevent interactive dismissal
|
||||
if case .modal = presentation {
|
||||
isModalInPresentation = true
|
||||
}
|
||||
}
|
||||
|
||||
private func configureForm() {
|
||||
guard isViewLoaded else { return }
|
||||
|
||||
nameTextField.text = player.name
|
||||
|
||||
if player.score == 0 && player.id == nil {
|
||||
scoreTextField.text = ""
|
||||
} else {
|
||||
scoreTextField.text = "\(player.score)"
|
||||
}
|
||||
}
|
||||
|
||||
private func saveChanges() {
|
||||
guard var player = self.player else {
|
||||
return
|
||||
}
|
||||
player.name = nameTextField.text ?? ""
|
||||
player.score = scoreTextField.text.flatMap { Int($0) } ?? 0
|
||||
try! appDatabase.savePlayer(&player)
|
||||
self.player = player
|
||||
|
||||
try! dbQueue.inDatabase { db in
|
||||
try player.save(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
/// PlayerListViewController displays the list of players.
|
||||
class PlayerListViewController: UITableViewController {
|
||||
private enum PlayerOrdering {
|
||||
case byName
|
||||
case byScore
|
||||
}
|
||||
|
||||
@IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem!
|
||||
private var animatesPlayersChange = false // Don't animate first update
|
||||
private var players: [Player] = []
|
||||
private var playersCancellable: DatabaseCancellable?
|
||||
private var playerCountCancellable: DatabaseCancellable?
|
||||
private var playerOrdering: PlayerOrdering = .byScore {
|
||||
didSet {
|
||||
configureOrderingBarButtonItem()
|
||||
configureTableView()
|
||||
}
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
configureToolbar()
|
||||
configureNavigationItem()
|
||||
configureTableView()
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
navigationController?.isToolbarHidden = false
|
||||
}
|
||||
|
||||
private func configureToolbar() {
|
||||
toolbarItems = [
|
||||
UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)),
|
||||
UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil),
|
||||
UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)),
|
||||
]
|
||||
}
|
||||
|
||||
private func configureNavigationItem() {
|
||||
navigationItem.backBarButtonItem = UIBarButtonItem(
|
||||
title: "Players", style: .plain,
|
||||
target: nil, action: nil)
|
||||
navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem]
|
||||
configureOrderingBarButtonItem()
|
||||
configureTitle()
|
||||
}
|
||||
|
||||
private func configureOrderingBarButtonItem() {
|
||||
switch playerOrdering {
|
||||
case .byScore:
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
title: "Score ▼",
|
||||
style: .plain,
|
||||
target: self, action: #selector(sortByName))
|
||||
case .byName:
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(
|
||||
title: "Name ▲",
|
||||
style: .plain,
|
||||
target: self, action: #selector(sortByScore))
|
||||
}
|
||||
}
|
||||
|
||||
private func configureTitle() {
|
||||
playerCountCancellable = appDatabase.observePlayerCount(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] count in
|
||||
guard let self = self else { return }
|
||||
switch count {
|
||||
case 0: self.navigationItem.title = "No Player"
|
||||
case 1: self.navigationItem.title = "1 Player"
|
||||
default: self.navigationItem.title = "\(count) Players"
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private func configureTableView() {
|
||||
switch playerOrdering {
|
||||
case .byName:
|
||||
playersCancellable = appDatabase.observePlayersOrderedByName(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.updateTableView(with: players)
|
||||
})
|
||||
case .byScore:
|
||||
playersCancellable = appDatabase.observePlayersOrderedByScore(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.updateTableView(with: players)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
private func updateTableView(with players: [Player]) {
|
||||
if animatesPlayersChange == false {
|
||||
self.players = players
|
||||
tableView.reloadData()
|
||||
|
||||
// Future updates will be animated
|
||||
animatesPlayersChange = true
|
||||
return
|
||||
}
|
||||
|
||||
// Compute difference between current and new list of players
|
||||
let difference = players
|
||||
.difference(from: self.players)
|
||||
.inferringMoves()
|
||||
|
||||
// Apply those changes to the table view
|
||||
tableView.performBatchUpdates({
|
||||
self.players = players
|
||||
for change in difference {
|
||||
switch change {
|
||||
case let .remove(offset, _, associatedWith):
|
||||
if let associatedWith = associatedWith {
|
||||
self.tableView.moveRow(
|
||||
at: IndexPath(row: offset, section: 0),
|
||||
to: IndexPath(row: associatedWith, section: 0))
|
||||
} else {
|
||||
self.tableView.deleteRows(
|
||||
at: [IndexPath(row: offset, section: 0)],
|
||||
with: .fade)
|
||||
}
|
||||
case let .insert(offset, _, associatedWith):
|
||||
if associatedWith == nil {
|
||||
self.tableView.insertRows(
|
||||
at: [IndexPath(row: offset, section: 0)],
|
||||
with: .fade)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, completion: nil)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PlayerListViewController {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "Edit" {
|
||||
guard
|
||||
let controller = segue.destination as? PlayerEditionViewController,
|
||||
let indexPath = tableView.indexPathForSelectedRow
|
||||
else { return }
|
||||
let player = players[indexPath.row]
|
||||
controller.title = player.name
|
||||
controller.player = player
|
||||
controller.presentation = .push
|
||||
}
|
||||
else if segue.identifier == "New" {
|
||||
guard
|
||||
let navigationController = segue.destination as? UINavigationController,
|
||||
let controller = navigationController.viewControllers.first as? PlayerEditionViewController
|
||||
else { return }
|
||||
setEditing(false, animated: true)
|
||||
controller.title = "New Player"
|
||||
controller.player = Player(id: nil, name: "", score: 0)
|
||||
controller.presentation = .modal
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) {
|
||||
// Player creation cancelled
|
||||
}
|
||||
|
||||
@IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) {
|
||||
// Player creation committed
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - UITableViewDataSource
|
||||
|
||||
extension PlayerListViewController {
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
players.count
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath)
|
||||
configure(cell, at: indexPath)
|
||||
return cell
|
||||
}
|
||||
|
||||
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
|
||||
// Delete the player
|
||||
let player = players[indexPath.row]
|
||||
try! appDatabase.deletePlayer(player)
|
||||
}
|
||||
|
||||
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
|
||||
let player = players[indexPath.row]
|
||||
if player.name.isEmpty {
|
||||
cell.textLabel?.text = "(anonymous)"
|
||||
} else {
|
||||
cell.textLabel?.text = player.name
|
||||
}
|
||||
cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
extension PlayerListViewController {
|
||||
@IBAction func sortByName() {
|
||||
setEditing(false, animated: true)
|
||||
playerOrdering = .byName
|
||||
}
|
||||
|
||||
@IBAction func sortByScore() {
|
||||
setEditing(false, animated: true)
|
||||
playerOrdering = .byScore
|
||||
}
|
||||
|
||||
@IBAction func deletePlayers() {
|
||||
setEditing(false, animated: true)
|
||||
try! appDatabase.deleteAllPlayers()
|
||||
}
|
||||
|
||||
@IBAction func refresh() {
|
||||
setEditing(false, animated: true)
|
||||
try! appDatabase.refreshPlayers()
|
||||
}
|
||||
|
||||
@IBAction func stressTest() {
|
||||
setEditing(false, animated: true)
|
||||
for _ in 0..<50 {
|
||||
DispatchQueue.global().async {
|
||||
try! appDatabase.refreshPlayers()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import UIKit
|
||||
import GRDB
|
||||
|
||||
/// PlayerListViewController displays the list of players.
|
||||
class PlayerListViewController: UITableViewController {
|
||||
/// PlayersViewController displays the list of players.
|
||||
class PlayersViewController: UITableViewController {
|
||||
private enum PlayerOrdering {
|
||||
case byName
|
||||
case byScore
|
||||
@@ -18,6 +18,14 @@ class PlayerListViewController: UITableViewController {
|
||||
configureTableView()
|
||||
}
|
||||
}
|
||||
private var playersRequest: QueryInterfaceRequest<Player> {
|
||||
switch playerOrdering {
|
||||
case .byName:
|
||||
return Player.orderedByName()
|
||||
case .byScore:
|
||||
return Player.orderedByScore()
|
||||
}
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
@@ -63,7 +71,13 @@ class PlayerListViewController: UITableViewController {
|
||||
}
|
||||
|
||||
private func configureTitle() {
|
||||
playerCountCancellable = appDatabase.observePlayerCount(
|
||||
// Track changes in the number of players
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
playerCountCancellable = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .immediate,
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] count in
|
||||
guard let self = self else { return }
|
||||
@@ -76,22 +90,19 @@ class PlayerListViewController: UITableViewController {
|
||||
}
|
||||
|
||||
private func configureTableView() {
|
||||
switch playerOrdering {
|
||||
case .byName:
|
||||
playersCancellable = appDatabase.observePlayersOrderedByName(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.updateTableView(players)
|
||||
})
|
||||
case .byScore:
|
||||
playersCancellable = appDatabase.observePlayersOrderedByScore(
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.updateTableView(players)
|
||||
})
|
||||
// Track changes in the list of players
|
||||
let request = self.playersRequest
|
||||
let observation = ValueObservation.tracking { db in
|
||||
try request.fetchAll(db)
|
||||
}
|
||||
playersCancellable = observation.start(
|
||||
in: dbQueue,
|
||||
scheduling: .immediate,
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
self.updateTableView(players)
|
||||
})
|
||||
}
|
||||
|
||||
private func updateTableView(_ players: [Player]) {
|
||||
@@ -130,7 +141,7 @@ class PlayerListViewController: UITableViewController {
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
extension PlayerListViewController {
|
||||
extension PlayersViewController {
|
||||
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if segue.identifier == "Edit" {
|
||||
@@ -162,7 +173,7 @@ extension PlayerListViewController {
|
||||
|
||||
// MARK: - UITableViewDataSource
|
||||
|
||||
extension PlayerListViewController {
|
||||
extension PlayersViewController {
|
||||
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
players.count
|
||||
}
|
||||
@@ -176,7 +187,9 @@ extension PlayerListViewController {
|
||||
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
|
||||
// Delete the player
|
||||
let player = players[indexPath.row]
|
||||
try! appDatabase.deletePlayer(player)
|
||||
try! dbQueue.write { db in
|
||||
_ = try player.delete(db)
|
||||
}
|
||||
}
|
||||
|
||||
private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) {
|
||||
@@ -193,7 +206,7 @@ extension PlayerListViewController {
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
extension PlayerListViewController {
|
||||
extension PlayersViewController {
|
||||
@IBAction func sortByName() {
|
||||
setEditing(false, animated: true)
|
||||
playerOrdering = .byName
|
||||
@@ -206,19 +219,48 @@ extension PlayerListViewController {
|
||||
|
||||
@IBAction func deletePlayers() {
|
||||
setEditing(false, animated: true)
|
||||
try! appDatabase.deleteAllPlayers()
|
||||
try! dbQueue.write { db in
|
||||
_ = try Player.deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
@IBAction func refresh() {
|
||||
setEditing(false, animated: true)
|
||||
try! appDatabase.refreshPlayers()
|
||||
refreshPlayers()
|
||||
}
|
||||
|
||||
@IBAction func stressTest() {
|
||||
setEditing(false, animated: true)
|
||||
for _ in 0..<50 {
|
||||
DispatchQueue.global().async {
|
||||
try! appDatabase.refreshPlayers()
|
||||
self.refreshPlayers()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func refreshPlayers() {
|
||||
try! dbQueue.write { db in
|
||||
if try Player.fetchCount(db) == 0 {
|
||||
// Insert new random players
|
||||
for _ in 0..<8 {
|
||||
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
|
||||
try player.insert(db)
|
||||
}
|
||||
} else {
|
||||
// Insert a player
|
||||
if Bool.random() {
|
||||
var player = Player(id: nil, name: Player.randomName(), score: Player.randomScore())
|
||||
try player.insert(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() {
|
||||
player.score = Player.randomScore()
|
||||
try player.update(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,28 +5,27 @@ Demo Application
|
||||
|
||||
**This demo application shows you:**
|
||||
|
||||
- How to setup a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a table view with [ValueObservation](../../../README.md#valueobservation).
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- how to setup a database in an iOS app
|
||||
- how to define a simple [Codable Record](../../README.md#codable-records)
|
||||
- how to track database changes and animate a table view with [ValueObservation](../../README.md#valueobservation).
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
- [AppDelegate.swift](GRDBDemoiOS/AppDelegate.swift)
|
||||
|
||||
`AppDelegate` creates, on application startup, a unique instance of [DatabaseQueue](../../../README.md#database-queues) available for the whole application.
|
||||
`AppDelegate` creates, on application startup, a unique instance of [DatabaseQueue](../../README.md#database-queues) available for the whole application.
|
||||
|
||||
- [AppDatabase.swift](GRDBDemoiOS/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` grants database access for the whole application. It uses [DatabaseMigrator](../../Migrations.md) in order to setup the database schema, and [ValueObservation](../../../README.md#valueobservation) in order to let the application observe database changes.
|
||||
`AppDatabase` defines the database for the whole application. It uses [DatabaseMigrator](../../README.md#migrations) in order to setup the database schema.
|
||||
|
||||
- [Player.swift](GRDBDemoiOS/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). It defines the database requests used by the application.
|
||||
`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).
|
||||
|
||||
- [PlayerListViewController.swift](GRDBDemoiOS/PlayerListViewController.swift)
|
||||
- [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift)
|
||||
|
||||
`PlayerListViewController` displays the list of players.
|
||||
`PlayersViewController` displays a list of players. It keeps its view up-to-date with [ValueObservation](../../README.md#valueobservation).
|
||||
|
||||
- [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift)
|
||||
|
||||
|
||||
@@ -371,7 +371,7 @@ final class LatinAsciiTokenizer : FTS5WrapperTokenizer {
|
||||
}
|
||||
```
|
||||
|
||||
> :point_up: **Note**: String.applyingTransform is not available before macOS 10.11. Use the Core Foundation function [CFStringTransform](https://developer.apple.com/reference/corefoundation/1542411-cfstringtransform) instead.
|
||||
> :point_up: **Note**: String.applyingTransform is not available before iOS 9.0 and macOS 10.11. Use the Core Foundation function [CFStringTransform](https://developer.apple.com/reference/corefoundation/1542411-cfstringtransform) instead.
|
||||
|
||||
Remember to register LatinAsciiTokenizer before using it:
|
||||
|
||||
|
||||
@@ -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.0.0-beta.5/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/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.0.0-beta.5/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
|
||||
@@ -24,7 +24,7 @@ GRDB requirements have been bumped:
|
||||
|
||||
- **Swift 5.2+** (was Swift 4.2+)
|
||||
- **Xcode 11.4+** (was Xcode 10.0+)
|
||||
- **iOS 10.0+** (was iOS 9.0+)
|
||||
- iOS 9.0+ (unchanged)
|
||||
- **macOS 10.10+** (was macOS 10.9+)
|
||||
- tvOS 9.0+ (unchanged)
|
||||
- watchOS 2.0+ (unchanged)
|
||||
@@ -193,10 +193,9 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
```swift
|
||||
let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
let cancellable = observation
|
||||
.publisher(
|
||||
in: dbQueue,
|
||||
// Opt in for immediate notification of the initial value
|
||||
scheduling: .immediate)
|
||||
.publisher(in: dbQueue)
|
||||
// Opt in for immediate notification of the initial value
|
||||
.scheduling(.immediate)
|
||||
.sink(...)
|
||||
```
|
||||
|
||||
@@ -208,10 +207,9 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
```swift
|
||||
let observation = ValueObservation.tracking(Player.fetchAll)
|
||||
let disposable = observation
|
||||
.rx.observe(
|
||||
in: dbQueue,
|
||||
// Opt in for immediate notification of the initial value
|
||||
scheduling: .immediate)
|
||||
.rx.observe(in: dbQueue)
|
||||
// Opt in for immediate notification of the initial value
|
||||
.scheduling(.immediate)
|
||||
.subscribe(...)
|
||||
```
|
||||
|
||||
@@ -295,23 +293,7 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
|
||||
## Other Changes
|
||||
|
||||
1. The `Configuration.trace` property has been removed. You know use the `Database.trace(options:_:)` method instead:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
var config = Configuration()
|
||||
config.trace = { print($0) }
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
|
||||
// NEW: GRDB 5
|
||||
var config = Configuration()
|
||||
config.prepareDatabase = { db in
|
||||
db.trace { print($0) }
|
||||
}
|
||||
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
|
||||
```
|
||||
|
||||
2. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
|
||||
1. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -320,72 +302,8 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
// NEW: GRDB 5
|
||||
try Player.updateAll(db, Column("score").set(to: 0))
|
||||
```
|
||||
|
||||
> :question: This change avoids conflicts with other libraries that define the same operator.
|
||||
|
||||
3. [SQL Interpolation] does no longer wrap subqueries in parenthesis:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
let maximumScore: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
let bestPlayers: SQLRequest<Player> = "SELECT * FROM player WHERE score = \(maximumScore)"
|
||||
|
||||
// NEW: GRDB 5
|
||||
let maximumScore: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
let bestPlayers: SQLRequest<Player> = "SELECT * FROM player WHERE score = (\(maximumScore))"
|
||||
// extra parenthesis required: ^ ^
|
||||
```
|
||||
|
||||
> :question: This change makes it possible to concatenate subqueries with the UNION operator.
|
||||
|
||||
4. In order to extract raw SQL string from an [SQLLiteral], you now need a database connection:
|
||||
|
||||
```swift
|
||||
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 (sql, arguments) = try dbQueue.read(query.build)
|
||||
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(arguments) // prints ["O'Brien", 42]
|
||||
```
|
||||
|
||||
5. In order to extract raw SQL string from a request ([SQLRequest] or [QueryInterfaceRequest]), you now need to call the `makePreparedRequest()` method:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
try dbQueue.read { db in
|
||||
let request = Player.filter(Column("name") == "O'Brien")
|
||||
let sqlRequest = try SQLRequest(db, request: request)
|
||||
print(sqlRequest.sql) // "SELECT * FROM player WHERE name = ?"
|
||||
print(sqlRequest.arguments) // ["O'Brien"]
|
||||
}
|
||||
|
||||
// NEW: GRDB 5
|
||||
try dbQueue.read { db in
|
||||
let request = Player.filter(Column("name") == "O'Brien")
|
||||
let statement = try request.makePreparedRequest(db, forSingleResult: false).statement
|
||||
print(statement.sql) // "SELECT * FROM player WHERE name = ?"
|
||||
print(statement.arguments) // ["O'Brien"]
|
||||
}
|
||||
```
|
||||
|
||||
6. The `TableRecord.selectionSQL()` method is no longer avaible. When you need to embed the columns selected by a record type in an SQL request, you now have to use [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
let sql = "SELECT \(Player.selectionSQL()) FROM player"
|
||||
let players = try Player.fetchAll(db, sql: sql)
|
||||
|
||||
// NEW: GRDB 5
|
||||
let request: SQLRequest<Player> = "SELECT \(columnsOf: Player.self) FROM player"
|
||||
let players = try request.fetchAll(db)
|
||||
```
|
||||
|
||||
7. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
|
||||
2. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -395,13 +313,29 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
Player.select(myFunction(Column("name")))
|
||||
```
|
||||
|
||||
8. Defining custom `FetchRequest` types is now **discouraged**.
|
||||
3. If you happen to implement custom fetch requests with the `FetchRequest` protocol, you now have to define the `makePreparedRequest(_:forSingleResult:)` method:
|
||||
|
||||
A future GRDB version will remove the ability to define custom `FetchRequest` types.
|
||||
|
||||
Our suggestion is to refactor your app so that your custom request type is no longer needed: [SQLRequest] and [QueryInterfaceRequest] are now supposed to fully address your needs. If it is not possible, then please [open an issue](https://github.com/groue/GRDB.swift/issues) and describe your particular use case.
|
||||
|
||||
9. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
struct MyRequest: FetchRequest {
|
||||
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?) {
|
||||
let statement: SelectStatement = ...
|
||||
let adapter: RowAdapter? = ...
|
||||
return (statement, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
// NEW: GRDB 5
|
||||
struct MyRequest: FetchRequest {
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
let statement: SelectStatement = ...
|
||||
let adapter: RowAdapter? = ...
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
4. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -411,7 +345,7 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
import GRDB
|
||||
```
|
||||
|
||||
10. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library:
|
||||
5. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer to import the underlying SQLite library:
|
||||
|
||||
```swift
|
||||
// BEFORE: GRDB 4
|
||||
@@ -426,6 +360,7 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
```
|
||||
|
||||
|
||||
|
||||
[ValueObservation]: ../README.md#valueobservation
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB
|
||||
@@ -434,7 +369,3 @@ The changes can quite impact your application. We'll describe them below, as wel
|
||||
[removeDuplicates]: ../README.md#valueobservationremoveduplicates
|
||||
[Custom SQL functions]: ../README.md#custom-sql-functions
|
||||
[Batch updates]: ../README.md#update-requests
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
[SQLLiteral]: SQLInterpolation.md#sqlliteral
|
||||
[SQLRequest]: ../README.md#custom-requests
|
||||
[QueryInterfaceRequest]: ../README.md#requests
|
||||
@@ -701,8 +701,8 @@ Instead, have a look at [Database Observation]:
|
||||
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
|
||||
[Why Adopt GRDB?]: WhyAdoptGRDB.md
|
||||
[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
|
||||
[migrations]: Migrations.md
|
||||
[migration]: Migrations.md
|
||||
[migrations]: ../README.md#migrations
|
||||
[migration]: ../README.md#migrations
|
||||
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
|
||||
[Concurrency Guide]: ../README.md#concurrency
|
||||
[GRDB concurrency rules]: ../README.md#concurrency
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
# Migrations
|
||||
|
||||
**Migrations** are a convenient way to alter your database schema over time in a consistent and easy way.
|
||||
|
||||
Migrations run in order, once and only once. When a user upgrades your application, only non-applied migrations are run.
|
||||
|
||||
Inside each migration, you typically [define and update your database tables](../README.md#database-schema) according to your evolving application needs:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
// 1st migration
|
||||
migrator.registerMigration("v1") { db in
|
||||
try db.create(table: "author") { t in ... }
|
||||
try db.create(table: "book") { t in ... }
|
||||
try db.create(index: ...)
|
||||
}
|
||||
|
||||
// 2nd migration
|
||||
migrator.registerMigration("v2") { db in
|
||||
try db.alter(table: "author") { t in ... }
|
||||
}
|
||||
|
||||
// Migrations for future versions will be inserted here:
|
||||
//
|
||||
// // 3rd migration
|
||||
// migrator.registerMigration("...") { db in
|
||||
// ...
|
||||
// }
|
||||
```
|
||||
|
||||
**Each migration runs in a separate transaction.** Should one throw an error, its transaction is rollbacked, subsequent migrations do not run, and the error is eventually thrown by `migrator.migrate(dbQueue)`.
|
||||
|
||||
**Migrations run with deferred foreign key checks.** This means that eventual foreign key violations are only checked at the end of the migration (and they make the migration fail).
|
||||
|
||||
**The memory of applied migrations is stored in the database itself** (in a reserved table).
|
||||
|
||||
You migrate the database up to the latest version with the `migrate(_:)` method:
|
||||
|
||||
```swift
|
||||
try migrator.migrate(dbQueue) // or migrator.migrate(dbPool)
|
||||
```
|
||||
|
||||
Migrate a database up to a specific version (useful for testing):
|
||||
|
||||
```swift
|
||||
try migrator.migrate(dbQueue, upTo: "v2")
|
||||
|
||||
// Migrations can only run forward:
|
||||
try migrator.migrate(dbQueue, upTo: "v2")
|
||||
try migrator.migrate(dbQueue, upTo: "v1")
|
||||
// ^ fatal error: database is already migrated beyond migration "v1"
|
||||
```
|
||||
|
||||
When several versions of your app are deployed in the wild, you may want to perform extra checks:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
// Readonly apps may want to check if database lacks expected migrations:
|
||||
if try migrator.hasCompletedMigrations(db) == false {
|
||||
// database too old
|
||||
}
|
||||
|
||||
// All apps may want to check if database contains unknown (future) migrations:
|
||||
if try migrator.hasBeenSuperseded(db) {
|
||||
// database too new
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
|
||||
A DatabaseMigrator can automatically wipe out the full database content, and recreate the whole database from scratch, if it detects that migrations have changed their definition:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
```
|
||||
|
||||
> :warning: **Warning**: This option can destroy your precious users' data!
|
||||
|
||||
Setting `eraseDatabaseOnSchemaChange` is useful during application development, as you are still designing migrations, and the schema changes often.
|
||||
|
||||
It is recommended that this option does not ship in the released application:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
```
|
||||
|
||||
The `eraseDatabaseOnSchemaChange` option triggers a recreation of the database if and only if:
|
||||
|
||||
- A migration has been removed, or renamed.
|
||||
- A *schema change* is detected. A schema change is any difference in the `sqlite_master` table, which contains the SQL used to create database tables, indexes, triggers, and views.
|
||||
|
||||
|
||||
## Advanced Database Schema Changes
|
||||
|
||||
SQLite does not support many schema changes, and won't let you drop a table column with "ALTER TABLE ... DROP COLUMN ...", for example.
|
||||
|
||||
Yet any kind of schema change is still possible, by recreating tables:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("AddNotNullCheckOnName") { db in
|
||||
// Add a NOT NULL constraint on player.name:
|
||||
try db.create(table: "new_player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
try db.execute(sql: "INSERT INTO new_player SELECT * FROM player")
|
||||
try db.drop(table: "player")
|
||||
try db.rename(table: "new_player", to: "player")
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -17,8 +17,6 @@ To release a new GRDB version:
|
||||
- CHANGELOG.md
|
||||
- GRDB.swift.podspec
|
||||
- README.md
|
||||
- Documentation/FullTextSearch.md
|
||||
- Documentation/Migrations.md
|
||||
- Support/Info.plist
|
||||
- Commit and tag
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
|
||||
@@ -6,17 +6,16 @@ Your SQL skills are [welcomed] throughout GRDB. Yet writing raw SQL presents com
|
||||
The query below exemplifies this situation. It even contains a bug that is not quite easy to spot:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
try db.execute(
|
||||
sql: """
|
||||
UPDATE student
|
||||
SET firstName = ?, lastName = ?, department = ?, birthDate = ?,
|
||||
registrationDate = ?, mainTeacherId = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
arguments: [firstName, lastName, department, birthDate,
|
||||
registrationDate, mainTeacherId])
|
||||
}
|
||||
try db.execute(
|
||||
sql: """
|
||||
UPDATE student
|
||||
SET firstName = ?, lastName = ?, department = ?, birthDate = ?,
|
||||
registrationDate = ?, mainTeacherId = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
arguments: [firstName, lastName, department, birthDate,
|
||||
registrationDate, mainTeacherId])
|
||||
|
||||
```
|
||||
|
||||
SQL Interpolation is an answer to these troubles. It is available in Swift 5.
|
||||
@@ -35,9 +34,7 @@ SQL Interpolation is an answer to these troubles. It is available in Swift 5.
|
||||
```swift
|
||||
let name: String = ...
|
||||
let id: Int64 = ...
|
||||
try dbQueue.write { db in
|
||||
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
|
||||
}
|
||||
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
|
||||
```
|
||||
|
||||
SQL interpolation looks and feel just like regular [String interpolation]:
|
||||
@@ -50,12 +47,16 @@ print("Hello \(name)!") // prints "Hello World!"
|
||||
The difference is that it generates valid SQL which does not suffer from syntax errors or [SQL injection]. For example, you do not need to validate input or process single quotes:
|
||||
|
||||
```swift
|
||||
// Executes `UPDATE player SET name = 'O''Brien' WHERE id = 42`
|
||||
let name = "O'Brien"
|
||||
let id = 42
|
||||
try dbQueue.write { db in
|
||||
// Executes `UPDATE player SET name = 'O''Brien' WHERE id = 42`
|
||||
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
|
||||
}
|
||||
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
|
||||
```
|
||||
|
||||
Under the hood, SQL interpolation generates a plain SQL string. It runs exactly as below:
|
||||
|
||||
```swift
|
||||
try db.execute(sql: "UPDATE player SET name = ? WHERE id = ?", arguments: [name, id])
|
||||
```
|
||||
|
||||
Plain SQL strings are indeed still available, and SQL interpolation only kicks in when you ask for it. There is a simple rule to remember:
|
||||
@@ -78,21 +79,17 @@ Plain SQL strings are indeed still available, and SQL interpolation only kicks i
|
||||
**SQLLiteral** is the type that looks like a plain String, but profits from SQL interpolation:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
try db.execute(literal: query)
|
||||
}
|
||||
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
try db.execute(literal: query)
|
||||
```
|
||||
|
||||
**SQLLiteral is not a Swift String.** You can not use the `execute(literal:)` method with a String argument:
|
||||
|
||||
```swift
|
||||
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 'SQLLiteral'
|
||||
try db.execute(literal: query)
|
||||
}
|
||||
// Compiler error:
|
||||
// Cannot convert value of type 'String' to expected argument type 'SQLLiteral'
|
||||
let query = "UPDATE player SET name = \(name) WHERE id = \(id)" // a String
|
||||
try db.execute(literal: query)
|
||||
```
|
||||
|
||||
SQLLiteral can build your queries step by step, with regular operators and methods:
|
||||
@@ -116,9 +113,8 @@ Extract the plain SQL string from a literal:
|
||||
|
||||
```swift
|
||||
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]
|
||||
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
|
||||
print(query.arguments) // prints ["O'Brien", 42]
|
||||
```
|
||||
|
||||
Build a literal from a plain SQL string:
|
||||
@@ -171,7 +167,7 @@ The [record protocols] extend your application types with database abilities.
|
||||
|
||||
**A record type knows everything about the schema of its underlying database table**. With the [TableRecord] protocol, the `databaseTableName` property contains the table name. With the [Decodable] protocol, the [CodingKeys] enum contain the column names. And with [FetchableRecord], you can decode raw database rows.
|
||||
|
||||
SQL Interpolation puts this knowledge to good use, so that you can build robust queries that consistently use correct table and column names. Let's start from this record:
|
||||
SQL Interpolation puts this knowledge to good use, so that you can build robust queries that consistently use correct table and column names:
|
||||
|
||||
```swift
|
||||
struct Player {
|
||||
@@ -180,15 +176,51 @@ struct Player {
|
||||
var score: Int?
|
||||
}
|
||||
|
||||
extension Player: Decodable, TableRecord, FetchableRecord { }
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// Deletes all player with no score
|
||||
static func deleteAllWithoutScore(_ db: Database) throws {
|
||||
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
|
||||
}
|
||||
|
||||
/// The player with a given id
|
||||
static func filter(id: Int64) -> SQLRequest<Player> {
|
||||
"SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
|
||||
}
|
||||
|
||||
/// All players with the given ids
|
||||
static func filter(ids: [Int64]) -> SQLRequest<Player> {
|
||||
"SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
|
||||
}
|
||||
|
||||
/// The maximum score
|
||||
static func maximumScore() -> SQLRequest<Int> {
|
||||
"SELECT MAX(\(CodingKeys.score)) FROM \(self)"
|
||||
}
|
||||
|
||||
/// All players whose score is the maximum score
|
||||
static func leaders() -> SQLRequest<Player> {
|
||||
"""
|
||||
SELECT * FROM \(self)
|
||||
WHERE \(CodingKeys.score) = \(maximumScore())
|
||||
"""
|
||||
}
|
||||
|
||||
/// A complex request
|
||||
static func complexRequest() -> SQLRequest<Player> {
|
||||
let query: SQLLiteral = "SELECT * FROM \(self) "
|
||||
query += "JOIN \(Team.self) ON ..."
|
||||
query += "GROUP BY ..."
|
||||
return SQLRequest(literal: query)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Let's extend Player with database methods.
|
||||
Let's breakdown each one of those methods.
|
||||
|
||||
- `Player.deleteAllWithoutScore(_:)`
|
||||
- `deleteAllWithoutScore(_:)`
|
||||
|
||||
```swift
|
||||
extension Player {
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// Deletes all player with no score
|
||||
static func deleteAllWithoutScore(_ db: Database) throws {
|
||||
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
|
||||
@@ -209,22 +241,13 @@ Let's extend Player with database methods.
|
||||
|
||||
`... \(CodingKeys.score) IS NULL` embeds CodingKeys.score. This one has been synthesized by the Swift compiler because Player adopts the Decodable protocol. It embeds the column name in the SQL query.
|
||||
|
||||
- `Player.filter(id:)`
|
||||
|
||||
- `filter(id:)`
|
||||
|
||||
```swift
|
||||
extension Player {
|
||||
/// "Simple" version
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// The player with a given id
|
||||
static func filter(id: Int64) -> SQLRequest<Player> {
|
||||
"SELECT * FROM player WHERE id = \(id)"
|
||||
}
|
||||
|
||||
/// "Future-proof" version
|
||||
static func filter(id: Int64) -> SQLRequest<Player> {
|
||||
"""
|
||||
SELECT \(columnsOf: self)
|
||||
FROM \(self)
|
||||
WHERE \(CodingKeys.id) = \(id)
|
||||
"""
|
||||
"SELECT * FROM \(self) WHERE \(CodingKeys.id) = \(id)"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -238,28 +261,17 @@ Let's extend Player with database methods.
|
||||
}
|
||||
```
|
||||
|
||||
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. It profits from SQL interpolation, and this is why this method simply returns an "SQL literal"".
|
||||
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. And it profits from SQL interpolation: this is why this method can simply return an "SQL literal"".
|
||||
|
||||
The first "simple" version only embeds the `\(id)` [value].
|
||||
|
||||
The second "robust" version embeds `\(columnsOf: self)`, the [columns selected by the record](#columns-selected-by-a-request), `\(self)` (the Player type which adopts the TableRecord protocol), `\(CodingKeys.id)` (the coding key synthesized by the Decodable protocol), and the `\(id)` [value].
|
||||
It embeds `\(self)` (the Player type which adopts the TableRecord protocol) and `\(CodingKeys.id)` (the coding key synthesized by the Decodable protocol), and `\(id)` (a [value]).
|
||||
|
||||
- `filter(ids:)`
|
||||
|
||||
```swift
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// "Simple" version
|
||||
/// All players with the given ids
|
||||
static func filter(ids: [Int64]) -> SQLRequest<Player> {
|
||||
"SELECT * FROM player WHERE id IN \(ids)"
|
||||
}
|
||||
|
||||
/// "Future-proof" version
|
||||
static func filter(ids: [Int64]) -> SQLRequest<Player> {
|
||||
"""
|
||||
SELECT \(columnsOf: self)
|
||||
FROM \(self)
|
||||
WHERE \(CodingKeys.id) IN \(ids)
|
||||
"""
|
||||
"SELECT * FROM \(self) WHERE \(CodingKeys.id) IN \(ids)"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -268,7 +280,7 @@ Let's extend Player with database methods.
|
||||
|
||||
```swift
|
||||
let players = try dbQueue.read { db in
|
||||
// SELECT * FROM player WHERE id IN (1, 2, 3)
|
||||
// SELECT * player WHERE id IN (1, 2, 3)
|
||||
try Player.filter(ids: [1, 2, 3]).fetchAll(db) // [Player]
|
||||
}
|
||||
```
|
||||
@@ -297,21 +309,15 @@ Let's extend Player with database methods.
|
||||
|
||||
The result is `SQLRequest<Int>`, unlike previous requests of type `SQLRequest<Player>`. SQLRequest accepts any fetchable type (database [row], simple [value], or custom [record]).
|
||||
|
||||
- `bestPlayers()`
|
||||
- `leaders()`
|
||||
|
||||
```swift
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// "Simple" version
|
||||
static func bestPlayers() -> SQLRequest<Player> {
|
||||
"SELECT * FROM player WHERE score = (\(maximumScore()))"
|
||||
}
|
||||
|
||||
/// "Future-proof" version
|
||||
static func bestPlayers() -> SQLRequest<Player> {
|
||||
/// All players whose score is the maximum score
|
||||
static func leaders() -> SQLRequest<Player> {
|
||||
"""
|
||||
SELECT \(columnsOf: self)
|
||||
FROM \(self)
|
||||
WHERE \(CodingKeys.score) = (\(maximumScore()))
|
||||
SELECT * FROM \(self)
|
||||
WHERE \(CodingKeys.score) = \(maximumScore())
|
||||
"""
|
||||
}
|
||||
}
|
||||
@@ -320,9 +326,10 @@ Let's extend Player with database methods.
|
||||
Usage:
|
||||
|
||||
```swift
|
||||
let bestPlayers = try dbQueue.read { db in
|
||||
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
|
||||
try Player.bestPlayers().fetchAll(db) // [Player]
|
||||
let leaders = try dbQueue.read { db in
|
||||
// SELECT * FROM player
|
||||
// WHERE score = (SELECT MAX(score) FROM player)
|
||||
try Player.leaders().fetchAll(db) // [Player]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -334,8 +341,7 @@ Let's extend Player with database methods.
|
||||
extension Player: Decodable, FetchableRecord, TableRecord {
|
||||
/// A complex request
|
||||
static func complexRequest() -> SQLRequest<Player> {
|
||||
let query: SQLLiteral = "SELECT \(columnsOf: self) "
|
||||
query += "FROM \(self) "
|
||||
let query: SQLLiteral = "SELECT * FROM \(self) "
|
||||
query += "JOIN \(Team.self) ON ..."
|
||||
query += "GROUP BY ..."
|
||||
return SQLRequest(literal: query)
|
||||
@@ -343,7 +349,7 @@ Let's extend Player with database methods.
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
This last request shows how to build an SQLRequest from an [SQLLiteral]. You will need SQLLiteral when the request can not be expressed in a single "SQL literal".
|
||||
|
||||
|
||||
|
||||
@@ -354,9 +360,8 @@ This chapter lists all kinds of supported interpolations.
|
||||
- Types adopting the [TableRecord] protocol:
|
||||
|
||||
```swift
|
||||
struct Player: TableRecord { ... }
|
||||
|
||||
// SELECT * FROM player
|
||||
extension Player: TableRecord { }
|
||||
"SELECT * FROM \(Player.self)"
|
||||
|
||||
// INSERT INTO player ...
|
||||
@@ -364,26 +369,6 @@ This chapter lists all kinds of supported interpolations.
|
||||
"INSERT INTO \(tableOf: player) ..."
|
||||
```
|
||||
|
||||
- Columns selected by [TableRecord]:
|
||||
|
||||
```swift
|
||||
struct Player: TableRecord { ... }
|
||||
|
||||
// SELECT player.* FROM player
|
||||
"SELECT \(columnsOf: Player.self) FROM player"
|
||||
|
||||
// SELECT p.* FROM player p
|
||||
"SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p"
|
||||
|
||||
struct AltPlayer: TableRecord {
|
||||
static let databaseTableName = "player"
|
||||
static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")]
|
||||
}
|
||||
|
||||
// SELECT player.id, player.name FROM player
|
||||
"SELECT \(columnsOf: AltPlayer.self) FROM player"
|
||||
```
|
||||
|
||||
- [Expressions] and [values]:
|
||||
|
||||
```swift
|
||||
@@ -420,16 +405,12 @@ This chapter lists all kinds of supported interpolations.
|
||||
"SELECT * FROM player WHERE id IN \(Column("name").desc)"
|
||||
```
|
||||
|
||||
- Subqueries:
|
||||
- SQLRequest:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
|
||||
let subquery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
"SELECT * FROM player WHERE score = (\(subquery))"
|
||||
|
||||
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
|
||||
let subquery = Player.select(max(Column("score")))
|
||||
"SELECT * FROM player WHERE score = (\(subquery))"
|
||||
let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
"SELECT * FROM player WHERE score = \(subQuery)"
|
||||
```
|
||||
|
||||
- SQLLiteral:
|
||||
@@ -471,4 +452,3 @@ This chapter lists all kinds of supported interpolations.
|
||||
[welcomed]: ../README.md#sqlite-api
|
||||
[query interface requests]: ../README.md#requests
|
||||
[SE-0228 Fix ExpressibleByStringInterpolation]: https://github.com/apple/swift-evolution/blob/master/proposals/0228-fix-expressiblebystringinterpolation.md
|
||||
[columns selected by the record]: ../README.md#columns-selected-by-a-request
|
||||
@@ -1,289 +0,0 @@
|
||||
Sharing a Database
|
||||
==================
|
||||
|
||||
This chapter describes a recommended setup that applies as soon as several processes want to access a same SQLite database.
|
||||
|
||||
On iOS for example, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati). On macOS as well, several processes may want to open the same database, according to their particular sandboxing contexts.
|
||||
|
||||
Accessing a shared database from several SQLite connections, from several processes, creates challenges at various levels:
|
||||
|
||||
1. **Database setup** may be attempted by multiple processes, concurrently.
|
||||
2. **SQLite** may throw `SQLITE_BUSY` errors, code 5, "database is locked".
|
||||
3. **iOS** may kill your application with a `0xDEAD10CC` exception.
|
||||
4. **GRDB** database observation misses changes performed by external processes.
|
||||
|
||||
We'll address all of those challenges below.
|
||||
|
||||
- [Use a Database Pool]
|
||||
- [How to limit the `SQLITE_BUSY` error]
|
||||
- [How to limit the `0xDEAD10CC` exception]
|
||||
- [How to perform cross-process database observation]
|
||||
|
||||
|
||||
## Use a Database Pool
|
||||
|
||||
In order to access a shared database, use a [Database Pool]. It opens the database in the [WAL mode](https://www.sqlite.org/wal.html), which helps sharing a database.
|
||||
|
||||
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
|
||||
|
||||
- In a process that can create and write in the database, use this sample code:
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL
|
||||
func openSharedDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
coordinator.coordinate(writingItemAt: databaseURL, options: .forMerging, error: &coordinatorError, byAccessor: { url in
|
||||
do {
|
||||
dbPool = try openDatabase(at: url)
|
||||
} catch {
|
||||
dbError = error
|
||||
}
|
||||
})
|
||||
if let error = dbError ?? coordinatorError {
|
||||
throw error
|
||||
}
|
||||
return dbPool!
|
||||
}
|
||||
|
||||
private func openDatabase(at databaseURL: URL) throws -> DatabasePool {
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase = { db in
|
||||
// Activate the persistent WAL mode so that
|
||||
// readonly processes can access the database.
|
||||
//
|
||||
// See https://www.sqlite.org/walformat.html#operations_that_require_locks_and_which_locks_those_operations_use
|
||||
// and https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal
|
||||
if db.configuration.readonly == false {
|
||||
var flag: CInt = 1
|
||||
let code = withUnsafeMutablePointer(to: &flag) { flagP in
|
||||
sqlite3_file_control(db.sqliteConnection, nil, SQLITE_FCNTL_PERSIST_WAL, flagP)
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: ResultCode(rawValue: code))
|
||||
}
|
||||
}
|
||||
}
|
||||
let dbPool = try DatabasePool(path: databaseURL.path)
|
||||
|
||||
// Perform here other database setups, such as defining
|
||||
// the database schema with a DatabaseMigrator, and
|
||||
// checking if the application can open the file:
|
||||
try migrator.migrate(dbPool)
|
||||
if try dbPool.read(migrator.hasBeenSuperseded) {
|
||||
// Database is too recent
|
||||
throw /* some error */
|
||||
}
|
||||
|
||||
return dbPool
|
||||
}
|
||||
```
|
||||
|
||||
- In a process that only reads in the database, use this sample code:
|
||||
|
||||
```swift
|
||||
/// Returns an initialized database pool at the shared location databaseURL,
|
||||
/// or nil if the database is not created yet, or does not have the required
|
||||
/// schema version.
|
||||
func openSharedReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
let coordinator = NSFileCoordinator(filePresenter: nil)
|
||||
var coordinatorError: NSError?
|
||||
var dbPool: DatabasePool?
|
||||
var dbError: Error?
|
||||
coordinator.coordinate(readingItemAt: databaseURL, options: .withoutChanges, error: &coordinatorError, byAccessor: { url in
|
||||
do {
|
||||
dbPool = try openReadOnlyDatabase(at: url)
|
||||
} catch {
|
||||
dbError = error
|
||||
}
|
||||
})
|
||||
if let error = dbError ?? coordinatorError {
|
||||
throw error
|
||||
}
|
||||
return dbPool
|
||||
}
|
||||
|
||||
private func openReadOnlyDatabase(at databaseURL: URL) throws -> DatabasePool? {
|
||||
do {
|
||||
var configuration = Configuration()
|
||||
configuration.readonly = true
|
||||
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
|
||||
|
||||
// Check here if the database schema is the expected one,
|
||||
// for example with a DatabaseMigrator:
|
||||
return try dbPool.read { db in
|
||||
if try migrator.hasBeenSuperseded(db) {
|
||||
// Database is too recent
|
||||
return nil
|
||||
} else if try migrator.hasCompletedMigrations(db) == false {
|
||||
// Database is too old
|
||||
return nil
|
||||
}
|
||||
return dbPool
|
||||
}
|
||||
} catch {
|
||||
if FileManager.default.fileExists(atPath: databaseURL.path) {
|
||||
throw error
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
#### The specific case of readonly connections
|
||||
|
||||
Readonly connections will fail unless two extra files ending in `-shm` and `-wal` are present next to the database file ([source](https://www.sqlite.org/walformat.html#operations_that_require_locks_and_which_locks_those_operations_use)). Those files are regular companions of databases in the [WAL mode]. But they are deleted, under regular operations, when database connections are closed. Precisely speaking, they *may* be deleted: it depends on the SQLite and the operating system versions ([source](https://github.com/groue/GRDB.swift/issues/739#issuecomment-604363998)). And when they are deleted, readonly connections fail.
|
||||
|
||||
The solution is to enable the "persistent WAL mode", as shown in the sample code above, by setting the [SQLITE_FCNTL_PERSIST_WAL](https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html#sqlitefcntlpersistwal) flag. This mode makes sure the `-shm` and `-wal` files are never deleted, and guarantees a database access to readonly connections.
|
||||
|
||||
|
||||
## How to limit the `SQLITE_BUSY` error
|
||||
|
||||
> The SQLITE_BUSY result code indicates that the database file could not be written (or in some cases read) because of concurrent activity by some other database connection, usually a database connection in a separate process.
|
||||
|
||||
See https://www.sqlite.org/rescode.html#busy for more information about this error.
|
||||
|
||||
If several processes want to write in the database, configure the database pool of each process that wants to write:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.busyMode = .timeout(/* a TimeInterval */)
|
||||
configuration.defaultTransactionKind = .immediate
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
With such a setup, you may still get `SQLITE_BUSY` (5, "database is locked") errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout.
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbPool.write { db in ... }
|
||||
} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
|
||||
// Another process won't let you write. Deal with it.
|
||||
}
|
||||
```
|
||||
|
||||
> :bulb: **Tip**: In order to be nice to other processes, measure the duration of your longest writes, and attempt at optimizing the ones that last for too long. See the [How do I monitor the duration of database statements execution?] FAQ.
|
||||
|
||||
|
||||
## How to limit the `0xDEAD10CC` exception
|
||||
|
||||
> 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/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 from your database preparation function:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.prepareDatabase = { (db: Database) in
|
||||
try db.usePassphrase("secret")
|
||||
try db.execute(sql: "PRAGMA cipher_plaintext_header_size = 32")
|
||||
}
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
Set the `observesSuspensionNotifications` configuration flag:
|
||||
|
||||
```swift
|
||||
var configuration = Configuration()
|
||||
configuration.observesSuspensionNotifications = true
|
||||
let dbPool = try DatabasePool(path: ..., configuration: configuration)
|
||||
```
|
||||
|
||||
Post `Database.suspendNotification` when the application is about to be [suspended](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle). You can for example post this notification from `UIApplicationDelegate.applicationDidEnterBackground(_:)`, or in the expiration handler of a [background task](https://forums.developer.apple.com/thread/85066).
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func applicationDidEnterBackground(_ application: UIApplication) {
|
||||
// Suspend databases
|
||||
NotificationCenter.default.post(name: Database.suspendNotification, object: self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Post `Database.resumeNotification` from `UIApplicationDelegate.applicationWillEnterForeground(_:)` (or `SceneDelegate.sceneWillEnterForeground(_:)` for scene-based applications):
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func applicationWillEnterForeground(_ application: UIApplication) {
|
||||
// Resume databases
|
||||
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If the application uses the background modes supported by iOS, post `Database.resumeNotification` method from each and every background mode callback that may use the database. For example, if your application supports background fetches:
|
||||
|
||||
```swift
|
||||
@UIApplicationMain
|
||||
class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
|
||||
// Resume databases
|
||||
NotificationCenter.default.post(name: Database.resumeNotification, object: self)
|
||||
// Proceed with background fetch
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception are greatly reduced. If you see one in your crash logs, please open an issue!
|
||||
|
||||
In exchange, you will get `SQLITE_INTERRUPT` (9) or `SQLITE_ABORT` (4) errors, with messages "Database is suspended", "Transaction was aborted", or "interrupted", for any attempt at writing in the database when it is suspended.
|
||||
|
||||
You can catch those errors:
|
||||
|
||||
```swift
|
||||
do {
|
||||
try dbPool.write { db in ... }
|
||||
} catch let error as DatabaseError where error.isInterruptionError {
|
||||
// Oops, the database is suspended.
|
||||
// Maybe try again after database is resumed?
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
## How to perform cross-process database observation
|
||||
|
||||
GRDB [Database Observation] features, as well as [GRDBCombine] and [RxGRDB], are not able to notify database changes performed by other processes.
|
||||
|
||||
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
|
||||
|
||||
You can trigger those notifications automatically with [DatabaseRegionObservation]:
|
||||
|
||||
```swift
|
||||
// Notify all changes made to the "player" and "team" database tables
|
||||
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
|
||||
let observer = try observation.start(in: dbPool) { (db: Database) in
|
||||
// Notify other processes
|
||||
}
|
||||
|
||||
// Notify all changes made to the database
|
||||
let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
|
||||
let observer = try observation.start(in: dbPool) { (db: Database) in
|
||||
// Notify other processes
|
||||
}
|
||||
```
|
||||
|
||||
[Use a Database Pool]: #use-a-database-pool
|
||||
[How to limit the `SQLITE_BUSY` error]: #how-to-limit-the-sqlite_busy-error
|
||||
[How to limit the `0xDEAD10CC` exception]: #how-to-limit-the-0xdead10cc-exception
|
||||
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
|
||||
[Database Pool]: ../README.md#database-pools
|
||||
[Database Observation]: ../README.md#database-changes-observation
|
||||
[GRDBCombine]: http://github.com/groue/GRDBCombine
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[NSFileCoordinator]: https://developer.apple.com/documentation/foundation/nsfilecoordinator
|
||||
[CFNotificationCenterGetDarwinNotifyCenter]: https://developer.apple.com/documentation/corefoundation/1542572-cfnotificationcentergetdarwinnot
|
||||
[DatabaseRegionObservation]: ../README.md#databaseregionobservation
|
||||
[WAL mode]: https://www.sqlite.org/wal.html
|
||||
[How do I monitor the duration of database statements execution?]: ../README.md#how-do-i-monitor-the-duration-of-database-statements-execution
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.0.0-beta.5'
|
||||
s.version = '4.14.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
@@ -10,7 +10,7 @@ Pod::Spec.new do |s|
|
||||
s.module_name = 'GRDB'
|
||||
|
||||
s.swift_versions = ['5.2']
|
||||
s.ios.deployment_target = '10.0'
|
||||
s.ios.deployment_target = '9.0'
|
||||
s.osx.deployment_target = '10.10'
|
||||
s.watchos.deployment_target = '2.0'
|
||||
s.tvos.deployment_target = '9.0'
|
||||
@@ -23,7 +23,7 @@ Pod::Spec.new do |s|
|
||||
end
|
||||
|
||||
s.subspec 'SQLCipher' do |ss|
|
||||
ss.source_files = 'GRDB/**/*.swift', 'Support/SQLCipher_config.h'
|
||||
ss.source_files = 'GRDB/**/*.swift', 'Support/grdb_config.h'
|
||||
ss.framework = 'Foundation'
|
||||
ss.dependency 'SQLCipher', '>= 3.4.0'
|
||||
ss.xcconfig = {
|
||||
|
||||
@@ -166,9 +166,6 @@
|
||||
563B071621862C4700B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */; };
|
||||
563B071821862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
|
||||
563B071921862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
|
||||
563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
|
||||
563C67B424628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
|
||||
563C67B524628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; };
|
||||
563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
|
||||
563DE4F4231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
|
||||
563DE4F5231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; };
|
||||
@@ -192,6 +189,14 @@
|
||||
5644DE6E20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
|
||||
5644DE6F20F8C32E001FFDDE /* DatabaseValueConversion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */; };
|
||||
564A50C81BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */; };
|
||||
564C2450244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
|
||||
564C2451244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
|
||||
564C2452244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
|
||||
564C2453244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
|
||||
564C2459244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
|
||||
564C245A244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
|
||||
564C245B244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
|
||||
564C245C244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
|
||||
564CE43121AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
564CE43221AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
564CE43321AA901800652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43021AA901800652B19 /* ValueObserver.swift */; };
|
||||
@@ -799,10 +804,6 @@
|
||||
56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; };
|
||||
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
|
||||
56F3E74D1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
|
||||
56F409212465C8D400A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; };
|
||||
56F409222465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; };
|
||||
56F409232465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; };
|
||||
56F409242465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */; };
|
||||
56F5ABD91D814330001F60CB /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
|
||||
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
|
||||
56F5ABDC1D814330001F60CB /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; };
|
||||
@@ -814,9 +815,6 @@
|
||||
56FC987B1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
|
||||
56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */; };
|
||||
56FDECE31BB32DFD009AD709 /* RowFromStatementTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */; };
|
||||
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
|
||||
56FEB8F9248403010081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
|
||||
56FEB8FA248403020081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */; };
|
||||
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
|
||||
56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
|
||||
56FF45441D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; };
|
||||
@@ -1245,7 +1243,6 @@
|
||||
563B0704218627F700B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = "<group>"; };
|
||||
563B071421862C4600B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
|
||||
563B071721862F4C00B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
|
||||
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
|
||||
563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
|
||||
563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
|
||||
563EF42C2161180D007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = "<group>"; };
|
||||
@@ -1255,6 +1252,8 @@
|
||||
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
|
||||
5644DE6C20F8C32E001FFDDE /* DatabaseValueConversion.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversion.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyFirstSQLTests.swift; sourceTree = "<group>"; };
|
||||
564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughFirstSQLTests.swift; sourceTree = "<group>"; };
|
||||
564CE43021AA901800652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
|
||||
564CE4E821B2E06F00652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
|
||||
564CE59621B7A8B500652B19 /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = "<group>"; };
|
||||
@@ -1505,11 +1504,9 @@
|
||||
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
|
||||
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
|
||||
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
|
||||
56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequestProtocol.swift; sourceTree = "<group>"; };
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
|
||||
56FC98771D969DEF00E3C842 /* SQLExpression+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "SQLExpression+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
|
||||
56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = "<group>"; };
|
||||
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = "<group>"; };
|
||||
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = "<group>"; };
|
||||
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1653,7 +1650,6 @@
|
||||
560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */,
|
||||
569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */,
|
||||
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */,
|
||||
563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */,
|
||||
);
|
||||
name = DatabasePool;
|
||||
sourceTree = "<group>";
|
||||
@@ -1845,9 +1841,11 @@
|
||||
5653EAC920944B4D00F46237 /* AssociationBelongsToSQLTests.swift */,
|
||||
5653EAC620944B4C00F46237 /* AssociationChainRowScopesTests.swift */,
|
||||
5653EACF20944B4E00F46237 /* AssociationChainSQLTests.swift */,
|
||||
564C244F244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift */,
|
||||
561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */,
|
||||
56057C4E2291B16900A7CB10 /* AssociationHasManyRowScopeTests.swift */,
|
||||
56959632222D056D002CB7C9 /* AssociationHasManySQLTests.swift */,
|
||||
564C2458244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */,
|
||||
561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */,
|
||||
56057C612291C7C600A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */,
|
||||
56959615222C456C002CB7C9 /* AssociationHasManyThroughSQLTests.swift */,
|
||||
@@ -2057,7 +2055,6 @@
|
||||
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
|
||||
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
|
||||
56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */,
|
||||
564FCE5D20F7E11A00202B90 /* DatabaseValueConversionErrorTests.swift */,
|
||||
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
|
||||
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
|
||||
@@ -2168,7 +2165,6 @@
|
||||
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
|
||||
56E9FAD7221053DC00C703A8 /* SQLLiteral.swift */,
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */,
|
||||
56F409202465C8D400A7A152 /* SQLRequestProtocol.swift */,
|
||||
56A238781B9C75030082EB20 /* Statement.swift */,
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
|
||||
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
|
||||
@@ -2331,10 +2327,10 @@
|
||||
567DAF141EAB61ED00FC0928 /* grdb_config.h */,
|
||||
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */,
|
||||
DC3773F819C8CBB3004FCF85 /* GRDB.h */,
|
||||
56C48E731C9A9923005DF1D9 /* module.modulemap */,
|
||||
DC3773F719C8CBB3004FCF85 /* Info.plist */,
|
||||
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */,
|
||||
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */,
|
||||
DC3773F719C8CBB3004FCF85 /* Info.plist */,
|
||||
56C48E731C9A9923005DF1D9 /* module.modulemap */,
|
||||
);
|
||||
name = "Supporting Files";
|
||||
path = ../Support;
|
||||
@@ -2819,7 +2815,6 @@
|
||||
56F5ABD91D814330001F60CB /* Data.swift in Sources */,
|
||||
565490D41D5AE252005622CB /* (null) in Sources */,
|
||||
566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
56F409232465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */,
|
||||
565490B61D5AE236005622CB /* Configuration.swift in Sources */,
|
||||
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */,
|
||||
56FC987E1D969DEF00E3C842 /* SQLExpression+QueryInterface.swift in Sources */,
|
||||
@@ -2862,10 +2857,12 @@
|
||||
569531091C9067DC00CF1A2B /* DatabaseQueueCrashTests.swift in Sources */,
|
||||
5695310D1C9067DC00CF1A2B /* RecordCrashTests.swift in Sources */,
|
||||
56BF2283241781C5003D86EB /* UtilsTests.swift in Sources */,
|
||||
564C2451244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
|
||||
5695310E1C9067DC00CF1A2B /* StatementColumnConvertibleCrashTests.swift in Sources */,
|
||||
5695310A1C9067DC00CF1A2B /* DatabaseValueConvertibleCrashTests.swift in Sources */,
|
||||
5695310F1C9067DC00CF1A2B /* StatementCrashTests.swift in Sources */,
|
||||
5695310B1C9067DC00CF1A2B /* GRDBCrashTestCase.swift in Sources */,
|
||||
564C245A244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
|
||||
560A37AF1C90A8D800949E71 /* DatabasePoolCrashTests.swift in Sources */,
|
||||
56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */,
|
||||
);
|
||||
@@ -2925,7 +2922,6 @@
|
||||
56D51D031EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
56DDDDF5242F87C60025E381 /* ValueObservationScheduler.swift in Sources */,
|
||||
560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */,
|
||||
56F409222465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */,
|
||||
56A2FA3B24424F4700E97D23 /* Export.swift in Sources */,
|
||||
569BBA4F229170F900478429 /* Inflections+English.swift in Sources */,
|
||||
5656A81F2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
@@ -3049,7 +3045,6 @@
|
||||
56B14E831D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
|
||||
562393341DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */,
|
||||
5698AC841DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */,
|
||||
563C67B424628BEA00E94EDC /* DatabasePoolTests.swift in Sources */,
|
||||
5653EAE320944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */,
|
||||
566AD8CA1D531BEC002EC1A8 /* TableDefinitionTests.swift in Sources */,
|
||||
56A238541B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
|
||||
@@ -3078,6 +3073,7 @@
|
||||
56EA869F1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift in Sources */,
|
||||
56677C16241D14450050755D /* FailableTestCase.swift in Sources */,
|
||||
5615B288222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
|
||||
564C245B244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
|
||||
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
|
||||
5682D722239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
|
||||
5657AB621D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
|
||||
@@ -3120,7 +3116,6 @@
|
||||
56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
|
||||
56FEE7FF1F47253700D930EA /* TableRecordTests.swift in Sources */,
|
||||
56057C562291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
|
||||
56FEB8F9248403010081AF83 /* DatabaseTraceTests.swift in Sources */,
|
||||
56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */,
|
||||
56A2383E1B9C74A90082EB20 /* DatabaseValueTests.swift in Sources */,
|
||||
567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */,
|
||||
@@ -3136,6 +3131,7 @@
|
||||
5653EAE520944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
|
||||
56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
|
||||
56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */,
|
||||
564C2452244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
|
||||
56915783231BF28B00E1D237 /* PoolTests.swift in Sources */,
|
||||
56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */,
|
||||
5665FA342129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
@@ -3257,7 +3253,6 @@
|
||||
56D496891D81316E008276D7 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
|
||||
56D4967C1D8130DB008276D7 /* CGFloatTests.swift in Sources */,
|
||||
56D496631D81304E008276D7 /* FoundationURLTests.swift in Sources */,
|
||||
563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */,
|
||||
56D496B71D81344B008276D7 /* RecordUniqueIndexTests.swift in Sources */,
|
||||
5653EAE220944B4F00F46237 /* AssociationHasOneSQLTests.swift in Sources */,
|
||||
56D496671D813086008276D7 /* Record+QueryInterfaceRequestTests.swift in Sources */,
|
||||
@@ -3286,6 +3281,7 @@
|
||||
56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */,
|
||||
56677C15241D14450050755D /* FailableTestCase.swift in Sources */,
|
||||
5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
|
||||
564C2459244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
|
||||
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
|
||||
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
|
||||
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
|
||||
@@ -3328,7 +3324,6 @@
|
||||
5674A72A1F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
|
||||
566A84402041914000E50BFD /* MutablePersistableRecordChangesTests.swift in Sources */,
|
||||
56057C552291B16A00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
|
||||
56FEB8F8248403000081AF83 /* DatabaseTraceTests.swift in Sources */,
|
||||
56176C5E1EACCCC7000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */,
|
||||
56FEE7FB1F47253700D930EA /* TableRecordTests.swift in Sources */,
|
||||
56D496641D81304E008276D7 /* FoundationUUIDTests.swift in Sources */,
|
||||
@@ -3344,6 +3339,7 @@
|
||||
562393601DEE06D300A6B01F /* CursorTests.swift in Sources */,
|
||||
5653EAE420944B4F00F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
|
||||
56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */,
|
||||
564C2450244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
|
||||
56915782231BF28B00E1D237 /* PoolTests.swift in Sources */,
|
||||
56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */,
|
||||
5665FA332129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
@@ -3471,7 +3467,6 @@
|
||||
AAA4DCA6230F1E0600C74B15 /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
56DDDDF7242F87C70025E381 /* ValueObservationScheduler.swift in Sources */,
|
||||
AAA4DCA7230F1E0600C74B15 /* TableRecord.swift in Sources */,
|
||||
56F409242465C8D500A7A152 /* SQLRequestProtocol.swift in Sources */,
|
||||
56A2FA3D24424F4800E97D23 /* Export.swift in Sources */,
|
||||
AAA4DCA8230F1E0600C74B15 /* Inflections+English.swift in Sources */,
|
||||
AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */,
|
||||
@@ -3595,7 +3590,6 @@
|
||||
AAA4DD33230F262000C74B15 /* RowFromDictionaryLiteralTests.swift in Sources */,
|
||||
AAA4DD34230F262000C74B15 /* AnyCursorTests.swift in Sources */,
|
||||
AAA4DD35230F262000C74B15 /* VirtualTableModuleTests.swift in Sources */,
|
||||
563C67B524628BEA00E94EDC /* DatabasePoolTests.swift in Sources */,
|
||||
AAA4DD36230F262000C74B15 /* AssociationHasOneSQLTests.swift in Sources */,
|
||||
AAA4DD37230F262000C74B15 /* TableDefinitionTests.swift in Sources */,
|
||||
AAA4DD38230F262000C74B15 /* RecordPrimaryKeyMultipleTests.swift in Sources */,
|
||||
@@ -3624,6 +3618,7 @@
|
||||
AAA4DD4D230F262000C74B15 /* DatabasePoolReadOnlyTests.swift in Sources */,
|
||||
56677C17241D14450050755D /* FailableTestCase.swift in Sources */,
|
||||
AAA4DD4E230F262000C74B15 /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
|
||||
564C245C244A466A003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
|
||||
AAA4DD4F230F262000C74B15 /* TruncateOptimizationTests.swift in Sources */,
|
||||
5682D723239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
|
||||
AAA4DD50230F262000C74B15 /* FoundationNSURLTests.swift in Sources */,
|
||||
@@ -3666,7 +3661,6 @@
|
||||
AAA4DD76230F262000C74B15 /* FTS5WrapperTokenizerTests.swift in Sources */,
|
||||
AAA4DD77230F262000C74B15 /* TableRecordTests.swift in Sources */,
|
||||
AAA4DD78230F262000C74B15 /* AssociationHasManyRowScopeTests.swift in Sources */,
|
||||
56FEB8FA248403020081AF83 /* DatabaseTraceTests.swift in Sources */,
|
||||
AAA4DD79230F262000C74B15 /* RecordSubClassTests.swift in Sources */,
|
||||
AAA4DD7A230F262000C74B15 /* DatabaseValueTests.swift in Sources */,
|
||||
AAA4DD7B230F262000C74B15 /* DatabaseQueueReadOnlyTests.swift in Sources */,
|
||||
@@ -3682,6 +3676,7 @@
|
||||
AAA4DD85230F262000C74B15 /* AssociationParallelRowScopesTests.swift in Sources */,
|
||||
AAA4DD86230F262000C74B15 /* SQLExpressionLiteralTests.swift in Sources */,
|
||||
AAA4DD87230F262000C74B15 /* DropFirstCursorTests.swift in Sources */,
|
||||
564C2453244A44B4003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
|
||||
56915784231BF28B00E1D237 /* PoolTests.swift in Sources */,
|
||||
AAA4DD88230F262000C74B15 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
|
||||
AAA4DD89230F262000C74B15 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
@@ -3809,7 +3804,6 @@
|
||||
5656A81E2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
5617294E223533F40006E219 /* EncodableRecord.swift in Sources */,
|
||||
5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */,
|
||||
56F409212465C8D400A7A152 /* SQLRequestProtocol.swift in Sources */,
|
||||
56A2FA3624424D2A00E97D23 /* Export.swift in Sources */,
|
||||
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
|
||||
|
||||
@@ -16,7 +16,7 @@ public struct Configuration {
|
||||
/// Default: false
|
||||
public var readonly: Bool = false
|
||||
|
||||
/// The configuration label.
|
||||
/// The database label.
|
||||
///
|
||||
/// You can query this label at runtime:
|
||||
///
|
||||
@@ -28,43 +28,46 @@ public struct Configuration {
|
||||
/// print(db.configuration.label) // Prints "MyDatabase"
|
||||
/// }
|
||||
///
|
||||
/// The configuration label is also used to name Database connections (the
|
||||
/// `Database.description` property), and the various dispatch queues
|
||||
/// created by GRDB, visible in debugging sessions and crash logs.
|
||||
/// The database label is also used to name the various dispatch queues
|
||||
/// created by GRDB, visible in debugging sessions and crash logs. However
|
||||
/// those dispatch queue labels are intended for debugging only. Their
|
||||
/// format may change between GRDB releases. Applications should not depend
|
||||
/// on the GRDB dispatch queue labels.
|
||||
///
|
||||
/// Those connection names and dispatch queue labels are intended for
|
||||
/// debugging only. Their format may change between GRDB releases.
|
||||
/// Applications should not depend on connection names and dispatch
|
||||
/// queue labels.
|
||||
/// If the database label is nil, the current GRDB implementation uses the
|
||||
/// following dispatch queue labels:
|
||||
///
|
||||
/// If the configuration label is nil, the current GRDB implementation uses
|
||||
/// the following names:
|
||||
///
|
||||
/// - `GRDB.DatabaseQueue`: the (unique) connection of a DatabaseQueue
|
||||
/// - `GRDB.DatabasePool.writer`: the (unique) writer connection of
|
||||
/// - `GRDB.DatabaseQueue`: the (unique) dispatch queue of a DatabaseQueue
|
||||
/// - `GRDB.DatabasePool.writer`: the (unique) writer dispatch queue of
|
||||
/// a DatabasePool
|
||||
/// - `GRDB.DatabasePool.reader.N`, where N is 1, 2, ...: one of the reader
|
||||
/// connection(s) of a DatabasePool. N may get bigger than the maximum
|
||||
/// number of concurrent readers, as SQLite connections get closed and new
|
||||
/// ones are opened.
|
||||
/// - `GRDB.DatabasePool.snapshot.N`: the connection of a DatabaseSnapshot.
|
||||
/// N grows with the number of snapshots.
|
||||
/// dispatch queue(s) of a DatabasePool. N grows with the number of SQLite
|
||||
/// connections: it may get bigger than the maximum number of concurrent
|
||||
/// readers, as SQLite connections get closed and new ones are opened.
|
||||
/// - `GRDB.DatabasePool.snapshot.N`: the dispatch queue of a
|
||||
/// DatabaseSnapshot. N grows with the number of snapshots.
|
||||
///
|
||||
/// If the configuration label is not nil, for example "MyDatabase", the
|
||||
/// current GRDB implementation uses the following names:
|
||||
/// If the database label is not nil, for example "MyDatabase", the current
|
||||
/// GRDB implementation uses the following dispatch queue labels:
|
||||
///
|
||||
/// - `MyDatabase`: the (unique) connection of a DatabaseQueue
|
||||
/// - `MyDatabase.writer`: the (unique) writer connection of a DatabasePool
|
||||
/// - `MyDatabase`: the (unique) dispatch queue of a DatabaseQueue
|
||||
/// - `MyDatabase.writer`: the (unique) writer dispatch queue of
|
||||
/// a DatabasePool
|
||||
/// - `MyDatabase.reader.N`, where N is 1, 2, ...: one of the reader
|
||||
/// connection(s) of a DatabasePool. N may get bigger than the maximum
|
||||
/// number of concurrent readers, as SQLite connections get closed and new
|
||||
/// ones are opened.
|
||||
/// - `MyDatabase.snapshot.N`: the connection of a DatabaseSnapshot. N grows
|
||||
/// with the number of snapshots.
|
||||
/// dispatch queue(s) of a DatabasePool. N grows with the number of SQLite
|
||||
/// connections: it may get bigger than the maximum number of concurrent
|
||||
/// readers, as SQLite connections get closed and new ones are opened.
|
||||
/// - `MyDatabase.snapshot.N`: the dispatch queue of a
|
||||
/// DatabaseSnapshot. N grows with the number of snapshots.
|
||||
///
|
||||
/// The default configuration label is nil.
|
||||
/// The default label is nil.
|
||||
public var label: String? = nil
|
||||
|
||||
/// A function that is called on every statement executed by the database.
|
||||
///
|
||||
/// Default: nil
|
||||
public var trace: TraceFunction?
|
||||
|
||||
/// If false, SQLite from version 3.29.0 will not interpret a double-quoted
|
||||
/// string as a string literal if it does not match any valid identifier.
|
||||
///
|
||||
@@ -161,10 +164,6 @@ public struct Configuration {
|
||||
/// Default: immediateError
|
||||
public var busyMode: Database.BusyMode = .immediateError
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
|
||||
/// If nil, GRDB picks a default one.
|
||||
var readonlyBusyMode: Database.BusyMode? = nil
|
||||
|
||||
/// The maximum number of concurrent readers (applies to database
|
||||
/// pools only).
|
||||
///
|
||||
@@ -207,11 +206,8 @@ public struct Configuration {
|
||||
return threadingMode.SQLiteOpenFlags | readWriteFlags
|
||||
}
|
||||
|
||||
func identifier(defaultLabel: String, purpose: String? = nil) -> String {
|
||||
(self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "")
|
||||
}
|
||||
|
||||
func makeDispatchQueue(label: String) -> DispatchQueue {
|
||||
func makeDispatchQueue(defaultLabel: String, purpose: String? = nil) -> DispatchQueue {
|
||||
let label = (self.label ?? defaultLabel) + (purpose.map { "." + $0 } ?? "")
|
||||
if let targetQueue = targetQueue {
|
||||
return DispatchQueue(label: label, target: targetQueue)
|
||||
} else {
|
||||
@@ -219,3 +215,6 @@ public struct Configuration {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tracing function that takes an SQL string.
|
||||
public typealias TraceFunction = (String) -> Void
|
||||
@@ -344,27 +344,23 @@ extension Database {
|
||||
throws -> [String]?
|
||||
where T.Iterator.Element == String
|
||||
{
|
||||
// Check primaryKey first, so that we fail early if the table does not exist
|
||||
let lowercasedColumns = Set(columns.map { $0.lowercased() })
|
||||
if lowercasedColumns.isEmpty {
|
||||
// Don't hit the database for trivial case
|
||||
return nil
|
||||
}
|
||||
|
||||
// Assume "rowid" is a primary key
|
||||
if lowercasedColumns == ["rowid"] {
|
||||
return ["rowid"]
|
||||
}
|
||||
|
||||
// Check primaryKey.
|
||||
let primaryKey = try self.primaryKey(tableName)
|
||||
if Set(primaryKey.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns) {
|
||||
if Set(primaryKey.columns.map { $0.lowercased() }) == lowercasedColumns {
|
||||
return primaryKey.columns
|
||||
}
|
||||
|
||||
// Is there is an explicit unique index on the columns?
|
||||
let indexes = try self.indexes(on: tableName)
|
||||
let matchingIndex = indexes.first { index in
|
||||
index.isUnique && Set(index.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns)
|
||||
index.isUnique && Set(index.columns.map { $0.lowercased() }) == lowercasedColumns
|
||||
}
|
||||
if let index = matchingIndex {
|
||||
return index.columns
|
||||
|
||||
@@ -6,9 +6,9 @@ extension Database {
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(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.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A SelectStatement.
|
||||
@@ -17,24 +17,6 @@ extension Database {
|
||||
try makeSelectStatement(sql: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
// TODO: remove when FetchRequest is a closed protocol.
|
||||
/// Returns a new prepared statement.
|
||||
///
|
||||
/// let id = 1
|
||||
/// let literal: SQLLiteral = "SELECT * FROM player WHERE id = \(id)"
|
||||
/// let statement = try db.makeSelectStatement(literal: literal)
|
||||
/// let player = try Player.fetchOne(statement)!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A SelectStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeSelectStatement(literal: SQLLiteral) throws -> SelectStatement {
|
||||
let (sql, arguments) = try literal.build(self)
|
||||
let statement = try makeSelectStatement(sql: sql, prepFlags: 0)
|
||||
statement.arguments = arguments
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
|
||||
@@ -176,8 +158,8 @@ extension Database {
|
||||
//
|
||||
// And before we return, we'll check that all arguments were consumed.
|
||||
|
||||
let context = SQLGenerationContext(self)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
var context = SQLGenerationContext.sqlLiteralContext
|
||||
let sql = sqlLiteral.sql(&context)
|
||||
var arguments = context.arguments
|
||||
let initialValuesCount = arguments.values.count
|
||||
|
||||
@@ -240,7 +222,7 @@ extension Database {
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion.formUnion(statement.databaseRegion)
|
||||
_selectedRegion.formUnion(statement.selectedRegion)
|
||||
}
|
||||
|
||||
let authorizer = observationBroker.updateStatementWillExecute(statement)
|
||||
@@ -317,7 +299,7 @@ extension Database {
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion.formUnion(statement.databaseRegion)
|
||||
_selectedRegion.formUnion(statement.selectedRegion)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+81
-331
@@ -19,7 +19,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// try dbQueue.write { db in
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
public final class Database {
|
||||
// The Database class is not thread-safe. An instance should always be
|
||||
// used through a SerializedDatabase.
|
||||
|
||||
@@ -59,11 +59,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// The database configuration
|
||||
public let configuration: Configuration
|
||||
|
||||
/// See `Configuration.label`
|
||||
public let description: String
|
||||
|
||||
public var debugDescription: String { "<Database: \(description)>" }
|
||||
|
||||
// MARK: - Database Information
|
||||
|
||||
/// The rowID of the most recently inserted row.
|
||||
@@ -149,7 +144,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
var isInsideTransactionBlock = false
|
||||
|
||||
/// Support for checkForSuspensionViolation(from:)
|
||||
@LockedBox var isSuspended = false
|
||||
var isSuspended = LockedBox<Bool>(value: false)
|
||||
|
||||
/// Support for checkForSuspensionViolation(from:)
|
||||
/// This cache is never cleared: we assume journal mode never changes.
|
||||
@@ -158,7 +153,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// MARK: - Private properties
|
||||
|
||||
private var busyCallback: BusyCallback?
|
||||
private var trace: ((TraceEvent) -> Void)?
|
||||
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly
|
||||
@@ -166,14 +161,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
init(
|
||||
path: String,
|
||||
description: String,
|
||||
configuration: Configuration,
|
||||
schemaCache: DatabaseSchemaCache) throws
|
||||
{
|
||||
init(path: String, configuration: Configuration, schemaCache: DatabaseSchemaCache) throws {
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.description = description
|
||||
self.configuration = configuration
|
||||
self.schemaCache = schemaCache
|
||||
}
|
||||
@@ -211,9 +200,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// This method must be called after database initialization
|
||||
func setup() throws {
|
||||
setupBusyMode()
|
||||
// Setup trace first, so that setup queries are traced.
|
||||
setupTrace()
|
||||
setupDoubleQuotedStringLiterals()
|
||||
try setupForeignKeys()
|
||||
setupBusyMode()
|
||||
setupDefaultFunctions()
|
||||
setupDefaultCollations()
|
||||
setupAuthorizer()
|
||||
@@ -231,6 +222,69 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
configuration.SQLiteConnectionDidOpen?()
|
||||
}
|
||||
|
||||
private func setupTrace() {
|
||||
guard configuration.trace != nil else {
|
||||
return
|
||||
}
|
||||
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
|
||||
// http://www.sqlite.org/changes.html#version_3_14
|
||||
// It is available from iOS 10.0 and OS X 10.12
|
||||
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace_v2(
|
||||
sqliteConnection,
|
||||
UInt32(SQLITE_TRACE_STMT),
|
||||
{ (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
|
||||
Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
|
||||
},
|
||||
dbPointer)
|
||||
#elseif os(Linux)
|
||||
setupTrace_v1()
|
||||
#else
|
||||
if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace_v2(
|
||||
sqliteConnection,
|
||||
UInt32(SQLITE_TRACE_STMT),
|
||||
{ (mask, dbPointer, stmt, unexpandedSQL) -> Int32 in
|
||||
Database.trace_v2(mask, dbPointer, stmt, unexpandedSQL, sqlite3_expanded_sql)
|
||||
},
|
||||
dbPointer)
|
||||
} else {
|
||||
setupTrace_v1()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
// Precondition: configuration.trace != nil
|
||||
private func setupTrace_v1() {
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
|
||||
guard let sql = sql.map(String.init) else { return }
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.configuration.trace!(sql)
|
||||
}, dbPointer)
|
||||
}
|
||||
|
||||
// Precondition: configuration.trace != nil
|
||||
private static func trace_v2(
|
||||
_ mask: UInt32,
|
||||
_ dbPointer: UnsafeMutableRawPointer?,
|
||||
_ stmt: UnsafeMutableRawPointer?,
|
||||
_ unexpandedSQL: UnsafeMutableRawPointer?,
|
||||
_ sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
|
||||
-> Int32
|
||||
{
|
||||
guard let stmt = stmt else { return SQLITE_OK }
|
||||
guard let expandedSQLCString = sqlite3_expanded_sql(OpaquePointer(stmt)) else { return SQLITE_OK }
|
||||
let sql = String(cString: expandedSQLCString)
|
||||
sqlite3_free(expandedSQLCString)
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.configuration.trace!(sql)
|
||||
return SQLITE_OK
|
||||
}
|
||||
|
||||
private func setupDoubleQuotedStringLiterals() {
|
||||
if configuration.acceptsDoubleQuotedStringLiterals {
|
||||
enableDoubleQuotedStringLiterals(sqliteConnection)
|
||||
@@ -247,10 +301,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
|
||||
private func setupBusyMode() {
|
||||
let busyMode = configuration.readonly
|
||||
? configuration.readonlyBusyMode ?? configuration.busyMode
|
||||
: configuration.busyMode
|
||||
switch busyMode {
|
||||
switch configuration.busyMode {
|
||||
case .immediateError:
|
||||
break
|
||||
|
||||
@@ -277,7 +328,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
add(function: .lowercase)
|
||||
add(function: .uppercase)
|
||||
|
||||
if #available(OSX 10.11, watchOS 3.0, *) {
|
||||
if #available(iOS 9.0, OSX 10.11, watchOS 3.0, *) {
|
||||
add(function: .localizedCapitalize)
|
||||
add(function: .localizedLowercase)
|
||||
add(function: .localizedUppercase)
|
||||
@@ -380,25 +431,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Limits
|
||||
|
||||
/// The maximum number of arguments accepted by an SQLite statement.
|
||||
///
|
||||
/// For example, requests such as the one below must make sure the `ids`
|
||||
/// array does not contain more than `maximumStatementArgumentCount`
|
||||
/// elements:
|
||||
///
|
||||
/// let ids: [Int] = ...
|
||||
/// try dbQueue.write { db in
|
||||
/// try Player.deleteAll(db, keys: ids)
|
||||
/// }
|
||||
///
|
||||
/// 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))
|
||||
}
|
||||
|
||||
// MARK: - Functions
|
||||
|
||||
/// Add or redefine an SQL function.
|
||||
@@ -485,38 +517,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
finally: endReadOnly)
|
||||
}
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
/// Returns a snapshot that must be freed with `grdb_snapshot_free`.
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/snapshot.html
|
||||
func takeVersionSnapshot() throws -> UnsafeMutablePointer<sqlite3_snapshot> {
|
||||
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let code = withUnsafeMutablePointer(to: &snapshot) {
|
||||
grdb_snapshot_get(sqliteConnection, "main", $0)
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
// Don't grab `lastErrorMessage`, because grdb_snapshot_get may be a
|
||||
// shim that does not call the missing sqlite3_snapshot_get.
|
||||
throw DatabaseError(resultCode: code)
|
||||
}
|
||||
if let snapshot = snapshot {
|
||||
return snapshot
|
||||
} else {
|
||||
throw DatabaseError(resultCode: .SQLITE_INTERNAL) // WTF SQLite?
|
||||
}
|
||||
}
|
||||
|
||||
func wasChanged(since initialSnapshot: UnsafeMutablePointer<sqlite3_snapshot>) throws -> Bool {
|
||||
let secondSnapshot = try takeVersionSnapshot()
|
||||
defer {
|
||||
grdb_snapshot_free(secondSnapshot)
|
||||
}
|
||||
let cmp = grdb_snapshot_cmp(initialSnapshot, secondSnapshot)
|
||||
assert(cmp <= 0, "Unexpected snapshot ordering")
|
||||
return cmp < 0
|
||||
}
|
||||
|
||||
// MARK: - Authorizer
|
||||
|
||||
func withAuthorizer<T>(_ authorizer: StatementAuthorizer?, _ block: () throws -> T) rethrows -> T {
|
||||
@@ -550,157 +550,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return try block()
|
||||
}
|
||||
|
||||
// MARK: - Trace
|
||||
// MARK: - Checkpoints
|
||||
|
||||
/// Registers a tracing function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // Trace all SQL statements executed by the database
|
||||
/// var configuration = Configuration()
|
||||
/// configuration.prepareDatabase = { db in
|
||||
/// db.trace(options: .statement) { event in
|
||||
/// print("SQL: \(event)")
|
||||
/// }
|
||||
/// }
|
||||
/// let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
|
||||
///
|
||||
/// Pass an empty options set in order to stop database tracing:
|
||||
///
|
||||
/// // Stop tracing
|
||||
/// db.trace(options: [])
|
||||
///
|
||||
/// 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.
|
||||
/// - parameter trace: the tracing function.
|
||||
public func trace(options: TracingOptions = .statement, _ trace: ((TraceEvent) -> Void)? = nil) {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
self.trace = trace
|
||||
|
||||
if options.isEmpty || trace == nil {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
|
||||
#elseif os(Linux)
|
||||
sqlite3_trace(sqliteConnection, nil)
|
||||
#else
|
||||
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
|
||||
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
|
||||
} else {
|
||||
sqlite3_trace(sqliteConnection, nil, nil)
|
||||
}
|
||||
#endif
|
||||
return
|
||||
}
|
||||
|
||||
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
|
||||
// http://www.sqlite.org/changes.html#version_3_14
|
||||
// It is available from macOS 10.12, tvOS 10.0, watchOS 3.0
|
||||
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql)
|
||||
return SQLITE_OK
|
||||
}, dbPointer)
|
||||
#elseif os(Linux)
|
||||
setupTrace_v1()
|
||||
#else
|
||||
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql)
|
||||
return SQLITE_OK
|
||||
}, dbPointer)
|
||||
} else {
|
||||
setupTrace_v1()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !(GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS))
|
||||
private func setupTrace_v1() {
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
|
||||
guard let sql = sql.map(String.init(cString:)) else { return }
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.trace?(Database.TraceEvent.statement(TraceEvent.Statement(impl: .trace_v1(sql))))
|
||||
}, dbPointer)
|
||||
}
|
||||
#endif
|
||||
|
||||
// Precondition: configuration.trace != nil
|
||||
private func trace_v2(
|
||||
_ mask: CInt,
|
||||
_ p: UnsafeMutableRawPointer?,
|
||||
_ x: UnsafeMutableRawPointer?,
|
||||
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
|
||||
{
|
||||
guard let trace = trace else { return }
|
||||
|
||||
switch mask {
|
||||
case SQLITE_TRACE_STMT:
|
||||
if let sqliteStatement = p, let unexpandedSQL = x {
|
||||
let statement = TraceEvent.Statement(impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: UnsafePointer(unexpandedSQL.assumingMemoryBound(to: CChar.self)),
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql))
|
||||
trace(TraceEvent.statement(statement))
|
||||
}
|
||||
case SQLITE_TRACE_PROFILE:
|
||||
if let sqliteStatement = p, let durationP = x?.assumingMemoryBound(to: Int64.self) {
|
||||
let statement = TraceEvent.Statement(impl: .trace_v2(
|
||||
sqliteStatement: OpaquePointer(sqliteStatement),
|
||||
unexpandedSQL: nil,
|
||||
sqlite3_expanded_sql: sqlite3_expanded_sql))
|
||||
let duration = TimeInterval(durationP.pointee) / 1.0e9
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
trace(TraceEvent.profile(statement: statement, duration: duration))
|
||||
#elseif os(Linux)
|
||||
#else
|
||||
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
|
||||
trace(TraceEvent.profile(statement: statement, duration: duration))
|
||||
}
|
||||
#endif
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - WAL Checkpoints
|
||||
|
||||
/// Runs a WAL checkpoint.
|
||||
///
|
||||
/// 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)
|
||||
/// - parameter dbName: The database name (default "main")
|
||||
/// - returns: A tuple:
|
||||
/// - `walFrameCount`: the total number of frames in the log file
|
||||
/// - `checkpointedFrameCount`: the total number of checkpointed frames
|
||||
/// in the log file
|
||||
@discardableResult
|
||||
public func checkpoint(_ kind: Database.CheckpointMode = .passive, on dbName: String? = "main") throws
|
||||
-> (walFrameCount: Int, checkpointedFrameCount: Int)
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
var walFrameCount: CInt = -1
|
||||
var checkpointedFrameCount: CInt = -1
|
||||
let code = sqlite3_wal_checkpoint_v2(sqliteConnection, dbName, kind.rawValue,
|
||||
&walFrameCount, &checkpointedFrameCount)
|
||||
switch code {
|
||||
case SQLITE_OK:
|
||||
return (walFrameCount: Int(walFrameCount), checkpointedFrameCount: Int(checkpointedFrameCount))
|
||||
case SQLITE_MISUSE:
|
||||
throw DatabaseError(resultCode: code)
|
||||
default:
|
||||
func checkpoint(_ kind: Database.CheckpointMode) throws {
|
||||
let code = sqlite3_wal_checkpoint_v2(sqliteConnection, nil, kind.rawValue, nil, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
}
|
||||
}
|
||||
@@ -739,7 +593,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
///
|
||||
/// Suspension ends with resume().
|
||||
func suspend() {
|
||||
$isSuspended.update { isSuspended in
|
||||
isSuspended.write { isSuspended in
|
||||
if isSuspended {
|
||||
return
|
||||
}
|
||||
@@ -766,7 +620,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
///
|
||||
/// See suspend().
|
||||
func resume() {
|
||||
isSuspended = false
|
||||
isSuspended.write { isSuspended in
|
||||
isSuspended = false
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for checkForSuspensionViolation(from:)
|
||||
@@ -794,7 +650,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// the database, in order to avoid the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
func checkForSuspensionViolation(from statement: Statement) throws {
|
||||
try $isSuspended.read { isSuspended in
|
||||
try isSuspended.read { isSuspended in
|
||||
guard isSuspended else {
|
||||
return
|
||||
}
|
||||
@@ -1449,112 +1305,6 @@ extension Database {
|
||||
/// log function that takes an error message.
|
||||
public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void
|
||||
|
||||
/// An option for `Database.trace(options:_:)`
|
||||
public struct TracingOptions: OptionSet {
|
||||
public let rawValue: CInt
|
||||
|
||||
public init(rawValue: CInt) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// Reports executed statements
|
||||
public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT)
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
/// Reports executed statements and the estimated duration that the
|
||||
/// statement took to run.
|
||||
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
|
||||
#elseif os(Linux)
|
||||
#else
|
||||
/// Reports executed statements and the estimated duration that the
|
||||
/// statement took to run.
|
||||
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
|
||||
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// An event reported by `Database.trace(options:_:)`
|
||||
public enum TraceEvent: CustomStringConvertible {
|
||||
|
||||
/// Information about a statement reported by `Database.trace(options:_:)`
|
||||
public struct Statement {
|
||||
enum Impl {
|
||||
case trace_v1(String)
|
||||
case trace_v2(
|
||||
sqliteStatement: SQLiteStatement,
|
||||
unexpandedSQL: UnsafePointer<CChar>?,
|
||||
sqlite3_expanded_sql: @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
|
||||
}
|
||||
let impl: Impl
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
/// The executed SQL.
|
||||
public var sql: String { _sql }
|
||||
#elseif os(Linux)
|
||||
#else
|
||||
/// The executed SQL.
|
||||
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
|
||||
public var sql: String { _sql }
|
||||
#endif
|
||||
|
||||
var _sql: String {
|
||||
switch impl {
|
||||
case .trace_v1:
|
||||
// Likely a GRDB bug
|
||||
fatalError("Not get statement SQL")
|
||||
|
||||
case let .trace_v2(sqliteStatement, unexpandedSQL, _):
|
||||
if let unexpandedSQL = unexpandedSQL {
|
||||
return String(cString: unexpandedSQL)
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
} else {
|
||||
return String(cString: sqlite3_sql(sqliteStatement))
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The executed SQL, with bound parameters expanded.
|
||||
public var expandedSQL: String {
|
||||
switch impl {
|
||||
case let .trace_v1(expandedSQL):
|
||||
return expandedSQL
|
||||
|
||||
case let .trace_v2(sqliteStatement, _, sqlite3_expanded_sql):
|
||||
guard let cString = sqlite3_expanded_sql(sqliteStatement) else {
|
||||
return ""
|
||||
}
|
||||
defer { sqlite3_free(cString) }
|
||||
return String(cString: cString)
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
case let .statement(statement):
|
||||
return statement.expandedSQL
|
||||
case let .profile(statement: statement, duration: duration):
|
||||
let durationString = String(format: "%.3f", duration)
|
||||
return "\(durationString)s \(statement.expandedSQL)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The end of a transaction: Commit, or Rollback
|
||||
public enum TransactionCompletion {
|
||||
case commit
|
||||
|
||||
@@ -223,9 +223,6 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
/// The SQL query that yielded the error (if relevant).
|
||||
public let sql: String?
|
||||
|
||||
/// The query arguments that yielded the error (if relevant).
|
||||
public let arguments: StatementArguments?
|
||||
|
||||
/// Creates a Database Error
|
||||
public init(
|
||||
resultCode: ResultCode = .SQLITE_ERROR,
|
||||
@@ -246,6 +243,12 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
init(resultCode: Int32, message: String? = nil, sql: String? = nil, arguments: StatementArguments? = nil) {
|
||||
self.init(resultCode: ResultCode(rawValue: resultCode), message: message, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
// MARK: Not public
|
||||
|
||||
/// The query arguments that yielded the error (if relevant).
|
||||
/// Not public because the StatementArguments class has no public method.
|
||||
let arguments: StatementArguments?
|
||||
}
|
||||
|
||||
// Support for `catch DatabaseError.SQLITE_XXX`
|
||||
|
||||
+72
-121
@@ -12,7 +12,7 @@ public final class DatabasePool: DatabaseWriter {
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
private var tokenizerRegistrations: [(Database) -> Void] = []
|
||||
|
||||
@LockedBox var databaseSnapshotCount = 0
|
||||
var databaseSnapshotCount = LockedBox(value: 0)
|
||||
|
||||
// MARK: - Database Information
|
||||
|
||||
@@ -80,9 +80,7 @@ public final class DatabasePool: DatabaseWriter {
|
||||
// setup a busy handler for pool readers, in order to workaround those
|
||||
// "obscure cases" that may happen when the database is shared between
|
||||
// multiple processes.
|
||||
if readerConfiguration.readonlyBusyMode == nil {
|
||||
readerConfiguration.readonlyBusyMode = .timeout(10)
|
||||
}
|
||||
readerConfiguration.busyMode = .timeout(10)
|
||||
|
||||
var readerCount = 0
|
||||
readerPool = Pool(maximumCount: configuration.maximumReaderCount, makeElement: { [unowned self] in
|
||||
@@ -139,12 +137,8 @@ public final class DatabasePool: DatabaseWriter {
|
||||
// Undo job done in setupMemoryManagement()
|
||||
//
|
||||
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
|
||||
// Explicit unregistration is required before OS X 10.11.
|
||||
// Explicit unregistration is required before iOS 9 and OS X 10.11.
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
|
||||
// Close reader connections before the writer connection.
|
||||
// Context: https://github.com/groue/GRDB.swift/issues/739
|
||||
readerPool = nil
|
||||
}
|
||||
|
||||
private func setupDatabase(_ db: Database) {
|
||||
@@ -167,6 +161,24 @@ public final class DatabasePool: DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - WAL Checkpoints
|
||||
|
||||
/// Runs a WAL checkpoint
|
||||
///
|
||||
/// 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)
|
||||
public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws {
|
||||
try writer.sync { db in
|
||||
try db.checkpoint(kind)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Memory management
|
||||
@@ -354,11 +366,8 @@ extension DatabasePool: DatabaseReader {
|
||||
public func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void) {
|
||||
// First async jump in order to grab a reader connection.
|
||||
// Honor configuration dispatching (qos/targetQueue).
|
||||
let label = configuration.identifier(
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "asyncRead")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.makeDispatchQueue(defaultLabel: "GRDB.DatabasePool", purpose: "asyncRead")
|
||||
.async {
|
||||
do {
|
||||
let (reader, releaseReader) = try self.readerPool.get()
|
||||
@@ -391,11 +400,8 @@ extension DatabasePool: DatabaseReader {
|
||||
public func _weakAsyncRead(_ block: @escaping (Result<Database, Error>?) -> Void) {
|
||||
// First async jump in order to grab a reader connection.
|
||||
// Honor configuration dispatching (qos/targetQueue).
|
||||
let label = configuration.identifier(
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "asyncRead")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.makeDispatchQueue(defaultLabel: "GRDB.DatabasePool", purpose: "asyncRead")
|
||||
.async { [weak self] in
|
||||
guard let self = self else {
|
||||
block(nil)
|
||||
@@ -854,133 +860,78 @@ extension DatabasePool: DatabaseReader {
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead")
|
||||
|
||||
let reduceQueueLabel = configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation")
|
||||
let observer = ValueObserver<Reducer>(
|
||||
requiresWriteAccess: observation.requiresWriteAccess,
|
||||
writer: self,
|
||||
reducer: observation.makeReducer(),
|
||||
scheduling: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
|
||||
reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"),
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
|
||||
// Starting a concurrent observation means that we'll fetch the initial
|
||||
// value right away, without waiting for an access to the writer queue,
|
||||
// and the opportunity to install a transaction observer.
|
||||
//
|
||||
// This is how DatabasePool can start an observation and promptly notify
|
||||
// an initial value, even when there is a long-running write transaction
|
||||
// in the background.
|
||||
//
|
||||
// We thus have to deal with the fact that between this initial fetch,
|
||||
// and the beginning of transaction tracking, any number of untracked
|
||||
// writes may occur.
|
||||
//
|
||||
// We must notify changes that happen during this untracked window. But
|
||||
// how do we spot them, since we're not tracking database changes yet?
|
||||
//
|
||||
// A safe solution is to always perform a second fetch. We may fetch the
|
||||
// same initial value, if no change did happen. But we don't miss
|
||||
// possible changes.
|
||||
//
|
||||
// We can avoid this second fetch when SQLite is compiled with the
|
||||
// SQLITE_ENABLE_SNAPSHOT option:
|
||||
//
|
||||
// 1. Perform the initial fetch in a DatabaseSnapshot. The snapshot
|
||||
// acquires a lock that will prevent checkpointing until we get a writer
|
||||
// access, so that we can reliably compare database versions with
|
||||
// `sqlite3_snapshot`: https://www.sqlite.org/c3ref/snapshot.html.
|
||||
//
|
||||
// 2. Get a writer access, and compare the versions of the initial
|
||||
// snapshot, and the current state of the database: if versions are
|
||||
// identical, we can avoid the second fetch. If they are not, we perform
|
||||
// the second fetch, even if the actual changes are unrelated to the
|
||||
// tracked database region (we have no way to know).
|
||||
//
|
||||
// 3. Install the transaction observer.
|
||||
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
let initialSnapshot = try makeSnapshot()
|
||||
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
|
||||
// Fetch the initial value without waiting for the writer.
|
||||
let initialValue = try unsafeReentrantRead(observer.fetchInitialValue)
|
||||
onChange(initialValue)
|
||||
add(observer: observer, from: initialSnapshot)
|
||||
|
||||
// Now wait for the writer
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
do {
|
||||
// Don't miss eventual changes between the
|
||||
// initial fetch and the writer access.
|
||||
if let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
}
|
||||
|
||||
// Now we can start observation
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
observer.cancel()
|
||||
onError(error)
|
||||
}
|
||||
} else {
|
||||
let label = configuration.identifier(
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "ValueObservation")
|
||||
configuration
|
||||
.makeDispatchQueue(label: label)
|
||||
.async { [weak self] in
|
||||
guard let self = self else { return }
|
||||
if observer.isCompleted { return }
|
||||
// Fetch the initial value without waiting for the writer.
|
||||
_weakAsyncRead { [weak self] dbResult in
|
||||
guard let dbResult = dbResult else { return }
|
||||
guard let self = self else { return }
|
||||
if observer.isCompleted { return }
|
||||
do {
|
||||
let initialValue = try observer.fetchInitialValue(dbResult.get())
|
||||
observer.notifyChange(initialValue)
|
||||
|
||||
do {
|
||||
let initialSnapshot = try self.makeSnapshot()
|
||||
let initialValue = try initialSnapshot.read(observer.fetchInitialValue)
|
||||
observer.notifyChange(initialValue)
|
||||
self.add(observer: observer, from: initialSnapshot)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
// Now wait for the writer
|
||||
self._weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
do {
|
||||
// Don't miss eventual changes between the
|
||||
// initial fetch and the writer access.
|
||||
if let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
}
|
||||
|
||||
// Now we can start observation
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return observer
|
||||
}
|
||||
|
||||
// Support for _addConcurrent(observation:)
|
||||
private func add<Reducer: _ValueReducer>(
|
||||
observer: ValueObserver<Reducer>,
|
||||
from initialSnapshot: DatabaseSnapshot)
|
||||
{
|
||||
_weakAsyncWriteWithoutTransaction { db in
|
||||
guard let db = db else { return }
|
||||
if observer.isCompleted { return }
|
||||
|
||||
do {
|
||||
// Transaction is needed for version snapshotting
|
||||
try db.inTransaction(.deferred) {
|
||||
// Keep DatabaseSnaphot alive until we have compared
|
||||
// database versions. It prevents database checkpointing,
|
||||
// and keeps versions (`sqlite3_snapshot`) valid
|
||||
// and comparable.
|
||||
let fetchNeeded: Bool = withExtendedLifetime(initialSnapshot) {
|
||||
// Version is nil if SQLite is not compiled with
|
||||
// SQLITE_ENABLE_SNAPSHOT, or if the DatabaseSnaphot
|
||||
// could not grab its version. In this case, we don't
|
||||
// care, and just fetch a fresh value.
|
||||
guard let initialVersion = initialSnapshot.version else {
|
||||
return true
|
||||
}
|
||||
do {
|
||||
return try db.wasChanged(since: initialVersion)
|
||||
} catch {
|
||||
// ignore: we'll just re-fetch
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
if fetchNeeded, let value = try observer.fetchValue(db) {
|
||||
observer.notifyChange(value)
|
||||
}
|
||||
return .commit
|
||||
}
|
||||
|
||||
// Now we can start observation
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
} catch {
|
||||
observer.notifyErrorAndComplete(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Custom FTS5 Tokenizers
|
||||
|
||||
#if SQLITE_ENABLE_FTS5
|
||||
@@ -1074,7 +1025,7 @@ extension DatabasePool {
|
||||
path: path,
|
||||
configuration: writer.configuration,
|
||||
defaultLabel: "GRDB.DatabasePool",
|
||||
purpose: "snapshot.\($databaseSnapshotCount.increment())")
|
||||
purpose: "snapshot.\(databaseSnapshotCount.increment())")
|
||||
snapshot.read { setupDatabase($0) }
|
||||
return snapshot
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
// Undo job done in setupMemoryManagement()
|
||||
//
|
||||
// https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/index.html#10_11Error
|
||||
// Explicit unregistration is required before OS X 10.11.
|
||||
// Explicit unregistration is required before iOS 9 and OS X 10.11.
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,9 +14,6 @@ public class DatabaseSnapshot: DatabaseReader {
|
||||
serializedDatabase.configuration
|
||||
}
|
||||
|
||||
/// Not nil iff SQLite was compiled with `SQLITE_ENABLE_SNAPSHOT`.
|
||||
private(set) var version: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
|
||||
var configuration = configuration
|
||||
configuration.readonly = true
|
||||
@@ -36,16 +33,12 @@ public class DatabaseSnapshot: DatabaseReader {
|
||||
throw DatabaseError(message: "WAL mode is not activated at path: \(path)")
|
||||
}
|
||||
try db.beginSnapshotTransaction()
|
||||
version = try? db.takeVersionSnapshot()
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
serializedDatabase.reentrantSync { db in
|
||||
if let version = version {
|
||||
grdb_snapshot_free(version)
|
||||
}
|
||||
serializedDatabase.sync { db in
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,16 +224,18 @@ extension DatabaseValue {
|
||||
extension DatabaseValue {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
// fast path for NULL
|
||||
if isNull {
|
||||
// fast path for NULL
|
||||
return "NULL"
|
||||
} else if context.append(arguments: [self]) {
|
||||
// Use statement arguments
|
||||
}
|
||||
|
||||
if context.append(arguments: [self]) {
|
||||
return "?"
|
||||
} else {
|
||||
// Quoting needed: just use SQLite, which knows better.
|
||||
return try String.fetchOne(context.db, sql: "SELECT QUOTE(?)", arguments: [self])!
|
||||
// Correctness above all: use SQLite to quote the value.
|
||||
// Assume that the Quote function always succeeds
|
||||
return DatabaseQueue().inDatabase { try! String.fetchOne($0, sql: "SELECT QUOTE(?)", arguments: [self])! }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ struct ValueConversionContext: Refinable {
|
||||
case .columnIndex(let index):
|
||||
return index
|
||||
case .columnName(let name):
|
||||
return row?.index(forColumn: name)
|
||||
return row?.index(ofColumn: name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -318,15 +318,12 @@ extension DatabaseWriter {
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
|
||||
let reduceQueueLabel = configuration.identifier(
|
||||
defaultLabel: "GRDB",
|
||||
purpose: "ValueObservation")
|
||||
let observer = ValueObserver<Reducer>(
|
||||
requiresWriteAccess: observation.requiresWriteAccess,
|
||||
writer: self,
|
||||
reducer: observation.makeReducer(),
|
||||
scheduling: scheduler,
|
||||
reduceQueue: configuration.makeDispatchQueue(label: reduceQueueLabel),
|
||||
reduceQueue: configuration.makeDispatchQueue(defaultLabel: "GRDB", purpose: "ValueObservation.reducer"),
|
||||
onError: onError,
|
||||
onChange: onChange)
|
||||
|
||||
|
||||
+39
-129
@@ -11,7 +11,6 @@ public struct PreparedRequest {
|
||||
/// Support for eager loading of hasMany associations.
|
||||
var supplementaryFetch: (([Row]) throws -> Void)?
|
||||
|
||||
// TODO: remove when FetchRequest is a closed protocol.
|
||||
/// Creates a PreparedRequest.
|
||||
///
|
||||
/// - parameter statement: A prepared statement that is ready to
|
||||
@@ -34,21 +33,8 @@ public struct PreparedRequest {
|
||||
self.adapter = adapter
|
||||
self.supplementaryFetch = supplementaryFetch
|
||||
}
|
||||
|
||||
// TODO: remove when FetchRequest is a closed protocol.
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the request SQL.
|
||||
///
|
||||
/// - parameter context: An SQL generation context.
|
||||
/// - returns: An SQL string.
|
||||
public func requestSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try SQLLiteral(sql: statement.sql, arguments: statement.arguments).sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
extension PreparedRequest: Refinable { }
|
||||
|
||||
// MARK: - FetchRequest
|
||||
|
||||
/// The protocol for all requests that fetch database rows, and tell how those
|
||||
@@ -59,27 +45,7 @@ extension PreparedRequest: Refinable { }
|
||||
/// try request.fetchCursor(db) // Cursor of Player
|
||||
/// try request.fetchAll(db) // [Player]
|
||||
/// try request.fetchOne(db) // Player?
|
||||
/// try request.fetchCount(db) // Int
|
||||
///
|
||||
/// To build a custom FetchRequest, declare a type with the `RowDecoder`
|
||||
/// associated type, and implement the `requestSQL(_:forSingleResult:)` method
|
||||
/// with the help of SQLLiteral.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct PlayerRequest: FetchRequest {
|
||||
/// typealias RowDecoder = Player
|
||||
/// var id: Int64
|
||||
/// func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
/// let query: SQLLiteral = "SELECT * FROM player WHERE id = \(id)"
|
||||
/// return try query.sql(context)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let player = try dbQueue.read { db in
|
||||
/// try PlayerRequest(id: 42).fetchOne(db)
|
||||
/// }
|
||||
public protocol FetchRequest: SQLRequestProtocol, DatabaseRegionConvertible {
|
||||
public protocol FetchRequest: DatabaseRegionConvertible {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
@@ -87,79 +53,57 @@ public protocol FetchRequest: SQLRequestProtocol, DatabaseRegionConvertible {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter singleResult: A hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use it to optimize the
|
||||
/// prepared statement, for example by adding a `LIMIT 1` SQL clause.
|
||||
///
|
||||
/// // Calls makePreparedRequest(db, forSingleResult: true)
|
||||
/// try request.fetchOne(db)
|
||||
///
|
||||
/// // Calls makePreparedRequest(db, forSingleResult: false)
|
||||
/// try request.fetchAll(db)
|
||||
/// consumed. Implementations can optionally use this to optimize the
|
||||
/// prepared statement.
|
||||
/// - returns: A prepared request.
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// The default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `prepare` method:
|
||||
/// `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// Adopting types can refine this method in order to use more
|
||||
/// efficient SQL.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
extension FetchRequest {
|
||||
|
||||
/// Returns an adapted request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
AdaptedFetchRequest(self, adapter)
|
||||
}
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// The default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `requestSQL(_:forSingleResult:)` method:
|
||||
/// `SELECT COUNT(*) FROM (...)`.
|
||||
/// This default implementation builds a naive SQL query based on the
|
||||
/// statement returned by the `prepare` method: `SELECT COUNT(*) FROM (...)`.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try requestSQL(context, forSingleResult: false)
|
||||
let countSQL = "SELECT COUNT(*) FROM (\(sql))"
|
||||
return try Int.fetchOne(db, sql: countSQL, arguments: context.arguments)!
|
||||
let request = try makePreparedRequest(db, forSingleResult: false)
|
||||
let sql = "SELECT COUNT(*) FROM (\(request.statement.sql))"
|
||||
return try Int.fetchOne(db, sql: sql, arguments: request.statement.arguments)!
|
||||
}
|
||||
|
||||
/// Returns the database region that the request looks into.
|
||||
///
|
||||
/// This default implementation returns a region built from the statement
|
||||
/// returned by the `requestSQL(_:forSingleResult)` method.
|
||||
/// returned by the `prepare` method.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try requestSQL(context, forSingleResult: false)
|
||||
let statement = try db.makeSelectStatement(sql: sql)
|
||||
return statement.databaseRegion
|
||||
}
|
||||
|
||||
/// Returns a PreparedRequest that is ready to be executed.
|
||||
///
|
||||
/// This default implementation returns a request built from the
|
||||
/// `requestSQL(_:forSingleResult)` method.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter singleResult: A hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use this to optimize the
|
||||
/// prepared statement.
|
||||
/// - returns: A prepared request.
|
||||
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try requestSQL(context, forSingleResult: singleResult)
|
||||
let statement = try db.makeSelectStatement(sql: sql)
|
||||
statement.arguments = context.arguments
|
||||
return PreparedRequest(statement: statement)
|
||||
let request = try makePreparedRequest(db, forSingleResult: false)
|
||||
return request.statement.selectedRegion
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AdaptedFetchRequest
|
||||
|
||||
extension FetchRequest {
|
||||
/// Returns an adapted request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
AdaptedFetchRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
/// An adapted request.
|
||||
public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
@@ -174,12 +118,6 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try base.requestSQL(context, forSingleResult: singleResult)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
var request = try base.makePreparedRequest(db, forSingleResult: singleResult)
|
||||
@@ -208,60 +146,32 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
///
|
||||
/// An AnyFetchRequest forwards its operations to an underlying request,
|
||||
/// hiding its specifics.
|
||||
public struct AnyFetchRequest<RowDecoder>: FetchRequest {
|
||||
// DatabaseRegionConvertible
|
||||
public struct AnyFetchRequest<T>: FetchRequest {
|
||||
public typealias RowDecoder = T
|
||||
|
||||
private let _preparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest
|
||||
private let _fetchCount: (Database) throws -> Int
|
||||
private let _databaseRegion: (Database) throws -> DatabaseRegion
|
||||
|
||||
// SQLRequestProtocol
|
||||
private let _requestSQL: (SQLGenerationContext, _ singleResult: Bool) throws -> String
|
||||
|
||||
// FetchRequest
|
||||
private let _makePreparedRequest: (Database, _ singleResult: Bool) throws -> PreparedRequest
|
||||
private let _fetchCount: (Database) throws -> Int
|
||||
|
||||
/// Creates a request bound to type RowDecoder.
|
||||
///
|
||||
/// - parameter type: The fetched type RowDecoder
|
||||
/// - returns: A request bound to type RowDecoder.
|
||||
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> AnyFetchRequest<RowDecoder> {
|
||||
AnyFetchRequest<RowDecoder>(
|
||||
_databaseRegion: _databaseRegion,
|
||||
_requestSQL: _requestSQL,
|
||||
_makePreparedRequest: _makePreparedRequest,
|
||||
_fetchCount: _fetchCount)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
try _databaseRegion(db)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try _requestSQL(context, singleResult)
|
||||
/// Creates a request that wraps and forwards operations to `request`.
|
||||
public init<Request: FetchRequest>(_ request: Request) {
|
||||
_preparedRequest = request.makePreparedRequest
|
||||
_fetchCount = request.fetchCount
|
||||
_databaseRegion = request.databaseRegion
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
try _makePreparedRequest(db, singleResult)
|
||||
try _preparedRequest(db, singleResult)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try _fetchCount(db)
|
||||
}
|
||||
}
|
||||
|
||||
extension AnyFetchRequest {
|
||||
/// Creates a request that wraps and forwards operations to `request`.
|
||||
public init<Request: FetchRequest>(_ request: Request)
|
||||
where Request.RowDecoder == RowDecoder
|
||||
{
|
||||
self.init(
|
||||
_databaseRegion: request.databaseRegion,
|
||||
_requestSQL: request.requestSQL,
|
||||
_makePreparedRequest: request.makePreparedRequest,
|
||||
_fetchCount: request.fetchCount)
|
||||
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
try _databaseRegion(db)
|
||||
}
|
||||
}
|
||||
+15
-15
@@ -140,12 +140,12 @@ extension Row {
|
||||
///
|
||||
/// This method is case-insensitive.
|
||||
public func hasColumn(_ columnName: String) -> Bool {
|
||||
index(forColumn: columnName) != nil
|
||||
index(ofColumn: columnName) != nil
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func index(forColumn name: String) -> Int? {
|
||||
impl.index(forColumn: name)
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
impl.index(ofColumn: name)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,7 +282,7 @@ extension Row {
|
||||
// if row["foo"] != nil { ... }
|
||||
//
|
||||
// Without this method, the code above would not compile.
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
guard let index = index(ofColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return impl.databaseValue(atUncheckedIndex: index).storage.value
|
||||
@@ -298,7 +298,7 @@ extension Row {
|
||||
/// `Value`. Should this conversion fail, a fatal error is raised.
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value? {
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
guard let index = index(ofColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return Value.decodeIfPresent(from: self, atUncheckedIndex: index)
|
||||
@@ -318,7 +318,7 @@ extension Row {
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value? {
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
guard let index = index(ofColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return Value.fastDecodeIfPresent(from: self, atUncheckedIndex: index)
|
||||
@@ -335,7 +335,7 @@ extension Row {
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
guard let index = index(ofColumn: columnName) else {
|
||||
// No such column
|
||||
fatalConversionError(to: Value.self, from: nil, in: self, atColumn: columnName)
|
||||
}
|
||||
@@ -357,7 +357,7 @@ extension Row {
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
guard let index = index(ofColumn: columnName) else {
|
||||
// No such column
|
||||
fatalConversionError(to: Value.self, from: nil, in: self, atColumn: columnName)
|
||||
}
|
||||
@@ -475,7 +475,7 @@ extension Row {
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
public func dataNoCopy(named columnName: String) -> Data? {
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
guard let index = index(ofColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return impl.dataNoCopy(atUncheckedIndex: index)
|
||||
@@ -1582,7 +1582,7 @@ protocol RowImpl {
|
||||
func dataNoCopy(atUncheckedIndex index: Int) -> Data?
|
||||
|
||||
/// Returns the index of the leftmost column that matches *name* (case-insensitive)
|
||||
func index(forColumn name: String) -> Int?
|
||||
func index(ofColumn name: String) -> Int?
|
||||
|
||||
// row.impl is guaranteed to be self.
|
||||
func unscopedRow(_ row: Row) -> Row
|
||||
@@ -1665,7 +1665,7 @@ private struct ArrayRowImpl: RowImpl {
|
||||
columns[index].0
|
||||
}
|
||||
|
||||
func index(forColumn name: String) -> Int? {
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
let lowercaseName = name.lowercased()
|
||||
return columns.firstIndex { (column, _) in column.lowercased() == lowercaseName }
|
||||
}
|
||||
@@ -1703,7 +1703,7 @@ private struct StatementCopyRowImpl: RowImpl {
|
||||
columnNames[index]
|
||||
}
|
||||
|
||||
func index(forColumn name: String) -> Int? {
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
let lowercaseName = name.lowercased()
|
||||
return columnNames.firstIndex { $0.lowercased() == lowercaseName }
|
||||
}
|
||||
@@ -1777,7 +1777,7 @@ private struct StatementRowImpl: RowImpl {
|
||||
statement.columnNames[index]
|
||||
}
|
||||
|
||||
func index(forColumn name: String) -> Int? {
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
if let index = lowercaseColumnIndexes[name] {
|
||||
return index
|
||||
}
|
||||
@@ -1814,7 +1814,7 @@ private struct SQLiteStatementRowImpl: RowImpl {
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
func index(forColumn name: String) -> Int? {
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
let name = name.lowercased()
|
||||
for index in 0..<count where columnName(atUncheckedIndex: index).lowercased() == name {
|
||||
return index
|
||||
@@ -1839,7 +1839,7 @@ private struct EmptyRowImpl: RowImpl {
|
||||
fatalError("row index out of range")
|
||||
}
|
||||
|
||||
func index(forColumn name: String) -> Int? { nil }
|
||||
func index(ofColumn name: String) -> Int? { nil }
|
||||
|
||||
func copiedRow(_ row: Row) -> Row { row }
|
||||
}
|
||||
@@ -523,7 +523,7 @@ struct AdaptedRowImpl: RowImpl {
|
||||
mapping.columnName(atMappingIndex: index)
|
||||
}
|
||||
|
||||
func index(forColumn name: String) -> Int? {
|
||||
func index(ofColumn name: String) -> Int? {
|
||||
mapping.layoutIndex(ofColumn: name)
|
||||
}
|
||||
|
||||
|
||||
+39
-38
@@ -14,39 +14,34 @@ public struct SQLLiteral {
|
||||
/// table aliases.
|
||||
enum Element {
|
||||
case sql(String, StatementArguments = StatementArguments())
|
||||
case subquery(SQLRequestProtocol)
|
||||
// Cases below can be qualified with a table alias
|
||||
case expression(SQLExpression)
|
||||
case selectable(SQLSelectable)
|
||||
case orderingTerm(SQLOrderingTerm)
|
||||
case subQuery(SQLLiteral)
|
||||
|
||||
fileprivate func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
fileprivate func sql(_ context: inout SQLGenerationContext) -> 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
|
||||
// GRDB limitation: 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")
|
||||
fatalError("Not implemented")
|
||||
}
|
||||
return sql
|
||||
case let .subquery(request):
|
||||
return try request.requestSQL(context, forSingleResult: false)
|
||||
case let .expression(expression):
|
||||
return try expression.expressionSQL(context, wrappedInParenthesis: false)
|
||||
return expression.expressionSQL(&context, wrappedInParenthesis: false)
|
||||
case let .selectable(selectable):
|
||||
return try selectable.resultColumnSQL(context)
|
||||
return selectable.resultColumnSQL(&context)
|
||||
case let .orderingTerm(orderingTerm):
|
||||
return try orderingTerm.orderingTermSQL(context)
|
||||
return orderingTerm.orderingTermSQL(&context)
|
||||
case let .subQuery(sqlLiteral):
|
||||
return "(" + sqlLiteral.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.qualifiedExpression(with: alias))
|
||||
@@ -54,10 +49,24 @@ public struct SQLLiteral {
|
||||
return .selectable(selectable.qualifiedSelectable(with: alias))
|
||||
case let .orderingTerm(orderingTerm):
|
||||
return .orderingTerm(orderingTerm.qualifiedOrdering(with: alias))
|
||||
case .subQuery:
|
||||
// subqueries are not requalified
|
||||
return self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public var sql: String {
|
||||
var context = SQLGenerationContext.sqlLiteralContext
|
||||
return sql(&context)
|
||||
}
|
||||
|
||||
public var arguments: StatementArguments {
|
||||
var context = SQLGenerationContext.sqlLiteralContext
|
||||
_ = sql(&context)
|
||||
return context.arguments
|
||||
}
|
||||
|
||||
private(set) var elements: [Element]
|
||||
|
||||
init(elements: [Element]) {
|
||||
@@ -88,22 +97,8 @@ public struct SQLLiteral {
|
||||
self.init(elements: [.expression(expression)])
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
// TODO: make internal when FetchRequest is a closed protocol.
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the literal SQL string given an SQL generation context.
|
||||
public func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
try elements.map { try $0.sql(context) }.joined()
|
||||
func sql(_ context: inout SQLGenerationContext) -> String {
|
||||
elements.map { $0.sql(&context) }.joined()
|
||||
}
|
||||
|
||||
fileprivate func qualified(with alias: TableAlias) -> SQLLiteral {
|
||||
@@ -235,6 +230,8 @@ extension SQLLiteral: ExpressibleByStringInterpolation {
|
||||
|
||||
// MARK: - _SQLExpressionLiteral
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLExpressionLiteral is an expression built from a raw SQL snippet.
|
||||
///
|
||||
/// SQLExpressionLiteral(sql: "1 + 2")
|
||||
@@ -251,13 +248,17 @@ private struct _SQLExpressionLiteral: SQLExpression {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
if wrappedInParenthesis {
|
||||
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
|
||||
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
|
||||
}
|
||||
return try sqlLiteral.sql(context)
|
||||
return sqlLiteral.sql(&context)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
sqlLiteral.qualified(with: alias).sqlExpression
|
||||
}
|
||||
@@ -273,11 +274,11 @@ private struct _SQLSelectionLiteral: SQLSelectable {
|
||||
self.sqlLiteral = sqlLiteral
|
||||
}
|
||||
|
||||
func resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try sqlLiteral.sql(context)
|
||||
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
sqlLiteral.sql(&context)
|
||||
}
|
||||
|
||||
func countedSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
func countedSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
fatalError("""
|
||||
Selection literals can't be counted. \
|
||||
To resolve this error, select one or several literal expressions instead. \
|
||||
@@ -323,8 +324,8 @@ private struct _SQLOrderingLiteral: SQLOrderingTerm {
|
||||
""")
|
||||
}
|
||||
|
||||
func orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try sqlLiteral.sql(context)
|
||||
func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
sqlLiteral.sql(&context)
|
||||
}
|
||||
|
||||
func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
|
||||
|
||||
+48
-19
@@ -1,5 +1,5 @@
|
||||
/// A FetchRequest built from raw SQL.
|
||||
public struct SQLRequest<RowDecoder> {
|
||||
public struct SQLRequest<T>: FetchRequest {
|
||||
/// There are two statement caches: one "public" for statements generated by
|
||||
/// the user, and one "internal" for the statements generated by GRDB. Those
|
||||
/// are separated so that GRDB has no opportunity to inadvertently modify
|
||||
@@ -12,6 +12,22 @@ public struct SQLRequest<RowDecoder> {
|
||||
case `internal`
|
||||
}
|
||||
|
||||
public typealias RowDecoder = T
|
||||
|
||||
/// The raw SQL query
|
||||
///
|
||||
/// let id = 42
|
||||
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
|
||||
/// request.sql // "SELECT * FROM player WHERE id = ?"
|
||||
public var sql: String { sqlLiteral.sql }
|
||||
|
||||
/// The request argument
|
||||
///
|
||||
/// let id = 42
|
||||
/// let request: SQLRequest<Player> = "SELECT * FROM player WHERE id = \(id)"
|
||||
/// request.arguments // [42]
|
||||
public var arguments: StatementArguments { sqlLiteral.arguments }
|
||||
|
||||
/// The request adapter
|
||||
public var adapter: RowAdapter?
|
||||
|
||||
@@ -73,6 +89,28 @@ public struct SQLRequest<RowDecoder> {
|
||||
self.init(literal: sqlLiteral, adapter: adapter, fromCache: cached ? .public : nil)
|
||||
}
|
||||
|
||||
/// Creates an SQL request from any other fetch request.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A request.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: An SQLRequest
|
||||
public init<Request>(
|
||||
_ db: Database,
|
||||
request: Request,
|
||||
cached: Bool = false)
|
||||
throws
|
||||
where Request: FetchRequest, Request.RowDecoder == RowDecoder
|
||||
{
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
self.init(
|
||||
literal: SQLLiteral(sql: request.statement.sql, arguments: request.statement.arguments),
|
||||
adapter: request.adapter,
|
||||
cached: cached)
|
||||
}
|
||||
|
||||
/// Creates a request from an SQLLiteral, and optional row adapter.
|
||||
///
|
||||
/// let request = SQLRequest<String>(literal: SQLLiteral(sql: """
|
||||
@@ -99,26 +137,17 @@ public struct SQLRequest<RowDecoder> {
|
||||
self.adapter = adapter
|
||||
self.cache = cache
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRequest: SQLRequestProtocol {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
/// A tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter singleResult: SQLRequest disregards this hint.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
try sqlLiteral.sql(context)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRequest: DatabaseRegionConvertible {
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRequest: FetchRequest {
|
||||
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
var context = SQLGenerationContext.sqlLiteralContext
|
||||
let sql = sqlLiteral.sql(&context)
|
||||
let statement: SelectStatement
|
||||
switch cache {
|
||||
case .none:
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
/// The protocol that can generate SQL requests and subqueries.
|
||||
public protocol SQLRequestProtocol: SQLExpression, SQLCollection {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns the request SQL.
|
||||
///
|
||||
/// - 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.
|
||||
func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String
|
||||
}
|
||||
|
||||
// MARK: - SQLExpression
|
||||
|
||||
extension SQLRequestProtocol {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
let sql = try requestSQL(context, forSingleResult: false)
|
||||
return "(\(sql))"
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLCollection
|
||||
|
||||
extension SQLRequestProtocol {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func collectionSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try requestSQL(context, forSingleResult: false)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func qualifiedCollection(with alias: TableAlias) -> SQLCollection {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -43,13 +43,8 @@ final class SerializedDatabase {
|
||||
config.threadingMode = .multiThread
|
||||
|
||||
self.path = path
|
||||
let identifier = configuration.identifier(defaultLabel: defaultLabel, purpose: purpose)
|
||||
self.db = try Database(
|
||||
path: path,
|
||||
description: identifier,
|
||||
configuration: config,
|
||||
schemaCache: schemaCache)
|
||||
self.queue = configuration.makeDispatchQueue(label: identifier)
|
||||
self.db = try Database(path: path, configuration: config, schemaCache: schemaCache)
|
||||
self.queue = configuration.makeDispatchQueue(defaultLabel: defaultLabel, purpose: purpose)
|
||||
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
|
||||
try queue.sync {
|
||||
do {
|
||||
|
||||
@@ -24,12 +24,11 @@ public class Statement {
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
}
|
||||
|
||||
// Database region is computed during statement compilation, and maybe
|
||||
// extended for select statements compiled by QueryInterfaceRequest, in
|
||||
// Selected region is computed during statement compilation, and maybe
|
||||
// optimized for select statements compiled by QueryInterfaceRequest, in
|
||||
// order to perform focused database observation. See
|
||||
// SQLQueryGenerator.makeSelectStatement(_:)
|
||||
/// The database region that the statement looks into.
|
||||
public internal(set) var databaseRegion = DatabaseRegion()
|
||||
// SQLQueryGenerator.optimizedSelectedRegion(_:_:)
|
||||
var selectedRegion = DatabaseRegion()
|
||||
|
||||
var isReadonly: Bool {
|
||||
sqlite3_stmt_readonly(sqliteStatement) != 0
|
||||
@@ -88,7 +87,7 @@ public class Statement {
|
||||
|
||||
self.database = database
|
||||
self.sqliteStatement = statement
|
||||
self.databaseRegion = authorizer.selectedRegion
|
||||
self.selectedRegion = authorizer.selectedRegion
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -357,6 +356,9 @@ public final class SelectStatement: Statement {
|
||||
"Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
}
|
||||
|
||||
/// The database region that the statement looks into.
|
||||
public var databaseRegion: DatabaseRegion { selectedRegion }
|
||||
|
||||
/// The number of columns in the resulting rows.
|
||||
public var columnCount: Int {
|
||||
Int(sqlite3_column_count(self.sqliteStatement))
|
||||
|
||||
@@ -1,21 +1,3 @@
|
||||
/// 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 {
|
||||
public var sqlExpression: SQLExpression {
|
||||
rawValue.sqlExpression
|
||||
}
|
||||
}
|
||||
|
||||
/// DatabaseValueConvertible is free for RawRepresentable types whose raw value
|
||||
/// is itself DatabaseValueConvertible.
|
||||
///
|
||||
|
||||
@@ -554,7 +554,7 @@ extension DatabaseFunction {
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(OSX 10.11, watchOS 3.0, *)
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedCapitalize =
|
||||
DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -575,7 +575,7 @@ extension DatabaseFunction {
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedLowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(OSX 10.11, watchOS 3.0, *)
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedLowercase =
|
||||
DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -596,7 +596,7 @@ extension DatabaseFunction {
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedUppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(OSX 10.11, watchOS 3.0, *)
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedUppercase =
|
||||
DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
|
||||
@@ -283,17 +283,6 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
} else {
|
||||
@@ -507,7 +496,6 @@ class DatabaseObservationBroker {
|
||||
/// Remove transaction observers that have stopped observing transaction,
|
||||
/// and uninstall SQLite update hooks if there is no remaining observers.
|
||||
private func databaseDidEndTransaction() {
|
||||
assert(!database.isInsideTransaction)
|
||||
transactionObservations = transactionObservations.filter(\.isObserving)
|
||||
|
||||
// Undo disableUntilNextTransaction(transactionObserver:)
|
||||
|
||||
@@ -19,10 +19,8 @@ public struct FTS3Pattern {
|
||||
// that pattern.
|
||||
do {
|
||||
try DatabaseQueue().inDatabase { db in
|
||||
try db.execute(literal: """
|
||||
CREATE VIRTUAL TABLE documents USING fts3();
|
||||
SELECT * FROM documents WHERE content MATCH \(rawPattern);
|
||||
""")
|
||||
try db.execute(sql: "CREATE VIRTUAL TABLE documents USING fts3()")
|
||||
try db.execute(sql: "SELECT * FROM documents WHERE content MATCH ?", arguments: [rawPattern])
|
||||
}
|
||||
} catch let error as DatabaseError {
|
||||
// Remove private SQL & arguments from the thrown error
|
||||
|
||||
+8
-8
@@ -69,40 +69,40 @@ public struct FTS5: VirtualTableModule {
|
||||
}
|
||||
|
||||
if let tokenizer = definition.tokenizer {
|
||||
let tokenizerSQL = try tokenizer
|
||||
let tokenizerSQL = tokenizer
|
||||
.components
|
||||
.joined(separator: " ")
|
||||
.sqlExpression
|
||||
.quotedSQL(db)
|
||||
.quotedSQL()
|
||||
arguments.append("tokenize=\(tokenizerSQL)")
|
||||
}
|
||||
|
||||
switch definition.contentMode {
|
||||
case let .raw(content, contentRowID):
|
||||
if let content = content {
|
||||
let quotedContent = try content.sqlExpression.quotedSQL(db)
|
||||
let quotedContent = content.sqlExpression.quotedSQL()
|
||||
arguments.append("content=\(quotedContent)")
|
||||
}
|
||||
if let contentRowID = contentRowID {
|
||||
let quotedContentRowID = try contentRowID.sqlExpression.quotedSQL(db)
|
||||
let quotedContentRowID = contentRowID.sqlExpression.quotedSQL()
|
||||
arguments.append("content_rowid=\(quotedContentRowID)")
|
||||
}
|
||||
case let .synchronized(contentTable):
|
||||
try arguments.append("content=\(contentTable.sqlExpression.quotedSQL(db))")
|
||||
arguments.append("content=\(contentTable.sqlExpression.quotedSQL())")
|
||||
if let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn {
|
||||
let quotedRowID = try rowIDColumn.sqlExpression.quotedSQL(db)
|
||||
let quotedRowID = rowIDColumn.sqlExpression.quotedSQL()
|
||||
arguments.append("content_rowid=\(quotedRowID)")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if let prefixes = definition.prefixes {
|
||||
let prefix = try prefixes
|
||||
let prefix = prefixes
|
||||
.sorted()
|
||||
.map { "\($0)" }
|
||||
.joined(separator: " ")
|
||||
.sqlExpression
|
||||
.quotedSQL(db)
|
||||
.quotedSQL()
|
||||
arguments.append("prefix=\(prefix)")
|
||||
}
|
||||
|
||||
|
||||
@@ -59,17 +59,14 @@ public struct FTS5TokenizerDescriptor {
|
||||
if separators.isEmpty {
|
||||
components = ["ascii"]
|
||||
} else {
|
||||
components = DatabaseQueue().inDatabase { db in
|
||||
// Assume quoting a string never fails
|
||||
try! [
|
||||
"ascii",
|
||||
"separators",
|
||||
separators
|
||||
.map { String($0) }
|
||||
.joined()
|
||||
.sqlExpression
|
||||
.quotedSQL(db)]
|
||||
}
|
||||
components = [
|
||||
"ascii",
|
||||
"separators",
|
||||
separators
|
||||
.map { String($0) }
|
||||
.joined()
|
||||
.sqlExpression
|
||||
.quotedSQL()]
|
||||
}
|
||||
return FTS5TokenizerDescriptor(components: components)
|
||||
}
|
||||
@@ -129,37 +126,29 @@ public struct FTS5TokenizerDescriptor {
|
||||
// TODO: test "=" and "\"", "(" and ")" as separators, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
let separatorComponents = DatabaseQueue().inDatabase { db in
|
||||
// Assume quoting a string never fails
|
||||
try! [
|
||||
"separators",
|
||||
separators
|
||||
.sorted()
|
||||
.map { String($0) }
|
||||
.joined()
|
||||
.sqlExpression
|
||||
.quotedSQL(db)
|
||||
]
|
||||
}
|
||||
components.append(contentsOf: separatorComponents)
|
||||
components.append(contentsOf: [
|
||||
"separators",
|
||||
separators
|
||||
.sorted()
|
||||
.map { String($0) }
|
||||
.joined()
|
||||
.sqlExpression
|
||||
.quotedSQL()
|
||||
])
|
||||
}
|
||||
if !tokenCharacters.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
let tokenCharactersComponents = DatabaseQueue().inDatabase { db in
|
||||
// Assume quoting a string never fails
|
||||
try! [
|
||||
"tokenchars",
|
||||
tokenCharacters
|
||||
.sorted()
|
||||
.map { String($0) }
|
||||
.joined()
|
||||
.sqlExpression
|
||||
.quotedSQL(db)
|
||||
]
|
||||
}
|
||||
components.append(contentsOf: tokenCharactersComponents)
|
||||
components.append(contentsOf: [
|
||||
"tokenchars",
|
||||
tokenCharacters
|
||||
.sorted()
|
||||
.map { String($0) }
|
||||
.joined()
|
||||
.sqlExpression
|
||||
.quotedSQL()
|
||||
])
|
||||
}
|
||||
return FTS5TokenizerDescriptor(components: components)
|
||||
}
|
||||
|
||||
@@ -7,13 +7,6 @@ import UIKit
|
||||
#endif
|
||||
|
||||
extension AnyFetchRequest {
|
||||
@available(*, unavailable, renamed: "RowDecoder")
|
||||
typealias T = RowDecoder
|
||||
|
||||
@available(*, unavailable, message: "Use AnyFetchRequest(request).asRequest(of: SomeType.self) instead.")
|
||||
public init<Request: FetchRequest>(_ request: Request)
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Define your own FetchRequest type instead.")
|
||||
public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?))
|
||||
{ preconditionFailure() }
|
||||
@@ -47,14 +40,6 @@ extension AssociationAggregate {
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
extension Configuration {
|
||||
@available(*, unavailable, message: "Use Database.trace(options:_:) in Configuration.prepareDatabase instead.")
|
||||
public var trace: TraceFunction? {
|
||||
get { preconditionFailure() }
|
||||
set { preconditionFailure() }
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseFunction {
|
||||
@available(*, unavailable, renamed: "callAsFunction(_:)")
|
||||
public func apply(_ arguments: SQLExpressible...) -> SQLExpression
|
||||
@@ -86,9 +71,6 @@ extension DatabaseMigrator {
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
@available(*, unavailable, message: "Use pool.writeWithoutTransaction { $0.checkpoint() } instead")
|
||||
public func checkpoint(_ kind: Database.CheckpointMode = .passive) throws { preconditionFailure() }
|
||||
|
||||
#if os(iOS)
|
||||
@available(*, unavailable, message: "Memory management is now enabled by default. This method does nothing.")
|
||||
public func setupMemoryManagement(in application: UIApplication) { preconditionFailure() }
|
||||
@@ -152,23 +134,12 @@ extension FetchRequest where RowDecoder == Row {
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
@available(*, unavailable, renamed: "RowDecoder")
|
||||
typealias T = RowDecoder
|
||||
}
|
||||
|
||||
extension SQLExpression {
|
||||
@available(*, unavailable, message: "Use SQLLiteral initializer instead")
|
||||
public var sqlLiteral: SQLLiteral
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
extension FilteredRequest {
|
||||
@available(*, unavailable, message: "The expectingSingleResult() hint is no longer available.")
|
||||
func expectingSingleResult() -> Self
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
@available(*, unavailable, message: "Build literal expressions with SQLLiteral.sqlExpression instead.")
|
||||
public struct SQLExpressionLiteral: SQLExpression {
|
||||
public var sql: String { preconditionFailure() }
|
||||
@@ -180,7 +151,7 @@ public struct SQLExpressionLiteral: SQLExpression {
|
||||
public init(literal sqlLiteral: SQLLiteral)
|
||||
{ preconditionFailure() }
|
||||
|
||||
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String
|
||||
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String
|
||||
{ preconditionFailure() }
|
||||
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression
|
||||
@@ -191,37 +162,11 @@ extension SQLLiteral {
|
||||
@available(*, unavailable, message: "Use SQL interpolation instead.")
|
||||
public func mapSQL(_ transform: @escaping (String) -> String) -> SQLLiteral
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Use the build(_:) method instead.")
|
||||
public var sql: String { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Use the build(_:) method instead.")
|
||||
public var arguments: StatementArguments { preconditionFailure() }
|
||||
}
|
||||
|
||||
@available(*, unavailable, renamed: "SQLAssociativeBinaryOperator")
|
||||
typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator
|
||||
|
||||
extension SQLRequest {
|
||||
@available(*, unavailable, renamed: "RowDecoder")
|
||||
typealias T = RowDecoder
|
||||
|
||||
@available(*, unavailable, message: "Turning a request into SQLRequest is no longer supported.")
|
||||
public init<Request>(
|
||||
_ db: Database,
|
||||
request: Request,
|
||||
cached: Bool = false)
|
||||
throws
|
||||
where Request: FetchRequest, Request.RowDecoder == RowDecoder
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Use makePreparedRequest(db, forSingleResult: false).statement.sql instead")
|
||||
public var sql: String { preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Use makePreparedRequest(db, forSingleResult: false).statement.arguments instead")
|
||||
public var arguments: StatementArguments { preconditionFailure() }
|
||||
}
|
||||
|
||||
extension SQLSpecificExpressible {
|
||||
@available(*, unavailable, renamed: "forKey(_:)")
|
||||
public func aliased(_ name: String) -> SQLSelectable
|
||||
@@ -246,10 +191,6 @@ extension TableRecord {
|
||||
@available(*, unavailable, message: "Use ValueObservation.tracking(MyRecord.fetchCount) instead")
|
||||
public static func observationForCount() -> ValueObservation<ValueReducers.Unavailable<Int>>
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Use SQL interpolation instead")
|
||||
public static func selectionSQL(alias: String? = nil) -> String
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
extension TableRecord where Self: FetchableRecord {
|
||||
@@ -262,9 +203,6 @@ extension TableRecord where Self: FetchableRecord {
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
public typealias TraceFunction = (String) -> Void
|
||||
|
||||
extension ValueObservation {
|
||||
@available(*, unavailable, message: "ValueObservation now schedules its values asynchronously on the main queue by default. See ValueObservation.start() for possible configuration")
|
||||
var scheduling: ValueScheduling {
|
||||
@@ -275,7 +213,7 @@ extension ValueObservation {
|
||||
@available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public static func tracking(_ regions: DatabaseRegionConvertible..., reducer: @escaping (Database) throws -> Reducer) -> ValueObservation
|
||||
{ preconditionFailure() }
|
||||
|
||||
|
||||
@available(*, unavailable, message: "Custom reducers are no longer supported. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public static func tracking(_ regions: [DatabaseRegionConvertible], reducer: @escaping (Database) throws -> Reducer) -> ValueObservation
|
||||
{ preconditionFailure() }
|
||||
@@ -288,7 +226,7 @@ extension ValueObservation {
|
||||
_ transform: @escaping (Reducer.Value, R1.Value) -> Combined)
|
||||
-> ValueObservation<ValueReducers.Unavailable<Combined>>
|
||||
{ preconditionFailure() }
|
||||
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public func combine<
|
||||
R1: _ValueReducer,
|
||||
@@ -299,7 +237,7 @@ extension ValueObservation {
|
||||
_ transform: @escaping (Reducer.Value, R1.Value, R2.Value) -> Combined)
|
||||
-> ValueObservation<ValueReducers.Unavailable<Combined>>
|
||||
{ preconditionFailure() }
|
||||
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public func combine<
|
||||
R1: _ValueReducer,
|
||||
@@ -312,7 +250,7 @@ extension ValueObservation {
|
||||
_ transform: @escaping (Reducer.Value, R1.Value, R2.Value, R3.Value) -> Combined)
|
||||
-> ValueObservation<ValueReducers.Unavailable<Combined>>
|
||||
{ preconditionFailure() }
|
||||
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
public func combine<
|
||||
R1: _ValueReducer,
|
||||
@@ -346,7 +284,7 @@ extension ValueObservation where Reducer == ValueReducers.Auto {
|
||||
R2: _ValueReducer>(
|
||||
_ o1: ValueObservation<R1>,
|
||||
_ o2: ValueObservation<R2>)
|
||||
-> ValueObservation<ValueReducers.Unavailable<(R1.Value, R2.Value)>>
|
||||
-> ValueObservation<ValueReducers.Unavailable<(R1.Value, R2.Value)>>
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "combine is no longer available. See the \"Migrating From GRDB 4 to GRDB 5\" guide.")
|
||||
|
||||
@@ -140,7 +140,6 @@ public struct DatabaseMigrator {
|
||||
// migrations would involve a lot of data).
|
||||
var witnessConfiguration = writer.configuration
|
||||
witnessConfiguration.targetQueue = nil // Avoid deadlocks
|
||||
witnessConfiguration.label = "GRDB.DatabaseMigrator.temporary"
|
||||
let witness = try DatabaseQueue(path: "", configuration: witnessConfiguration)
|
||||
|
||||
// Grab schema of migrated witness database
|
||||
@@ -171,10 +170,8 @@ public struct DatabaseMigrator {
|
||||
|
||||
// MARK: - Querying Migrations
|
||||
|
||||
/// Returns the identifiers of registered and applied migrations, in the
|
||||
/// order of registration.
|
||||
///
|
||||
/// See also `appliedIdentifiers(_:)`.
|
||||
/// Returns the applied migration identifiers, in the same order as
|
||||
/// registered migrations.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: An eventual database error.
|
||||
@@ -183,24 +180,6 @@ public struct DatabaseMigrator {
|
||||
return migrations.map { $0.identifier }.filter { appliedIdentifiers.contains($0) }
|
||||
}
|
||||
|
||||
/// Returns the applied migration identifiers, even unregistered ones.
|
||||
///
|
||||
/// See also `appliedMigrations(_:)`.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: An eventual database error.
|
||||
public func appliedIdentifiers(_ db: Database) throws -> Set<String> {
|
||||
do {
|
||||
return try Set(String.fetchCursor(db, sql: "SELECT identifier FROM grdb_migrations"))
|
||||
} catch {
|
||||
// Rethrow if we can't prove grdb_migrations does not exist yet
|
||||
if (try? !db.tableExists("grdb_migrations")) ?? false {
|
||||
return []
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the identifiers of completed migrations, of which all previous
|
||||
/// migrations have been applied.
|
||||
///
|
||||
@@ -221,19 +200,7 @@ public struct DatabaseMigrator {
|
||||
public func hasCompletedMigrations(_ db: Database) throws -> Bool {
|
||||
try completedMigrations(db).last == migrations.last?.identifier
|
||||
}
|
||||
|
||||
/// Returns whether database contains unknown migration
|
||||
/// identifiers, which is likely the sign that the database
|
||||
/// has migrated further than the migrator itself supports.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: An eventual database error.
|
||||
public func hasBeenSuperseded(_ db: Database) throws -> Bool {
|
||||
let appliedIdentifiers = try self.appliedIdentifiers(db)
|
||||
let knownIdentifiers = migrations.map(\.identifier)
|
||||
return appliedIdentifiers.contains { !knownIdentifiers.contains($0) }
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Non public
|
||||
|
||||
private mutating func registerMigration(_ migration: Migration) {
|
||||
@@ -243,6 +210,22 @@ public struct DatabaseMigrator {
|
||||
migrations.append(migration)
|
||||
}
|
||||
|
||||
/// Returns the applied migration identifiers, even unregistered ones
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: An eventual database error.
|
||||
public func appliedIdentifiers(_ db: Database) throws -> Set<String> {
|
||||
do {
|
||||
return try Set(String.fetchCursor(db, sql: "SELECT identifier FROM grdb_migrations"))
|
||||
} catch {
|
||||
// Rethrow if we can't prove grdb_migrations does not exist yet
|
||||
if (try? !db.tableExists("grdb_migrations")) ?? false {
|
||||
return []
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns unapplied migration identifier,
|
||||
private func unappliedMigrations(upTo targetIdentifier: String, appliedIdentifiers: [String]) -> [Migration] {
|
||||
var expectedMigrations: [Migration] = []
|
||||
|
||||
@@ -4,7 +4,10 @@ struct Migration {
|
||||
let migrate: (Database) throws -> Void
|
||||
|
||||
func run(_ db: Database) throws {
|
||||
if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false {
|
||||
// PRAGMA foreign_key_check and SQLITE_CONSTRAINT_FOREIGNKEY were
|
||||
// introduced in SQLite 3.7.16
|
||||
// http://www.sqlite.org/changes.html#version_3_7_16
|
||||
if try sqlite3_libversion_number() >= 3007016 && (Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false) {
|
||||
try runWithDeferredForeignKeysChecks(db)
|
||||
} else {
|
||||
try runWithoutDisabledForeignKeys(db)
|
||||
|
||||
@@ -113,7 +113,7 @@ extension Association {
|
||||
/// // SELECT player.*, team.color
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team.select { db in [Column("color")]
|
||||
/// let association = Player.team.select([Column("color")])
|
||||
/// var request = Player.including(required: association)
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
@@ -122,10 +122,10 @@ extension Association {
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team
|
||||
/// .select { db in [Column("id")] }
|
||||
/// .select { db in [Column("color") }
|
||||
/// .select([Column("id")])
|
||||
/// .select([Column("color")])
|
||||
/// var request = Player.including(required: association)
|
||||
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
public func select(_ selection: [SQLSelectable]) -> Self {
|
||||
mapDestinationRelation { $0.select(selection) }
|
||||
}
|
||||
|
||||
@@ -140,9 +140,9 @@ extension Association {
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// let association = Player.team
|
||||
/// .select([Column("color")])
|
||||
/// .annotated(with: { db in [Column("name")] })
|
||||
/// .annotated(with: [Column("name")])
|
||||
/// var request = Player.including(required: association)
|
||||
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
public func annotated(with selection: [SQLSelectable]) -> Self {
|
||||
mapDestinationRelation { $0.annotated(with: selection) }
|
||||
}
|
||||
|
||||
@@ -321,3 +321,166 @@ extension AssociationToMany {
|
||||
return .init(sqlAssociation: sqlAssociation.forDestinationKey(associationKey))
|
||||
}
|
||||
}
|
||||
|
||||
extension AssociationToMany {
|
||||
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<OriginRowDecoder> {
|
||||
AssociationAggregate { request in
|
||||
let tableAlias = TableAlias()
|
||||
let request = request
|
||||
.joining(optional: self.aliased(tableAlias))
|
||||
.groupByPrimaryKey()
|
||||
let expression = tableAlias[expression]
|
||||
return (request: request, expression: expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of associated records.
|
||||
///
|
||||
/// It has a default name, which is "[key]Count", where key is the key of
|
||||
/// the association. For example:
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var playerCount: Int
|
||||
/// }
|
||||
/// let request = Team.annotated(with: Team.players.count())
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
|
||||
public var count: AssociationAggregate<OriginRowDecoder> {
|
||||
// TODO: try to replace rowid with actual primary key
|
||||
makeAggregate(SQLExpressionCountDistinct(Column.rowID))
|
||||
.forKey("\(key.singularizedName)Count")
|
||||
}
|
||||
|
||||
/// Creates an aggregate that is true if there exists no associated records.
|
||||
///
|
||||
/// It has a default name, which is "hasNo[Key]", where key is the key of
|
||||
/// the association. For example:
|
||||
///
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var hasNoPlayer: Bool
|
||||
/// }
|
||||
/// let request = Team.annotated(with: Team.players.isEmpty())
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.isEmpty()).fetchAll(db)
|
||||
/// let teams: [Team] = try Team.having(!Team.players.isEmpty())
|
||||
/// let teams: [Team] = try Team.having(Team.players.isEmpty() == false)
|
||||
public var isEmpty: AssociationAggregate<OriginRowDecoder> {
|
||||
// TODO: try to replace rowid with actual primary key
|
||||
makeAggregate(SQLExpressionIsEmpty(SQLExpressionCountDistinct(Column.rowID)))
|
||||
.forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
|
||||
}
|
||||
|
||||
/// Creates an aggregate which evaluate to the average value of the given
|
||||
/// expression in associated records.
|
||||
///
|
||||
/// When the averaged expression is a column, the aggregate has a default
|
||||
/// name which is "average[Key][Column]", where key is the key of the
|
||||
/// association. For example:
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var averagePlayerScore: Double
|
||||
/// }
|
||||
/// let request = Team.annotated(with: Team.players.average(Column("score")))
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db)
|
||||
public func average(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
} else {
|
||||
return aggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an aggregate which evaluate to the maximum value of the given
|
||||
/// expression in associated records.
|
||||
///
|
||||
/// When the maximized expression is a column, the aggregate has a default
|
||||
/// name which is "maximum[Key][Column]", where key is the key of the
|
||||
/// association. For example:
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var maxPlayerScore: Double
|
||||
/// }
|
||||
/// let request = Team.annotated(with: Team.players.max(Column("score")))
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db)
|
||||
public func max(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
} else {
|
||||
return aggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an aggregate which evaluate to the minimum value of the given
|
||||
/// expression in associated records.
|
||||
///
|
||||
/// When the minimized expression is a column, the aggregate has a default
|
||||
/// name which is "minimum[Key][Column]", where key is the key of the
|
||||
/// association. For example:
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var minPlayerScore: Double
|
||||
/// }
|
||||
/// let request = Team.annotated(with: Team.players.min(Column("score")))
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db)
|
||||
public func min(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
} else {
|
||||
return aggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an aggregate which evaluate to the sum of the given expression
|
||||
/// in associated records.
|
||||
///
|
||||
/// When the summed expression is a column, the aggregate has a default
|
||||
/// name which is "[key][Column]Sum", where key is the key of the
|
||||
/// association. For example:
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var playerScoreSum: Double
|
||||
/// }
|
||||
/// let request = Team.annotated(with: Team.players.sum(Column("score")))
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db)
|
||||
public func sum(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum")
|
||||
} else {
|
||||
return aggregate
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,180 +1,8 @@
|
||||
import Foundation
|
||||
|
||||
typealias AssociationAggregatePreparation<RowDecoder> =
|
||||
(inout QueryInterfaceRequest<RowDecoder>)
|
||||
-> DatabasePromise<SQLExpression>
|
||||
|
||||
extension AssociationToMany {
|
||||
private func makeAggregate(_ expressionPromise: DatabasePromise<SQLExpression>)
|
||||
-> AssociationAggregate<OriginRowDecoder>
|
||||
{
|
||||
AssociationAggregate { request in
|
||||
let tableAlias = TableAlias()
|
||||
request = request
|
||||
.joining(optional: self.aliased(tableAlias))
|
||||
.groupByPrimaryKey()
|
||||
return expressionPromise.map { tableAlias[$0] }
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience
|
||||
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<OriginRowDecoder> {
|
||||
makeAggregate(DatabasePromise(value: expression))
|
||||
}
|
||||
|
||||
/// The number of associated records.
|
||||
///
|
||||
/// It has a default name, which is "[key]Count", where key is the key of
|
||||
/// the association. For example:
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var playerCount: Int
|
||||
/// }
|
||||
/// let request = Team.annotated(with: Team.players.count())
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
|
||||
public var count: AssociationAggregate<OriginRowDecoder> {
|
||||
let expression = SQLExpressionCountDistinct(
|
||||
SQLPrimaryKeyExpression(
|
||||
tableName: self.databaseTableName))
|
||||
return makeAggregate(expression).forKey("\(key.singularizedName)Count")
|
||||
}
|
||||
|
||||
/// Creates an aggregate that is true if there exists no associated records.
|
||||
///
|
||||
/// It has a default name, which is "hasNo[Key]", where key is the key of
|
||||
/// the association. For example:
|
||||
///
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var hasNoPlayer: Bool
|
||||
/// }
|
||||
/// let request = Team.annotated(with: Team.players.isEmpty())
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.isEmpty()).fetchAll(db)
|
||||
/// let teams: [Team] = try Team.having(!Team.players.isEmpty())
|
||||
/// let teams: [Team] = try Team.having(Team.players.isEmpty() == false)
|
||||
public var isEmpty: AssociationAggregate<OriginRowDecoder> {
|
||||
let expression = SQLExpressionIsEmpty(
|
||||
SQLExpressionCountDistinct(
|
||||
SQLPrimaryKeyExpression(
|
||||
tableName: self.databaseTableName)))
|
||||
return makeAggregate(expression).forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
|
||||
}
|
||||
|
||||
/// Creates an aggregate which evaluate to the average value of the given
|
||||
/// expression in associated records.
|
||||
///
|
||||
/// When the averaged expression is a column, the aggregate has a default
|
||||
/// name which is "average[Key][Column]", where key is the key of the
|
||||
/// association. For example:
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var averagePlayerScore: Double
|
||||
/// }
|
||||
/// let request = Team.annotated(with: Team.players.average(Column("score")))
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db)
|
||||
public func average(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(SQLExpressionFunction(.avg, arguments: expression))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
} else {
|
||||
return aggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an aggregate which evaluate to the maximum value of the given
|
||||
/// expression in associated records.
|
||||
///
|
||||
/// When the maximized expression is a column, the aggregate has a default
|
||||
/// name which is "maximum[Key][Column]", where key is the key of the
|
||||
/// association. For example:
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var maxPlayerScore: Double
|
||||
/// }
|
||||
/// let request = Team.annotated(with: Team.players.max(Column("score")))
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db)
|
||||
public func max(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(SQLExpressionFunction(.max, arguments: expression))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
} else {
|
||||
return aggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an aggregate which evaluate to the minimum value of the given
|
||||
/// expression in associated records.
|
||||
///
|
||||
/// When the minimized expression is a column, the aggregate has a default
|
||||
/// name which is "minimum[Key][Column]", where key is the key of the
|
||||
/// association. For example:
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var minPlayerScore: Double
|
||||
/// }
|
||||
/// let request = Team.annotated(with: Team.players.min(Column("score")))
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db)
|
||||
public func min(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(SQLExpressionFunction(.min, arguments: expression))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
|
||||
} else {
|
||||
return aggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an aggregate which evaluate to the sum of the given expression
|
||||
/// in associated records.
|
||||
///
|
||||
/// When the summed expression is a column, the aggregate has a default
|
||||
/// name which is "[key][Column]Sum", where key is the key of the
|
||||
/// association. For example:
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct TeamInfo: FetchableRecord, Decodable {
|
||||
/// var team: Team
|
||||
/// var playerScoreSum: Double
|
||||
/// }
|
||||
/// let request = Team.annotated(with: Team.players.sum(Column("score")))
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db)
|
||||
public func sum(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(SQLExpressionFunction(.sum, arguments: expression))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum")
|
||||
} else {
|
||||
return aggregate
|
||||
}
|
||||
}
|
||||
}
|
||||
(QueryInterfaceRequest<RowDecoder>)
|
||||
-> (request: QueryInterfaceRequest<RowDecoder>, expression: SQLExpression)
|
||||
|
||||
/// An AssociationAggregate is able to compute aggregated values from a
|
||||
/// population of associated records.
|
||||
@@ -199,9 +27,10 @@ extension AssociationToMany {
|
||||
/// // Won't compile because Fruit is not Author.
|
||||
/// let request = Fruit.annotated(with: bookCount)
|
||||
public struct AssociationAggregate<RowDecoder> {
|
||||
/// Extend the request with the associated records used to compute the
|
||||
/// aggregate, and return an expression promise which resolves to the
|
||||
/// aggregated value.
|
||||
// TODO: replace rowid with actual primary key in the doc when implemented
|
||||
/// Given a request, returns a tuple made of a request extended with the
|
||||
/// associated records used to compute the aggregate, and an expression
|
||||
/// whose value is the aggregated value.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -210,22 +39,22 @@ public struct AssociationAggregate<RowDecoder> {
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM author
|
||||
/// var request = Author.all()
|
||||
/// let request = Author.all()
|
||||
///
|
||||
/// let aggregate = Author.books.count
|
||||
/// let expressionPromise = aggregate.prepare(&request)
|
||||
/// let tuple = aggregate.prepare(request)
|
||||
///
|
||||
/// // The request has been extended with associated records:
|
||||
/// // The request extended with associated records:
|
||||
/// //
|
||||
/// // SELECT author.* FROM author
|
||||
/// // LEFT JOIN book ON book.authorId = author.id
|
||||
/// // GROUP BY author.id
|
||||
/// request
|
||||
/// tuple.request
|
||||
///
|
||||
/// // The aggregated value:
|
||||
/// //
|
||||
/// // COUNT(DISTINCT book.id)
|
||||
/// try expressionPromise.resolve(db)
|
||||
/// // COUNT(DISTINCT book.rowid)
|
||||
/// tuple.expression
|
||||
///
|
||||
/// The aggregated value is not right away embedded in the extended request:
|
||||
///
|
||||
@@ -270,31 +99,6 @@ extension AssociationAggregate: Refinable {
|
||||
public func forKey(_ key: CodingKey) -> Self {
|
||||
forKey(key.stringValue)
|
||||
}
|
||||
|
||||
/// Transforms the expression, and does not preserve key.
|
||||
fileprivate func map(_ transform: @escaping (SQLExpression) throws -> SQLExpression) -> Self {
|
||||
AssociationAggregate { request in
|
||||
self.prepare(&request).map(transform)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Combines the expression of two aggregates.
|
||||
private func combine<RowDecoder>(
|
||||
_ lhs: AssociationAggregate<RowDecoder>,
|
||||
_ rhs: AssociationAggregate<RowDecoder>,
|
||||
with combineExpressions : @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
AssociationAggregate { request in
|
||||
let lhsPromise = lhs.prepare(&request)
|
||||
let rhsPromise = rhs.prepare(&request)
|
||||
return DatabasePromise { db in
|
||||
try combineExpressions(
|
||||
lhsPromise.resolve(db),
|
||||
rhsPromise.resolve(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Logical Operators (AND, OR, NOT)
|
||||
@@ -305,7 +109,10 @@ private func combine<RowDecoder>(
|
||||
///
|
||||
/// Author.having(!Author.books.isEmpty)
|
||||
public prefix func ! <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
|
||||
aggregate.map { !$0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = aggregate.prepare(request)
|
||||
return (request: request, expression: !expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Groups two aggregates with the `AND` SQL operator.
|
||||
@@ -318,7 +125,11 @@ public func && <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: &&)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression && rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: test
|
||||
@@ -328,7 +139,10 @@ public func && <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 && rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression && rhs)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: test
|
||||
@@ -338,7 +152,10 @@ public func && <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs && $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs && expression)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -352,7 +169,11 @@ public func || <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: ||)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression || rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: test
|
||||
@@ -362,7 +183,10 @@ public func || <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 || rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression || rhs)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: test
|
||||
@@ -372,7 +196,10 @@ public func || <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs || $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs || expression)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Egality and Identity Operators (=, <>, IS, IS NOT)
|
||||
@@ -387,7 +214,11 @@ public func == <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: ==)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression == rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `=` SQL operator.
|
||||
@@ -400,7 +231,10 @@ public func == <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 == rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression == rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `=` SQL operator.
|
||||
@@ -413,7 +247,10 @@ public func == <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs == $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs == expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that checks the boolean value of an aggregate.
|
||||
@@ -422,7 +259,10 @@ public func == <RowDecoder>(
|
||||
///
|
||||
/// Author.having(Author.books.isEmpty == false)
|
||||
public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
|
||||
lhs.map { $0 == rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression == rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that checks the boolean value of an aggregate.
|
||||
@@ -431,7 +271,10 @@ public func == <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) ->
|
||||
///
|
||||
/// Author.having(false == Author.books.isEmpty)
|
||||
public func == <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
|
||||
rhs.map { lhs == $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs == expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares two aggregates with the `<>` SQL operator.
|
||||
@@ -444,7 +287,11 @@ public func != <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: !=)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression != rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `<>` SQL operator.
|
||||
@@ -457,7 +304,10 @@ public func != <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 != rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression != rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `<>` SQL operator.
|
||||
@@ -470,7 +320,10 @@ public func != <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs != $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs != expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that checks the boolean value of an aggregate.
|
||||
@@ -479,7 +332,10 @@ public func != <RowDecoder>(
|
||||
///
|
||||
/// Author.having(Author.books.isEmpty != true)
|
||||
public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) -> AssociationAggregate<RowDecoder> {
|
||||
lhs.map { $0 != rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression != rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that checks the boolean value of an aggregate.
|
||||
@@ -488,7 +344,10 @@ public func != <RowDecoder>(lhs: AssociationAggregate<RowDecoder>, rhs: Bool) ->
|
||||
///
|
||||
/// Author.having(true != Author.books.isEmpty)
|
||||
public func != <RowDecoder>(lhs: Bool, rhs: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
|
||||
rhs.map { lhs != $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs != expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares two aggregates with the `IS` SQL operator.
|
||||
@@ -501,7 +360,11 @@ public func === <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: ===)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression === rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `IS` SQL operator.
|
||||
@@ -514,7 +377,10 @@ public func === <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 === rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression === rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `IS` SQL operator.
|
||||
@@ -527,7 +393,10 @@ public func === <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs === $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs === expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares two aggregates with the `IS NOT` SQL operator.
|
||||
@@ -540,7 +409,11 @@ public func !== <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: !==)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression !== rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator.
|
||||
@@ -553,7 +426,10 @@ public func !== <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 !== rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression !== rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `IS NOT` SQL operator.
|
||||
@@ -566,7 +442,10 @@ public func !== <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs !== $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs !== expression)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Comparison Operators (<, >, <=, >=)
|
||||
@@ -581,7 +460,11 @@ public func <= <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: <=)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression <= rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `<=` SQL operator.
|
||||
@@ -594,7 +477,10 @@ public func <= <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 <= rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression <= rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `<=` SQL operator.
|
||||
@@ -607,7 +493,10 @@ public func <= <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs <= $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs <= expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares two aggregates with the `<` SQL operator.
|
||||
@@ -620,7 +509,11 @@ public func < <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: <)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression < rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `<` SQL operator.
|
||||
@@ -633,7 +526,10 @@ public func < <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 < rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression < rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `<` SQL operator.
|
||||
@@ -646,7 +542,10 @@ public func < <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs < $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs < expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares two aggregates with the `>` SQL operator.
|
||||
@@ -659,7 +558,11 @@ public func > <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: >)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression > rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `>` SQL operator.
|
||||
@@ -672,7 +575,10 @@ public func > <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 > rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression > rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `>` SQL operator.
|
||||
@@ -685,7 +591,10 @@ public func > <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs > $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs > expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares two aggregates with the `>=` SQL operator.
|
||||
@@ -698,7 +607,11 @@ public func >= <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: >=)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression >= rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `>=` SQL operator.
|
||||
@@ -711,7 +624,10 @@ public func >= <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 >= rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression >= rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that compares an aggregate with the `>=` SQL operator.
|
||||
@@ -724,7 +640,10 @@ public func >= <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs >= $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs >= expression)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Arithmetic Operators (+, -, *, /)
|
||||
@@ -735,7 +654,10 @@ public func >= <RowDecoder>(
|
||||
///
|
||||
/// Author.annotated(with: -Author.books.count)
|
||||
public prefix func - <RowDecoder>(aggregate: AssociationAggregate<RowDecoder>) -> AssociationAggregate<RowDecoder> {
|
||||
aggregate.map { -$0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = aggregate.prepare(request)
|
||||
return (request: request, expression:-expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that sums two aggregates with the `+` SQL operator.
|
||||
@@ -748,7 +670,11 @@ public func + <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: +)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression + rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that sums an aggregate with the `+` SQL operator.
|
||||
@@ -761,7 +687,10 @@ public func + <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 + rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression + rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that sums an aggregate with the `+` SQL operator.
|
||||
@@ -774,7 +703,10 @@ public func + <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs + $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs + expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that substracts two aggregates with the `-` SQL operator.
|
||||
@@ -787,7 +719,11 @@ public func - <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: -)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression - rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that substracts an aggregate with the `-` SQL operator.
|
||||
@@ -800,7 +736,10 @@ public func - <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 - rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression - rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that substracts an aggregate with the `-` SQL operator.
|
||||
@@ -813,7 +752,10 @@ public func - <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs - $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs - expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that multiplies two aggregates with the `*` SQL operator.
|
||||
@@ -826,7 +768,11 @@ public func * <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: *)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression * rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that substracts an aggregate with the `*` SQL operator.
|
||||
@@ -839,7 +785,10 @@ public func * <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 * rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression * rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that substracts an aggregate with the `*` SQL operator.
|
||||
@@ -852,7 +801,10 @@ public func * <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs * $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs * expression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that multiplies two aggregates with the `/` SQL operator.
|
||||
@@ -865,7 +817,11 @@ public func / <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
combine(lhs, rhs, with: /)
|
||||
AssociationAggregate { request in
|
||||
let (lRequest, lExpression) = lhs.prepare(request)
|
||||
let (request, rExpression) = rhs.prepare(lRequest)
|
||||
return (request: request, expression: lExpression / rExpression)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that substracts an aggregate with the `/` SQL operator.
|
||||
@@ -878,7 +834,10 @@ public func / <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
lhs.map { $0 / rhs }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression / rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that substracts an aggregate with the `/` SQL operator.
|
||||
@@ -891,7 +850,10 @@ public func / <RowDecoder>(
|
||||
rhs: AssociationAggregate<RowDecoder>)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
rhs.map { lhs / $0 }
|
||||
AssociationAggregate { request in
|
||||
let (request, expression) = rhs.prepare(request)
|
||||
return (request: request, expression: lhs / expression)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - IFNULL(...)
|
||||
@@ -904,8 +866,14 @@ public func ?? <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
var aggregate = AssociationAggregate<RowDecoder> { request in
|
||||
let (request, expression) = lhs.prepare(request)
|
||||
return (request: request, expression: expression ?? rhs)
|
||||
}
|
||||
|
||||
// Preserve key
|
||||
lhs.map { $0 ?? rhs }.with(\.key, lhs.key)
|
||||
aggregate.key = lhs.key
|
||||
return aggregate
|
||||
}
|
||||
|
||||
// TODO: add support for ABS(aggregate)
|
||||
|
||||
@@ -96,7 +96,7 @@ public struct BelongsToAssociation<Origin: TableRecord, Destination: TableRecord
|
||||
sqlAssociation = SQLAssociation(
|
||||
key: associationKey,
|
||||
condition: condition,
|
||||
relation: Destination.relationForAll,
|
||||
relation: Destination.all().relation,
|
||||
cardinality: .toOne)
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,72 @@ public struct HasManyAssociation<Origin: TableRecord, Destination: TableRecord>:
|
||||
sqlAssociation = SQLAssociation(
|
||||
key: associationKey,
|
||||
condition: condition,
|
||||
relation: Destination.relationForAll,
|
||||
relation: Destination.all().relation,
|
||||
cardinality: .toMany)
|
||||
}
|
||||
|
||||
/// Creates a "Has one" association between the source and
|
||||
/// destination types.
|
||||
///
|
||||
/// struct Book: TableRecord { ... }
|
||||
/// struct Author: TableRecord {
|
||||
/// static let firstBook = hasMany(Book.self).order(Column("year")).first
|
||||
/// }
|
||||
///
|
||||
/// The association lets you define requests that load both the source
|
||||
/// and the destination type:
|
||||
///
|
||||
/// // A request for all (author, firstBook) pairs:
|
||||
/// let request = Author.including(required: Author.firstBook)
|
||||
///
|
||||
/// To consume those requests, define a type that adopts both the
|
||||
/// FetchableRecord and Decodable protocols:
|
||||
///
|
||||
/// struct Authorship: FetchableRecord, Decodable {
|
||||
/// var author: Author
|
||||
/// var firstBook: Book
|
||||
/// }
|
||||
///
|
||||
/// let authorships = try dbQueue.read { db in
|
||||
/// return try Authorship.fetchAll(db, request)
|
||||
/// }
|
||||
/// for authorship in authorships {
|
||||
/// print("\(authorship.author.name) wrote \(authorship.firstBook.title) first")
|
||||
/// }
|
||||
public var first: HasOneAssociation<Origin, Destination> {
|
||||
HasOneAssociation(sqlAssociation: sqlAssociation.associationForFirst())
|
||||
.forKey("first\(key.singularizedName.uppercasingFirstCharacter)")
|
||||
}
|
||||
|
||||
/// Creates a "Has one" association between the source and
|
||||
/// destination types.
|
||||
///
|
||||
/// struct Book: TableRecord { ... }
|
||||
/// struct Author: TableRecord {
|
||||
/// static let lastBook = hasMany(Book.self).order(Column("year")).last
|
||||
/// }
|
||||
///
|
||||
/// The association lets you define requests that load both the source
|
||||
/// and the destination type:
|
||||
///
|
||||
/// // A request for all (author, firstBook) pairs:
|
||||
/// let request = Author.including(required: Author.lastBook)
|
||||
///
|
||||
/// To consume those requests, define a type that adopts both the
|
||||
/// FetchableRecord and Decodable protocols:
|
||||
///
|
||||
/// struct Authorship: FetchableRecord, Decodable {
|
||||
/// var author: Author
|
||||
/// var lastBook: Book
|
||||
/// }
|
||||
///
|
||||
/// let authorships = try dbQueue.read { db in
|
||||
/// return try Authorship.fetchAll(db, request)
|
||||
/// }
|
||||
/// for authorship in authorships {
|
||||
/// print("\(authorship.author.name) wrote \(authorship.lastBook.title) last")
|
||||
/// }
|
||||
public var last: HasOneAssociation<Origin, Destination> {
|
||||
reversed().first.forKey("last\(key.singularizedName.uppercasingFirstCharacter)")
|
||||
}
|
||||
}
|
||||
@@ -55,4 +55,15 @@ public struct HasManyThroughAssociation<Origin: TableRecord, Destination: TableR
|
||||
public init(sqlAssociation: SQLAssociation) {
|
||||
self.sqlAssociation = sqlAssociation
|
||||
}
|
||||
|
||||
// TODO
|
||||
public var first: HasOneThroughAssociation<Origin, Destination> {
|
||||
HasOneThroughAssociation(sqlAssociation: sqlAssociation.associationForFirst())
|
||||
.forKey("first\(key.singularizedName.uppercasingFirstCharacter)")
|
||||
}
|
||||
|
||||
// TODO
|
||||
public var last: HasOneThroughAssociation<Origin, Destination> {
|
||||
reversed().first.forKey("last\(key.singularizedName.uppercasingFirstCharacter)")
|
||||
}
|
||||
}
|
||||
@@ -98,7 +98,7 @@ public struct HasOneAssociation<Origin: TableRecord, Destination: TableRecord>:
|
||||
sqlAssociation = SQLAssociation(
|
||||
key: associationKey,
|
||||
condition: condition,
|
||||
relation: Destination.relationForAll,
|
||||
relation: Destination.all().relation,
|
||||
cardinality: .toOne)
|
||||
}
|
||||
}
|
||||
@@ -3,18 +3,18 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
|
||||
// MARK: - Association Aggregates
|
||||
|
||||
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
|
||||
var request = self
|
||||
let expressionPromise = aggregate.prepare(&request)
|
||||
let (request, expression) = aggregate.prepare(self)
|
||||
if let key = aggregate.key {
|
||||
return request.annotated(with: { db in try [expressionPromise.resolve(db).forKey(key)] })
|
||||
return request.annotated(with: [expression.forKey(key)])
|
||||
} else {
|
||||
return request.annotated(with: { db in try [expressionPromise.resolve(db)] })
|
||||
return request.annotated(with: [expression])
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: replace rowid with actual primary key in the doc when implemented
|
||||
/// Creates a request which appends *aggregates* to the current selection.
|
||||
///
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
|
||||
/// // FROM player LEFT JOIN book ...
|
||||
/// var request = Player.all()
|
||||
/// request = request.annotated(with: Player.books.count)
|
||||
@@ -22,9 +22,10 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
|
||||
annotated(with: aggregates)
|
||||
}
|
||||
|
||||
// TODO: replace rowid with actual primary key in the doc when implemented
|
||||
/// Creates a request which appends *aggregates* to the current selection.
|
||||
///
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
|
||||
/// // FROM player LEFT JOIN book ...
|
||||
/// var request = Player.all()
|
||||
/// request = request.annotated(with: [Player.books.count])
|
||||
@@ -34,17 +35,17 @@ extension QueryInterfaceRequest where RowDecoder: TableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: replace rowid with actual primary key in the doc when implemented
|
||||
/// Creates a request which appends the provided aggregate *predicate* to
|
||||
/// the eventual set of already applied predicates.
|
||||
///
|
||||
/// // SELECT player.*
|
||||
/// // FROM player LEFT JOIN book ...
|
||||
/// // HAVING COUNT(DISTINCT book.id) = 0
|
||||
/// // HAVING COUNT(DISTINCT book.rowid) = 0
|
||||
/// var request = Player.all()
|
||||
/// request = request.having(Player.books.isEmpty)
|
||||
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
|
||||
var request = self
|
||||
let expressionPromise = predicate.prepare(&request)
|
||||
return request.having(expressionPromise.resolve)
|
||||
let (request, expression) = predicate.prepare(self)
|
||||
return request.having(expression)
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,13 @@
|
||||
//
|
||||
// It wraps an SQLQuery, and has an attached type.
|
||||
//
|
||||
// The attached RowDecoder type helps decoding raw database values:
|
||||
// The attached type helps decoding raw database values:
|
||||
//
|
||||
// try dbQueue.read { db in
|
||||
// try playerRequest.fetchAll(db) // [Player]
|
||||
// }
|
||||
//
|
||||
// RowDecoder also helps the compiler validate associated requests:
|
||||
// The attached type also helps the compiler validate associated requests:
|
||||
//
|
||||
// playerRequest.including(required: Player.team) // OK
|
||||
// fruitRequest.including(required: Player.team) // Does not compile
|
||||
@@ -28,7 +28,7 @@
|
||||
/// }
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
public struct QueryInterfaceRequest<RowDecoder> {
|
||||
public struct QueryInterfaceRequest<T> {
|
||||
var query: SQLQuery
|
||||
}
|
||||
|
||||
@@ -38,67 +38,98 @@ extension QueryInterfaceRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: Refinable { }
|
||||
|
||||
// MARK: - DatabaseRegionConvertible
|
||||
|
||||
extension QueryInterfaceRequest: DatabaseRegionConvertible {
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
try SQLQueryGenerator(query: query)
|
||||
.makeSelectStatement(db)
|
||||
.databaseRegion
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLRequestProtocol
|
||||
|
||||
extension QueryInterfaceRequest: SQLRequestProtocol {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func requestSQL(_ context: SQLGenerationContext, forSingleResult singleResult: Bool) throws -> String {
|
||||
let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult)
|
||||
return try generator.requestSQL(context)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - FetchRequest
|
||||
|
||||
extension QueryInterfaceRequest: FetchRequest {
|
||||
public typealias RowDecoder = T
|
||||
|
||||
/// Returns a tuple that contains a prepared statement that is ready to be
|
||||
/// executed, and an eventual row adapter.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter singleResult: A hint as to whether the query should be optimized for a single result.
|
||||
/// - returns: A prepared statement and an eventual row adapter.
|
||||
/// :nodoc:
|
||||
public func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult)
|
||||
let preparedRequest = try generator.makePreparedRequest(db)
|
||||
var query = self.query
|
||||
|
||||
// Optimize query by setting a limit of 1 when appropriate
|
||||
if singleResult && !query.expectsSingleResult {
|
||||
query.limit = SQLLimit(limit: 1, offset: query.limit?.offset)
|
||||
}
|
||||
|
||||
let (statement, adapter) = try SQLQueryGenerator(query).prepare(db)
|
||||
let associations = query.relation.prefetchedAssociations
|
||||
if associations.isEmpty {
|
||||
return preparedRequest
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
} else {
|
||||
// Eager loading of prefetched associations
|
||||
return preparedRequest.with(\.supplementaryFetch) { rows in
|
||||
try prefetch(db, associations: associations, in: rows)
|
||||
}
|
||||
return PreparedRequest(
|
||||
statement: statement,
|
||||
adapter: adapter,
|
||||
supplementaryFetch: { rows in
|
||||
try prefetch(db, associations: associations, in: rows)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try query.fetchCount(db)
|
||||
}
|
||||
|
||||
/// Returns the database region that the request looks into.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
var region = try SQLQueryGenerator(query).makeSelectStatement(db).selectedRegion
|
||||
|
||||
// Iterate all prefetched associations
|
||||
var fifo = query.relation.prefetchedAssociations
|
||||
while !fifo.isEmpty {
|
||||
let association = fifo.removeFirst()
|
||||
|
||||
// Build the query for prefetched rows.
|
||||
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
|
||||
let pivotMappings = try association.pivot.condition.columnMappings(db)
|
||||
let pivotColumns = pivotMappings.map(\.right)
|
||||
let pivotAlias = TableAlias()
|
||||
let prefetchedRelation = association
|
||||
.map(\.pivot.relation, { $0.qualified(with: pivotAlias) })
|
||||
.destinationRelation(fromOriginRows: { _ in [] /* no origin row */ })
|
||||
.annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") })
|
||||
let prefetchedQuery = SQLQuery(relation: prefetchedRelation)
|
||||
|
||||
// Union region
|
||||
try region.formUnion(SQLQueryGenerator(prefetchedQuery).makeSelectStatement(db).selectedRegion)
|
||||
|
||||
// Append nested prefetched associations (support for
|
||||
// A.including(all: A.bs.including(all: B.cs))
|
||||
fifo.append(contentsOf: prefetchedRelation.prefetchedAssociations)
|
||||
}
|
||||
|
||||
return region
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Request Derivation
|
||||
|
||||
extension QueryInterfaceRequest: SelectionRequest {
|
||||
/// Creates a request which selects *selection promise*.
|
||||
// MARK: Request Derivation
|
||||
|
||||
/// Creates a request which selects *selection*.
|
||||
///
|
||||
/// // SELECT id, email FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.select { db in [Column("id"), Column("email")] }
|
||||
/// request = request.select([Column("id"), Column("email")])
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM player
|
||||
/// request
|
||||
/// .select { db in [Column("id")] }
|
||||
/// .select { db in [Column("email")] }
|
||||
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
|
||||
/// .select([Column("id")])
|
||||
/// .select([Column("email")])
|
||||
public func select(_ selection: [SQLSelectable]) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.select(selection) }
|
||||
}
|
||||
|
||||
@@ -182,43 +213,21 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
select(sqlLiteral.sqlSelectable, as: type)
|
||||
}
|
||||
|
||||
/// Creates a request which appends *selection promise*.
|
||||
/// Creates a request which appends *selection*.
|
||||
///
|
||||
/// // SELECT id, email, name FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request
|
||||
/// .select([Column("id"), Column("email")])
|
||||
/// .annotated(with: { db in [Column("name")] })
|
||||
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
|
||||
/// .annotated(with: [Column("name")])
|
||||
public func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.annotated(with: selection) }
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates a request which selects the primary key of the table.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player: TableRecord { ... }
|
||||
///
|
||||
/// let playerIds = dbQueue.read { db in
|
||||
/// try Player.all().selectPrimaryKey(as: Int64.self).fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// For tables that have no explicit primary key, the request selects the
|
||||
/// `rowid` column.
|
||||
///
|
||||
/// For tables whose primary key spans several columns, the current
|
||||
/// implementation also returns a request that selects the `rowid` column.
|
||||
/// Future GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html).
|
||||
public func selectPrimaryKey<RowDecoder>(as type: RowDecoder.Type = RowDecoder.self)
|
||||
-> QueryInterfaceRequest<RowDecoder>
|
||||
{
|
||||
select(SQLPrimaryKeyExpression(tableName: databaseTableName), as: RowDecoder.self)
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: FilteredRequest {
|
||||
// MARK: Request Derivation
|
||||
|
||||
/// Creates a request with the provided *predicate promise* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
///
|
||||
@@ -231,6 +240,8 @@ extension QueryInterfaceRequest: FilteredRequest {
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: OrderedRequest {
|
||||
// MARK: Request Derivation
|
||||
|
||||
/// Creates a request with the provided *orderings promise*.
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name
|
||||
@@ -274,14 +285,16 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: AggregatingRequest {
|
||||
// MARK: Request Derivation
|
||||
|
||||
/// Creates a request grouped according to *expressions promise*.
|
||||
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.group(expressions) }
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *predicate promise* added to the
|
||||
/// Creates a request with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
|
||||
public func having(_ predicate: SQLExpressible) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.having(predicate) }
|
||||
}
|
||||
}
|
||||
@@ -313,32 +326,46 @@ extension QueryInterfaceRequest: _JoinableRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: JoinableRequest where RowDecoder: TableRecord { }
|
||||
extension QueryInterfaceRequest: JoinableRequest where T: TableRecord { }
|
||||
|
||||
extension QueryInterfaceRequest: TableRequest {
|
||||
extension QueryInterfaceRequest: Refinable {
|
||||
|
||||
// MARK: Request Derivation
|
||||
|
||||
/// Creates a request which returns distinct rows.
|
||||
///
|
||||
/// // SELECT DISTINCT * FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.distinct()
|
||||
///
|
||||
/// // SELECT DISTINCT name FROM player
|
||||
/// var request = Player.select(Column("name"))
|
||||
/// request = request.distinct()
|
||||
public func distinct() -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.distinct() }
|
||||
}
|
||||
|
||||
/// Creates a request which expects a single result.
|
||||
///
|
||||
/// It is unlikely you need to call this method. Its net effect is that
|
||||
/// QueryInterfaceRequest does not use any `LIMIT 1` sql clause when you
|
||||
/// call a `fetchOne` method.
|
||||
///
|
||||
/// :nodoc:
|
||||
public var databaseTableName: String {
|
||||
switch query.relation.source {
|
||||
case .table(tableName: let tableName, alias: _):
|
||||
// Use case:
|
||||
//
|
||||
// let request = Player.all()
|
||||
// request.filter(key: ...)
|
||||
// request.filter(keys: ...)
|
||||
// request.orderByPrimaryKey()
|
||||
return tableName
|
||||
case .subquery:
|
||||
// The only current use case for SQLSource.query is the
|
||||
// "trivial count query" (see SQLQuery.countQuery):
|
||||
//
|
||||
// // SELECT COUNT(*) FROM (SELECT * FROM player LIMIT 10)
|
||||
// let request = Player.limit(10)
|
||||
// let count = try request.fetchCount(db)
|
||||
//
|
||||
// This query is currently never wrapped in a QueryInterfaceRequest
|
||||
// So this fatal error can not currently happen.
|
||||
fatalError("Request is not based on a database table")
|
||||
}
|
||||
public func expectingSingleResult() -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.expectingSingleResult() }
|
||||
}
|
||||
|
||||
|
||||
/// Creates a request which fetches *limit* rows, starting at *offset*.
|
||||
///
|
||||
/// // SELECT * FROM player LIMIT 1
|
||||
/// var request = Player.all()
|
||||
/// request = request.limit(1)
|
||||
///
|
||||
/// Any previous limit is replaced.
|
||||
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.limit(limit, offset: offset) }
|
||||
}
|
||||
|
||||
/// Creates a request that allows you to define expressions that target
|
||||
@@ -361,38 +388,10 @@ extension QueryInterfaceRequest: TableRequest {
|
||||
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.qualified(with: alias) }
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { }
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
/// Creates a request which returns distinct rows.
|
||||
///
|
||||
/// // SELECT DISTINCT * FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.distinct()
|
||||
///
|
||||
/// // SELECT DISTINCT name FROM player
|
||||
/// var request = Player.select(Column("name"))
|
||||
/// request = request.distinct()
|
||||
public func distinct() -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.distinct() }
|
||||
}
|
||||
|
||||
/// Creates a request which fetches *limit* rows, starting at *offset*.
|
||||
/// Creates a request bound to type Target.
|
||||
///
|
||||
/// // SELECT * FROM player LIMIT 1
|
||||
/// var request = Player.all()
|
||||
/// request = request.limit(1)
|
||||
///
|
||||
/// Any previous limit is replaced.
|
||||
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest {
|
||||
map(\.query) { $0.limit(limit, offset: offset) }
|
||||
}
|
||||
|
||||
/// Creates a request bound to type RowDecoder.
|
||||
///
|
||||
/// The returned request can fetch if the type RowDecoder is fetchable (Row,
|
||||
/// The returned request can fetch if the type Target is fetchable (Row,
|
||||
/// value, record).
|
||||
///
|
||||
/// // Int?
|
||||
@@ -401,16 +400,68 @@ extension QueryInterfaceRequest {
|
||||
/// .asRequest(of: Int.self) // <--
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// - parameter type: The fetched type RowDecoder
|
||||
/// - returns: A request bound to type RowDecoder.
|
||||
/// - parameter type: The fetched type Target
|
||||
/// - returns: A typed request bound to type Target.
|
||||
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
|
||||
QueryInterfaceRequest<RowDecoder>(query: query)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Batch Delete
|
||||
extension QueryInterfaceRequest {
|
||||
/// Turns a request into a SQLRelation.
|
||||
///
|
||||
/// This method helps initializing associations:
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// // invokes Author.all().relation
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
var relation: SQLRelation {
|
||||
let query = self.query
|
||||
|
||||
// Prevent information loss
|
||||
GRDBPrecondition(!query.isDistinct, "Not implemented: join distinct queries")
|
||||
GRDBPrecondition(query.groupPromise == nil, "Can't join aggregated queries")
|
||||
GRDBPrecondition(query.havingExpressions.isEmpty, "Can't join aggregated queries")
|
||||
GRDBPrecondition(query.limit == nil, "Can't join limited queries")
|
||||
|
||||
return query.relation
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
extension QueryInterfaceRequest: TableRequest {
|
||||
/// :nodoc:
|
||||
public var databaseTableName: String {
|
||||
switch query.relation.source {
|
||||
case .table(tableName: let tableName, alias: _):
|
||||
// Use case:
|
||||
//
|
||||
// let request = Player.all()
|
||||
// request.filter(key: ...)
|
||||
// request.filter(keys: ...)
|
||||
// request.orderByPrimaryKey()
|
||||
return tableName
|
||||
case .query:
|
||||
// The only current use case for SQLSource.query is the
|
||||
// "trivial count query" (see SQLQuery.countQuery):
|
||||
//
|
||||
// // SELECT COUNT(*) FROM (SELECT * FROM player LIMIT 10)
|
||||
// let request = Player.limit(10)
|
||||
// let count = try request.fetchCount(db)
|
||||
//
|
||||
// This query is currently never wrapped in a QueryInterfaceRequest
|
||||
// So this fatal error can not currently happen.
|
||||
fatalError("Request is not based on a database table")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: DerivableRequest where T: TableRecord { }
|
||||
|
||||
extension QueryInterfaceRequest where T: MutablePersistableRecord {
|
||||
|
||||
// MARK: Batch Delete
|
||||
|
||||
/// Deletes matching rows; returns the number of deleted rows.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -418,14 +469,12 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public func deleteAll(_ db: Database) throws -> Int {
|
||||
try SQLQueryGenerator(query: query).makeDeleteStatement(db).execute()
|
||||
try SQLQueryGenerator(query).makeDeleteStatement(db).execute()
|
||||
return db.changesCount
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Batch Update
|
||||
|
||||
extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
|
||||
// MARK: Batch Update
|
||||
|
||||
/// Updates matching rows; returns the number of updated rows.
|
||||
///
|
||||
/// For example:
|
||||
@@ -448,7 +497,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
_ assignments: [ColumnAssignment]) throws -> Int
|
||||
{
|
||||
let conflictResolution = conflictResolution ?? RowDecoder.persistenceConflictPolicy.conflictResolutionForUpdate
|
||||
guard let updateStatement = try SQLQueryGenerator(query: query).makeUpdateStatement(
|
||||
guard let updateStatement = try SQLQueryGenerator(query).makeUpdateStatement(
|
||||
db,
|
||||
conflictResolution: conflictResolution,
|
||||
assignments: assignments) else
|
||||
@@ -497,7 +546,7 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [
|
||||
return
|
||||
}
|
||||
|
||||
// CAUTION: Keep this code in sync with prefetchedRegion(_:_:)
|
||||
// CAUTION: Keep this code in sync with QueryInterfaceRequest.databaseRegion(_:)
|
||||
for association in associations {
|
||||
let pivotMappings = try association.pivot.condition.columnMappings(db)
|
||||
|
||||
@@ -536,7 +585,7 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [
|
||||
// TODO: can we remove those grdb_ columns now that grouping has been done?
|
||||
}
|
||||
|
||||
let groupingIndexes = firstRow.indexes(forColumns: pivotMappings.map(\.left))
|
||||
let groupingIndexes = firstRow.indexes(ofColumns: pivotMappings.map(\.left))
|
||||
for row in rows {
|
||||
let groupingKey = groupingIndexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
|
||||
let prefetchedRows = prefetchedRows[groupingKey, default: []]
|
||||
@@ -545,32 +594,6 @@ private func prefetch(_ db: Database, associations: [SQLAssociation], in rows: [
|
||||
}
|
||||
}
|
||||
|
||||
// Returns the region of prefetched associations
|
||||
func prefetchedRegion(_ db: Database, associations: [SQLAssociation]) throws -> DatabaseRegion {
|
||||
try associations.reduce(into: DatabaseRegion()) { (region, association) in
|
||||
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
|
||||
let pivotMappings = try association.pivot.condition.columnMappings(db)
|
||||
let pivotColumns = pivotMappings.map(\.right)
|
||||
let pivotAlias = TableAlias()
|
||||
let prefetchedRelation = association
|
||||
.map(\.pivot.relation, { $0.qualified(with: pivotAlias) })
|
||||
// Use a `NullRow` in order to make sure all join condition
|
||||
// columns are made visible to SQLite, and present in the
|
||||
// selected region:
|
||||
// ... JOIN right ON right.leftId IS NULL
|
||||
// ^ content of the NullRow
|
||||
.destinationRelation(fromOriginRows: { _ in [NullRow()] })
|
||||
.annotated(with: pivotColumns.map { pivotAlias[Column($0)].forKey("grdb_\($0)") })
|
||||
let prefetchedQuery = SQLQuery(relation: prefetchedRelation)
|
||||
|
||||
// Union prefetched region
|
||||
let prefetchedRegion = try SQLQueryGenerator(query: prefetchedQuery)
|
||||
.makeSelectStatement(db)
|
||||
.databaseRegion // contains region of nested associations
|
||||
region.formUnion(prefetchedRegion)
|
||||
}
|
||||
}
|
||||
|
||||
extension Array where Element == Row {
|
||||
/// - precondition: Columns all exist in all rows. All rows have the same
|
||||
/// columnns, in the same order.
|
||||
@@ -578,7 +601,7 @@ extension Array where Element == Row {
|
||||
guard let firstRow = first else {
|
||||
return [:]
|
||||
}
|
||||
let indexes = firstRow.indexes(forColumns: columns)
|
||||
let indexes = firstRow.indexes(ofColumns: columns)
|
||||
return Dictionary(grouping: self, by: { row in
|
||||
indexes.map { row.impl.databaseValue(atUncheckedIndex: $0) }
|
||||
})
|
||||
@@ -587,9 +610,9 @@ extension Array where Element == Row {
|
||||
|
||||
extension Row {
|
||||
/// - precondition: Columns all exist in the row.
|
||||
fileprivate func indexes(forColumns columns: [String]) -> [Int] {
|
||||
fileprivate func indexes(ofColumns columns: [String]) -> [Int] {
|
||||
columns.map { column -> Int in
|
||||
guard let index = index(forColumn: column) else {
|
||||
guard let index = index(ofColumn: column) else {
|
||||
fatalError("Column \(column) is not selected")
|
||||
}
|
||||
return index
|
||||
@@ -613,10 +636,10 @@ public struct ColumnAssignment {
|
||||
var column: ColumnExpression
|
||||
var value: SQLExpressible
|
||||
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
try column.expressionSQL(context, wrappedInParenthesis: false) +
|
||||
func sql(_ context: inout SQLGenerationContext) -> String {
|
||||
column.expressionSQL(&context, wrappedInParenthesis: false) +
|
||||
" = " +
|
||||
value.sqlExpression.expressionSQL(context, wrappedInParenthesis: false)
|
||||
value.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,32 +6,6 @@
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol SelectionRequest {
|
||||
/// Creates a request which selects *selection promise*.
|
||||
///
|
||||
/// // SELECT id, email FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request.select { db in [Column("id"), Column("email") })
|
||||
///
|
||||
/// Any previous selection is replaced:
|
||||
///
|
||||
/// // SELECT email FROM player
|
||||
/// request
|
||||
/// .select { db in [Column("id")] }
|
||||
/// .select { db in [Column("email")] }
|
||||
func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self
|
||||
|
||||
/// Creates a request which appends *selection promise*.
|
||||
///
|
||||
/// // SELECT id, email, name FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request
|
||||
/// .select([Column("id"), Column("email")])
|
||||
/// .annotated(with: { db in [Column("name")] })
|
||||
func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
extension SelectionRequest {
|
||||
/// Creates a request which selects *selection*.
|
||||
///
|
||||
/// // SELECT id, email FROM player
|
||||
@@ -44,10 +18,20 @@ extension SelectionRequest {
|
||||
/// request
|
||||
/// .select([Column("id")])
|
||||
/// .select([Column("email")])
|
||||
public func select(_ selection: [SQLSelectable]) -> Self {
|
||||
select { _ in selection }
|
||||
}
|
||||
func select(_ selection: [SQLSelectable]) -> Self
|
||||
|
||||
/// Creates a request which appends *selection*.
|
||||
///
|
||||
/// // SELECT id, email, name FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request
|
||||
/// .select([Column("id"), Column("email")])
|
||||
/// .annotated(with: [Column("name")])
|
||||
func annotated(with selection: [SQLSelectable]) -> Self
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
extension SelectionRequest {
|
||||
/// Creates a request which selects *selection*.
|
||||
///
|
||||
/// // SELECT id, email FROM player
|
||||
@@ -107,18 +91,7 @@ extension SelectionRequest {
|
||||
/// .select(literal: SQLLiteral(sql: "email"))
|
||||
public func select(literal sqlLiteral: SQLLiteral) -> Self {
|
||||
// NOT TESTED
|
||||
select(sqlLiteral.sqlSelectable)
|
||||
}
|
||||
|
||||
/// Creates a request which appends *selection*.
|
||||
///
|
||||
/// // SELECT id, email, name FROM player
|
||||
/// var request = Player.all()
|
||||
/// request = request
|
||||
/// .select([Column("id"), Column("email")])
|
||||
/// .annotated(with: [Column("name")])
|
||||
public func annotated(with selection: [SQLSelectable]) -> Self {
|
||||
annotated(with: { _ in selection })
|
||||
return select(sqlLiteral.sqlSelectable)
|
||||
}
|
||||
|
||||
/// Creates a request which appends *selection*.
|
||||
@@ -148,10 +121,23 @@ public protocol FilteredRequest {
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter { db in true }
|
||||
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self
|
||||
|
||||
/// Creates a request which expects a single result.
|
||||
///
|
||||
/// Requests expecting a single result may ignore the second parameter of
|
||||
/// the `FetchRequest.prepare(_:forSingleResult:)` method, in order to
|
||||
/// produce sharply tailored SQL.
|
||||
///
|
||||
/// This method has a default implementation which returns self.
|
||||
func expectingSingleResult() -> Self
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
extension FilteredRequest {
|
||||
public func expectingSingleResult() -> Self {
|
||||
self
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
///
|
||||
@@ -188,7 +174,7 @@ extension FilteredRequest {
|
||||
/// request = request.filter(literal: "name = \("O'Brien")")
|
||||
public func filter(literal sqlLiteral: SQLLiteral) -> Self {
|
||||
// NOT TESTED
|
||||
filter(sqlLiteral.sqlExpression)
|
||||
return filter(sqlLiteral.sqlExpression)
|
||||
}
|
||||
|
||||
/// Creates a request that matches nothing.
|
||||
@@ -248,13 +234,19 @@ extension TableRequest where Self: FilteredRequest {
|
||||
-> Self
|
||||
where Sequence.Element: DatabaseValueConvertible
|
||||
{
|
||||
var request = self
|
||||
let keys = Array(keys)
|
||||
if keys.isEmpty {
|
||||
switch keys.count {
|
||||
case 0:
|
||||
return none()
|
||||
case 1:
|
||||
request = request.expectingSingleResult()
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
let databaseTableName = self.databaseTableName
|
||||
return filter { db in
|
||||
return request.filter { db in
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
@@ -279,12 +271,18 @@ extension TableRequest where Self: FilteredRequest {
|
||||
/// When executed, this request raises a fatal error if there is no unique
|
||||
/// index on the key columns.
|
||||
public func filter(keys: [[String: DatabaseValueConvertible?]]) -> Self {
|
||||
if keys.isEmpty {
|
||||
var request = self
|
||||
switch keys.count {
|
||||
case 0:
|
||||
return none()
|
||||
case 1:
|
||||
request = request.expectingSingleResult()
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
let databaseTableName = self.databaseTableName
|
||||
return filter { db in
|
||||
return request.filter { db in
|
||||
try keys
|
||||
.map { key in
|
||||
// Prevent filter(keys: [["foo": 1, "bar": 2]]) where
|
||||
@@ -346,9 +344,9 @@ public protocol AggregatingRequest {
|
||||
/// Creates a request grouped according to *expressions promise*.
|
||||
func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self
|
||||
|
||||
/// Creates a request with the provided *predicate promise* added to the
|
||||
/// Creates a request with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self
|
||||
func having(_ predicate: SQLExpressible) -> Self
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@@ -371,13 +369,7 @@ extension AggregatingRequest {
|
||||
/// Creates a request with a new grouping.
|
||||
public func group(literal sqlLiteral: SQLLiteral) -> Self {
|
||||
// NOT TESTED
|
||||
group(sqlLiteral.sqlExpression)
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *predicate* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
public func having(_ predicate: SQLExpressible) -> Self {
|
||||
having { _ in predicate }
|
||||
return group(sqlLiteral.sqlExpression)
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *sql* added to the
|
||||
@@ -390,7 +382,7 @@ extension AggregatingRequest {
|
||||
/// eventual set of already applied predicates.
|
||||
public func having(literal sqlLiteral: SQLLiteral) -> Self {
|
||||
// NOT TESTED
|
||||
having(sqlLiteral.sqlExpression)
|
||||
return having(sqlLiteral.sqlExpression)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -504,7 +496,7 @@ extension OrderedRequest {
|
||||
/// .order(sql: "name")
|
||||
public func order(literal sqlLiteral: SQLLiteral) -> Self {
|
||||
// NOT TESTED
|
||||
order(sqlLiteral.sqlOrderingTerm)
|
||||
return order(sqlLiteral.sqlOrderingTerm)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ public protocol ColumnExpression: SQLExpression {
|
||||
extension ColumnExpression {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
name.quotedDatabaseIdentifier
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ struct QualifiedColumn: ColumnExpression {
|
||||
self.alias = alias
|
||||
}
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
if let qualifier = context.qualifier(for: alias) {
|
||||
return qualifier.quotedDatabaseIdentifier + "." + name.quotedDatabaseIdentifier
|
||||
}
|
||||
@@ -82,7 +82,7 @@ struct QualifiedColumn: ColumnExpression {
|
||||
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
// Never requalify
|
||||
self
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -41,4 +41,10 @@ struct DatabasePromise<T> {
|
||||
try transform(self.resolve(db))
|
||||
}
|
||||
}
|
||||
|
||||
func flatMap<U>(_ transform: @escaping (T) -> DatabasePromise<U>) -> DatabasePromise<U> {
|
||||
DatabasePromise<U> { db in
|
||||
try transform(self.resolve(db)).resolve(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,17 @@ public /* TODO: internal */ struct SQLAssociation {
|
||||
SQLAssociation(steps: other.steps + steps)
|
||||
}
|
||||
|
||||
func associationForFirst() -> Self {
|
||||
SQLAssociation(steps: steps.map { step in
|
||||
switch step.cardinality {
|
||||
case .toOne:
|
||||
return step
|
||||
case .toMany:
|
||||
return step.map(\.relation) { $0.with(\.firstOnly, true) }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Given an origin alias and rows, returns the destination of the
|
||||
/// association as a relation.
|
||||
///
|
||||
@@ -135,16 +146,13 @@ public /* TODO: internal */ struct SQLAssociation {
|
||||
/// HasMany in the above examples, but also for indirect associations such
|
||||
/// as HasManyThrough, which have any number of pivot relations between the
|
||||
/// origin and the destination.
|
||||
func destinationRelation<Row>(
|
||||
fromOriginRows originRows: @escaping (Database) throws -> [Row])
|
||||
-> SQLRelation
|
||||
where Row: ColumnAddressable
|
||||
{
|
||||
// Filter the pivot: `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)`
|
||||
func destinationRelation(fromOriginRows originRows: @escaping (Database) throws -> [Row]) -> SQLRelation {
|
||||
// Filter the pivot
|
||||
let pivot = self.pivot
|
||||
let filteredPivotRelation = pivot.relation.filter { db in
|
||||
let filteredPivotRelation = pivot.relation.filter({ db in
|
||||
// `pivot.originId = 123` or `pivot.originId IN (1, 2, 3)`
|
||||
try pivot.condition.filteringExpression(db, leftRows: originRows(db))
|
||||
}
|
||||
})
|
||||
|
||||
if steps.count == 1 {
|
||||
// This is a direct join from origin to destination, without
|
||||
@@ -179,11 +187,11 @@ public /* TODO: internal */ struct SQLAssociation {
|
||||
let relation = step.relation
|
||||
.selectOnly([])
|
||||
.filteringChildren({
|
||||
switch $0.kind {
|
||||
case .allPrefetched, .allNotPrefetched: return false
|
||||
case .oneRequired, .oneOptional: return true
|
||||
}
|
||||
})
|
||||
switch $0.kind {
|
||||
case .allPrefetched, .allNotPrefetched: return false
|
||||
case .oneRequired, .oneOptional: return true
|
||||
}
|
||||
})
|
||||
|
||||
// Don't interfere with user-defined keys that could be added later
|
||||
let key = step.key.map(\.baseName) { "grdb_\($0)" }
|
||||
@@ -213,7 +221,7 @@ struct SQLAssociationStep: Refinable {
|
||||
case .toOne:
|
||||
return true
|
||||
case .toMany:
|
||||
return false
|
||||
return relation.firstOnly
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -87,8 +87,8 @@ extension SQLCollatedExpression: SQLOrderingTerm {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try sqlExpression.orderingTermSQL(context)
|
||||
public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
sqlExpression.orderingTermSQL(&context)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
@@ -9,16 +9,13 @@ public protocol SQLCollection {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an SQL string that represents the collection.
|
||||
func collectionSQL(_ context: SQLGenerationContext) throws -> String
|
||||
func collectionSQL(_ context: inout SQLGenerationContext) -> String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an expression that check whether the collection contains
|
||||
/// the expression.
|
||||
func contains(_ value: SQLExpressible) -> SQLExpression
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func qualifiedCollection(with alias: TableAlias) -> SQLCollection
|
||||
}
|
||||
|
||||
|
||||
@@ -43,9 +40,13 @@ extension SQLCollection {
|
||||
struct SQLExpressionsArray: SQLCollection {
|
||||
let expressions: [SQLExpression]
|
||||
|
||||
func collectionSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try expressions
|
||||
.map { try $0.expressionSQL(context, wrappedInParenthesis: false) }
|
||||
init<S: Sequence>(_ expressions: S) where S.Iterator.Element: SQLExpressible {
|
||||
self.expressions = expressions.map(\.sqlExpression)
|
||||
}
|
||||
|
||||
func collectionSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
expressions
|
||||
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
|
||||
@@ -61,8 +62,4 @@ struct SQLExpressionsArray: SQLCollection {
|
||||
// ["foo", "bar"].contains(Column("name")) => name IN ('foo', 'bar')
|
||||
return SQLExpressionContains(value, self)
|
||||
}
|
||||
|
||||
func qualifiedCollection(with alias: TableAlias) -> SQLCollection {
|
||||
SQLExpressionsArray(expressions: expressions.map { $0.qualifiedExpression(with: alias) })
|
||||
}
|
||||
}
|
||||
@@ -64,8 +64,8 @@ extension SQLExpressible where Self: SQLOrderingTerm {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try sqlExpression.expressionSQL(context, wrappedInParenthesis: false)
|
||||
public func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,14 +75,14 @@ extension SQLExpressible where Self: SQLSelectable {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try sqlExpression.expressionSQL(context, wrappedInParenthesis: false)
|
||||
public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func countedSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try sqlExpression.expressionSQL(context, wrappedInParenthesis: false)
|
||||
public func countedSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
extension SQLExpression {
|
||||
/// The expression as a quoted SQL literal (not public in order to avoid abuses)
|
||||
///
|
||||
/// try "foo'bar".databaseValue.quotedSQL(db) // "'foo''bar'""
|
||||
func quotedSQL(_ db: Database) throws -> String {
|
||||
let context = SQLGenerationContext(db, argumentsSink: .forRawSQL)
|
||||
return try expressionSQL(context, wrappedInParenthesis: false)
|
||||
/// "foo'bar".databaseValue.quotedSQL() // "'foo''bar'""
|
||||
func quotedSQL() -> String {
|
||||
var context = SQLGenerationContext.rawSQLContext
|
||||
return expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,13 +70,11 @@ public struct SQLExpressionUnary: SQLExpression {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
if wrappedInParenthesis {
|
||||
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
|
||||
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
|
||||
}
|
||||
return try op.sql
|
||||
+ (op.needsRightSpace ? " " : "")
|
||||
+ expression.expressionSQL(context, wrappedInParenthesis: true)
|
||||
return op.sql + (op.needsRightSpace ? " " : "") + expression.expressionSQL(&context, wrappedInParenthesis: true)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
@@ -168,14 +166,14 @@ public struct SQLExpressionBinary: SQLExpression {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
if wrappedInParenthesis {
|
||||
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
|
||||
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
|
||||
}
|
||||
return try """
|
||||
\(lhs.expressionSQL(context, wrappedInParenthesis: true)) \
|
||||
return """
|
||||
\(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \
|
||||
\(op.sql) \
|
||||
\(rhs.expressionSQL(context, wrappedInParenthesis: true))
|
||||
\(rhs.expressionSQL(&context, wrappedInParenthesis: true))
|
||||
"""
|
||||
}
|
||||
|
||||
@@ -265,14 +263,14 @@ struct SQLExpressionBinaryReduce: SQLExpression {
|
||||
}
|
||||
}
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
guard let first = expressions.first else {
|
||||
return try op.neutralValue.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
|
||||
return op.neutralValue.sqlExpression.expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
if expressions.count == 1 {
|
||||
return try first.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
|
||||
return first.expressionSQL(&context, wrappedInParenthesis: wrappedInParenthesis)
|
||||
}
|
||||
let expressionSQLs = try expressions.map { try $0.expressionSQL(context, wrappedInParenthesis: true) }
|
||||
let expressionSQLs = expressions.map { $0.expressionSQL(&context, wrappedInParenthesis: true) }
|
||||
let joiner = " \(op.sql) "
|
||||
if wrappedInParenthesis {
|
||||
return "(\(expressionSQLs.joined(separator: joiner)))"
|
||||
@@ -311,22 +309,6 @@ struct SQLExpressionBinaryReduce: SQLExpression {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
var truthComponents: [SQLExpression] {
|
||||
guard let first = expressions.first else {
|
||||
return op.neutralValue.truthComponents
|
||||
}
|
||||
|
||||
if expressions.count == 1 {
|
||||
return first.truthComponents
|
||||
}
|
||||
|
||||
if op == .and {
|
||||
return expressions.flatMap(\.truthComponents)
|
||||
}
|
||||
|
||||
return [self]
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Element == SQLExpression {
|
||||
@@ -394,14 +376,14 @@ struct SQLExpressionEqual: SQLExpression {
|
||||
}
|
||||
}
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
if wrappedInParenthesis {
|
||||
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
|
||||
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
|
||||
}
|
||||
return try """
|
||||
\(lhs.expressionSQL(context, wrappedInParenthesis: true)) \
|
||||
return """
|
||||
\(lhs.expressionSQL(&context, wrappedInParenthesis: true)) \
|
||||
\(op.rawValue) \
|
||||
\(rhs.expressionSQL(context, wrappedInParenthesis: true))
|
||||
\(rhs.expressionSQL(&context, wrappedInParenthesis: true))
|
||||
"""
|
||||
}
|
||||
|
||||
@@ -465,14 +447,14 @@ struct SQLExpressionContains: SQLExpression {
|
||||
self.isNegated = negated
|
||||
}
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
if wrappedInParenthesis {
|
||||
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
|
||||
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
|
||||
}
|
||||
return try """
|
||||
\(expression.expressionSQL(context, wrappedInParenthesis: true)) \
|
||||
return """
|
||||
\(expression.expressionSQL(&context, wrappedInParenthesis: true)) \
|
||||
\(isNegated ? "NOT IN" : "IN") \
|
||||
(\(collection.collectionSQL(context)))
|
||||
(\(collection.collectionSQL(&context)))
|
||||
"""
|
||||
}
|
||||
|
||||
@@ -481,10 +463,7 @@ struct SQLExpressionContains: SQLExpression {
|
||||
}
|
||||
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
return SQLExpressionContains(
|
||||
expression.qualifiedExpression(with: alias),
|
||||
collection.qualifiedCollection(with: alias),
|
||||
negated: isNegated)
|
||||
SQLExpressionContains(expression.qualifiedExpression(with: alias), collection, negated: isNegated)
|
||||
}
|
||||
|
||||
func matchedRowIds(rowIdName: String?) -> Set<Int64>? {
|
||||
@@ -536,16 +515,16 @@ struct SQLExpressionBetween: SQLExpression {
|
||||
self.isNegated = negated
|
||||
}
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
if wrappedInParenthesis {
|
||||
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
|
||||
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
|
||||
}
|
||||
return try """
|
||||
\(expression.expressionSQL(context, wrappedInParenthesis: true)) \
|
||||
return """
|
||||
\(expression.expressionSQL(&context, wrappedInParenthesis: true)) \
|
||||
\(isNegated ? "NOT BETWEEN" : "BETWEEN") \
|
||||
\(lowerBound.expressionSQL(context, wrappedInParenthesis: true)) \
|
||||
\(lowerBound.expressionSQL(&context, wrappedInParenthesis: true)) \
|
||||
AND \
|
||||
\(upperBound.expressionSQL(context, wrappedInParenthesis: true))
|
||||
\(upperBound.expressionSQL(&context, wrappedInParenthesis: true))
|
||||
"""
|
||||
}
|
||||
|
||||
@@ -629,11 +608,11 @@ public struct SQLExpressionFunction: SQLExpression {
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
public func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
var sql = functionName.sql
|
||||
sql += "("
|
||||
sql += try arguments
|
||||
.map { try $0.expressionSQL(context, wrappedInParenthesis: false) }
|
||||
sql += arguments
|
||||
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
|
||||
.joined(separator: ", ")
|
||||
sql += ")"
|
||||
return sql
|
||||
@@ -660,8 +639,8 @@ struct SQLExpressionCount: SQLExpression {
|
||||
self.counted = counted
|
||||
}
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
try "COUNT(" + counted.countedSQL(context) + ")"
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
"COUNT(" + counted.countedSQL(&context) + ")"
|
||||
}
|
||||
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
@@ -682,8 +661,8 @@ struct SQLExpressionCountDistinct: SQLExpression {
|
||||
self.counted = counted
|
||||
}
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
try "COUNT(DISTINCT " + counted.expressionSQL(context, wrappedInParenthesis: false) + ")"
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
"COUNT(DISTINCT " + counted.expressionSQL(&context, wrappedInParenthesis: false) + ")"
|
||||
}
|
||||
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
@@ -710,12 +689,12 @@ struct SQLExpressionIsEmpty: SQLExpression {
|
||||
SQLExpressionIsEmpty(countExpression, isEmpty: !isEmpty)
|
||||
}
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
if wrappedInParenthesis {
|
||||
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
|
||||
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
|
||||
}
|
||||
return try """
|
||||
\(countExpression.expressionSQL(context, wrappedInParenthesis: true)) \
|
||||
return """
|
||||
\(countExpression.expressionSQL(&context, wrappedInParenthesis: true)) \
|
||||
\(isEmpty ? "= 0" : "> 0")
|
||||
"""
|
||||
}
|
||||
@@ -731,14 +710,14 @@ struct TableMatchExpression: SQLExpression {
|
||||
var alias: TableAlias
|
||||
var pattern: SQLExpression
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
if wrappedInParenthesis {
|
||||
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
|
||||
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
|
||||
}
|
||||
return try """
|
||||
return """
|
||||
\(context.resolvedName(for: alias).quotedDatabaseIdentifier) \
|
||||
MATCH \
|
||||
\(pattern.expressionSQL(context, wrappedInParenthesis: true))
|
||||
\(pattern.expressionSQL(&context, wrappedInParenthesis: true))
|
||||
"""
|
||||
}
|
||||
|
||||
@@ -764,12 +743,12 @@ struct SQLExpressionCollate: SQLExpression {
|
||||
self.collationName = collationName
|
||||
}
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
if wrappedInParenthesis {
|
||||
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
|
||||
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
|
||||
}
|
||||
return try """
|
||||
\(expression.expressionSQL(context, wrappedInParenthesis: false)) \
|
||||
return """
|
||||
\(expression.expressionSQL(&context, wrappedInParenthesis: false)) \
|
||||
COLLATE \
|
||||
\(collationName.rawValue)
|
||||
"""
|
||||
@@ -779,68 +758,3 @@ struct SQLExpressionCollate: SQLExpression {
|
||||
SQLExpressionCollate(expression.qualifiedExpression(with: alias), collationName: collationName)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLPrimaryKeyExpression
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLPrimaryKeyExpression is the primary key of a table.
|
||||
///
|
||||
/// For tables that have no explicit primary key, SQLPrimaryKeyExpression is the
|
||||
/// `rowid` column.
|
||||
///
|
||||
/// For tables whose primary key spans several columns, the current
|
||||
/// implementation of SQLPrimaryKeyExpression also is the `rowid` column. Future
|
||||
/// GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player: TableRecord { ... }
|
||||
///
|
||||
/// let player = dbQueue.read { db in
|
||||
/// try Player.filter(Player.primaryKey == 12).fetchOne(db)
|
||||
/// }
|
||||
public struct SQLPrimaryKeyExpression: SQLExpression {
|
||||
let tableName: String
|
||||
|
||||
/// Support for SQLPrimaryKeyExpression and SQLQualifiedPrimaryKeyExpression
|
||||
fileprivate static func primaryKeyColumn(_ db: Database, tableName: String) throws -> Column {
|
||||
let columns = try db.primaryKey(tableName).columns
|
||||
if columns.count == 1 {
|
||||
return Column(columns[0])
|
||||
} else {
|
||||
return Column.rowID
|
||||
}
|
||||
}
|
||||
|
||||
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
try SQLPrimaryKeyExpression
|
||||
.primaryKeyColumn(context.db, tableName: tableName)
|
||||
.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
|
||||
}
|
||||
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
SQLQualifiedPrimaryKeyExpression(tableName: tableName, alias: alias)
|
||||
}
|
||||
}
|
||||
|
||||
struct SQLQualifiedPrimaryKeyExpression: SQLExpression {
|
||||
let tableName: String
|
||||
let alias: TableAlias
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
GRDBPrecondition(
|
||||
tableName.lowercased() == alias.tableName.lowercased(),
|
||||
"Table names don't match: \(tableName) and \(alias.tableName)")
|
||||
|
||||
return try SQLPrimaryKeyExpression
|
||||
.primaryKeyColumn(context.db, tableName: tableName)
|
||||
.qualifiedExpression(with: alias)
|
||||
.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
|
||||
}
|
||||
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
// Never requalify
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ public protocol SQLExpression: SQLSpecificExpressible, SQLSelectable, SQLOrderin
|
||||
/// statement arguments.
|
||||
/// - parameter wrappedInParenthesis: If true, the returned SQL should be
|
||||
/// wrapped inside parenthesis.
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
@@ -41,27 +41,6 @@ public protocol SQLExpression: SQLSpecificExpressible, SQLSelectable, SQLOrderin
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func qualifiedExpression(with alias: TableAlias) -> SQLExpression
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The elements of the returned array, when joined with the AND operator,
|
||||
/// are guaranteed to have the same truth value as the receiver.
|
||||
///
|
||||
/// Those truth components allow easier introspection of the expression.
|
||||
/// For example:
|
||||
///
|
||||
/// // No change:
|
||||
/// // [Column("a")]
|
||||
/// Column("a").truthComponents
|
||||
///
|
||||
/// // Erase a SQLExpressionBinaryReduce `and` expression:
|
||||
/// // [Column("a"), Column("b")]
|
||||
/// [Column("a"), Column("b")].joined(operator: .and).truthComponents
|
||||
///
|
||||
/// // Erase a SQLExpressionBinaryReduce `or` expression:
|
||||
/// // [Column("a")]
|
||||
/// [Column("a")].joined(operator: .or).truthComponents
|
||||
var truthComponents: [SQLExpression] { get }
|
||||
}
|
||||
|
||||
extension SQLExpression {
|
||||
@@ -104,13 +83,6 @@ extension SQLExpression {
|
||||
public func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm {
|
||||
qualifiedExpression(with: alias)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The default implementation returns [self]
|
||||
///
|
||||
/// :nodoc:
|
||||
public var truthComponents: [SQLExpression] { [self] }
|
||||
}
|
||||
|
||||
// SQLExpression: SQLExpressible
|
||||
@@ -154,11 +126,11 @@ struct SQLExpressionNot: SQLExpression {
|
||||
self.expression = expression
|
||||
}
|
||||
|
||||
func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
func expressionSQL(_ context: inout SQLGenerationContext, wrappedInParenthesis: Bool) -> String {
|
||||
if wrappedInParenthesis {
|
||||
return try "(\(expressionSQL(context, wrappedInParenthesis: false)))"
|
||||
return "(\(expressionSQL(&context, wrappedInParenthesis: false)))"
|
||||
}
|
||||
return try "NOT \(expression.expressionSQL(context, wrappedInParenthesis: true))"
|
||||
return "NOT \(expression.expressionSQL(&context, wrappedInParenthesis: true))"
|
||||
}
|
||||
|
||||
var negated: SQLExpression {
|
||||
@@ -169,3 +141,22 @@ struct SQLExpressionNot: SQLExpression {
|
||||
SQLExpressionNot(expression.qualifiedExpression(with: alias))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension Database {
|
||||
/// Returns an expression for the primary key of this table.
|
||||
///
|
||||
/// When the table as a primary key made of several columns, we return
|
||||
/// the rowid column. Eventually we'll support
|
||||
/// [row values](https://www.sqlite.org/rowvalue.html) and be able to deal
|
||||
/// with WITHOUT ROWID tables.
|
||||
func primaryKeyExpression(_ tableName: String) throws -> SQLExpression {
|
||||
let columns = try primaryKey(tableName).columns
|
||||
if columns.count == 1 {
|
||||
return Column(columns[0])
|
||||
} else {
|
||||
return Column.rowID
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,7 +144,7 @@ public func sum(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
|
||||
|
||||
// MARK: - String functions
|
||||
// MARK: - Swift String functions
|
||||
|
||||
/// :nodoc:
|
||||
extension SQLSpecificExpressible {
|
||||
@@ -187,7 +187,7 @@ extension SQLSpecificExpressible {
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(OSX 10.11, watchOS 3.0, *)
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public var localizedCapitalized: SQLExpression {
|
||||
DatabaseFunction.localizedCapitalize(sqlExpression)
|
||||
}
|
||||
@@ -198,7 +198,7 @@ extension SQLSpecificExpressible {
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedLowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(OSX 10.11, watchOS 3.0, *)
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public var localizedLowercased: SQLExpression {
|
||||
DatabaseFunction.localizedLowercase(sqlExpression)
|
||||
}
|
||||
@@ -209,112 +209,8 @@ extension SQLSpecificExpressible {
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedUppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(OSX 10.11, watchOS 3.0, *)
|
||||
@available(iOS 9.0, OSX 10.11, watchOS 3.0, *)
|
||||
public var localizedUppercased: SQLExpression {
|
||||
DatabaseFunction.localizedUppercase(sqlExpression)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Date functions
|
||||
|
||||
/// A date modifier for SQLite date functions.
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/lang_datefunc.html
|
||||
public enum SQLDateModifier: SQLExpression {
|
||||
case day(Int)
|
||||
case hour(Int)
|
||||
case minute(Int)
|
||||
case second(Double)
|
||||
case month(Int)
|
||||
case year(Int)
|
||||
case startOfMonth
|
||||
case startOfYear
|
||||
case startOfDay
|
||||
case weekday(Int)
|
||||
case unixEpoch
|
||||
case localTime
|
||||
case utc
|
||||
|
||||
var rawValue: String {
|
||||
switch self {
|
||||
case let .day(value):
|
||||
return "\(value) days"
|
||||
case let .hour(value):
|
||||
return "\(value) hours"
|
||||
case let .minute(value):
|
||||
return "\(value) minutes"
|
||||
case let .second(value):
|
||||
return "\(value) seconds"
|
||||
case let .month(value):
|
||||
return "\(value) months"
|
||||
case let .year(value):
|
||||
return "\(value) years"
|
||||
case .startOfMonth:
|
||||
return "start of month"
|
||||
case .startOfYear:
|
||||
return "start of year"
|
||||
case .startOfDay:
|
||||
return "start of day"
|
||||
case let .weekday(value):
|
||||
return "weekday \(value)"
|
||||
case .unixEpoch:
|
||||
return "unixepoch"
|
||||
case .localTime:
|
||||
return "localtime"
|
||||
case .utc:
|
||||
return "utc"
|
||||
}
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func expressionSQL(_ context: SQLGenerationContext, wrappedInParenthesis: Bool) throws -> String {
|
||||
try rawValue.databaseValue.expressionSQL(context, wrappedInParenthesis: wrappedInParenthesis)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func qualifiedExpression(with alias: TableAlias) -> SQLExpression {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: JULIANDAY(...)
|
||||
|
||||
extension SQLFunctionName {
|
||||
/// The `JULIANDAY` function name
|
||||
public static let julianDay = SQLFunctionName("JULIANDAY")
|
||||
}
|
||||
|
||||
/// Returns an expression that evaluates the `JULIANDAY` SQL function.
|
||||
///
|
||||
/// // JULIANDAY(date)
|
||||
/// julianDay(Column("date"))
|
||||
///
|
||||
/// // JULIANDAY(date, '1 days')
|
||||
/// julianDay(Column("date"), .day(1))
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/lang_datefunc.html
|
||||
public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression {
|
||||
SQLExpressionFunction(.julianDay, arguments: [value.sqlExpression] + modifiers)
|
||||
}
|
||||
|
||||
// MARK: DATETIME(...)
|
||||
|
||||
extension SQLFunctionName {
|
||||
/// The `DATETIME` function name
|
||||
public static let dateTime = SQLFunctionName("DATETIME")
|
||||
}
|
||||
|
||||
/// Returns an expression that evaluates the `DATETIME` SQL function.
|
||||
///
|
||||
/// // DATETIME(date)
|
||||
/// dateTime(Column("date"))
|
||||
///
|
||||
/// // DATETIME(date, '1 days')
|
||||
/// dateTime(Column("date"), .day(1))
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/lang_datefunc.html
|
||||
public func dateTime(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression {
|
||||
SQLExpressionFunction(.dateTime, arguments: [value.sqlExpression] + modifiers)
|
||||
}
|
||||
@@ -298,6 +298,7 @@ public func !== (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQ
|
||||
SQLExpressionEqual(.isNot, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Comparison Operators (<, >, <=, >=)
|
||||
|
||||
extension SQLBinaryOperator {
|
||||
@@ -474,6 +475,7 @@ public func >= (lhs: SQLSpecificExpressible, rhs: SQLSpecificExpressible) -> SQL
|
||||
SQLExpressionBinary(.greaterThanOrEqual, lhs.sqlExpression, rhs.sqlExpression)
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Inclusion Operators (BETWEEN, IN)
|
||||
|
||||
extension Range where Bound: SQLExpressible {
|
||||
@@ -539,27 +541,7 @@ extension Sequence where Self.Iterator.Element: SQLExpressible {
|
||||
/// // id IN (1,2,3)
|
||||
/// [1, 2, 3].contains(Column("id"))
|
||||
public func contains(_ element: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionsArray(expressions: map(\.sqlExpression)).contains(element.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that checks the inclusion of an expression in
|
||||
/// a sequence.
|
||||
///
|
||||
/// // name IN ('A', 'B') COLLATE NOCASE
|
||||
/// ["A", "B"].contains(Column("name").collating(.nocase))
|
||||
public func contains(_ element: SQLCollatedExpression) -> SQLExpression {
|
||||
SQLExpressionCollate(contains(element.expression), collationName: element.collationName)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Self.Iterator.Element == SQLExpressible {
|
||||
/// An SQL expression that checks the inclusion of an expression in
|
||||
/// a sequence.
|
||||
///
|
||||
/// // id IN (1,2,3)
|
||||
/// [1, 2, 3].contains(Column("id"))
|
||||
public func contains(_ element: SQLSpecificExpressible) -> SQLExpression {
|
||||
SQLExpressionsArray(expressions: map(\.sqlExpression)).contains(element.sqlExpression)
|
||||
SQLExpressionsArray(self).contains(element.sqlExpression)
|
||||
}
|
||||
|
||||
/// An SQL expression that checks the inclusion of an expression in
|
||||
|
||||
@@ -15,7 +15,7 @@ public protocol SQLOrderingTerm {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Returns an SQL string that represents the ordering term.
|
||||
func orderingTermSQL(_ context: SQLGenerationContext) throws -> String
|
||||
func orderingTermSQL(_ context: inout SQLGenerationContext) -> String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func qualifiedOrdering(with alias: TableAlias) -> SQLOrderingTerm
|
||||
@@ -46,17 +46,17 @@ enum SQLOrdering: SQLOrderingTerm {
|
||||
}
|
||||
}
|
||||
|
||||
func orderingTermSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
func orderingTermSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
switch self {
|
||||
case .asc(let expression):
|
||||
return try expression.expressionSQL(context, wrappedInParenthesis: false) + " ASC"
|
||||
return expression.expressionSQL(&context, wrappedInParenthesis: false) + " ASC"
|
||||
case .desc(let expression):
|
||||
return try expression.expressionSQL(context, wrappedInParenthesis: false) + " DESC"
|
||||
return expression.expressionSQL(&context, wrappedInParenthesis: false) + " DESC"
|
||||
#if GRDBCUSTOMSQLITE
|
||||
case .ascNullsLast(let expression):
|
||||
return try expression.expressionSQL(context, wrappedInParenthesis: false) + " ASC NULLS LAST"
|
||||
return expression.expressionSQL(&context, wrappedInParenthesis: false) + " ASC NULLS LAST"
|
||||
case .descNullsFirst(let expression):
|
||||
return try expression.expressionSQL(context, wrappedInParenthesis: false) + " DESC NULLS FIRST"
|
||||
return expression.expressionSQL(&context, wrappedInParenthesis: false) + " DESC NULLS FIRST"
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
struct SQLQuery {
|
||||
var relation: SQLRelation
|
||||
var isDistinct: Bool = false
|
||||
var expectsSingleResult: Bool = false
|
||||
var groupPromise: DatabasePromise<[SQLExpression]>?
|
||||
// Having clause is an array of expressions that we'll join with
|
||||
// the AND operator. This gives nicer output in generated SQL:
|
||||
// `(a AND b AND c)` instead of `((a AND b) AND c)`.
|
||||
var havingExpressionsPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: [])
|
||||
var havingExpressions: [SQLExpression] = []
|
||||
var limit: SQLLimit?
|
||||
}
|
||||
|
||||
@@ -17,6 +18,10 @@ extension SQLQuery: Refinable {
|
||||
with(\.isDistinct, true)
|
||||
}
|
||||
|
||||
func expectingSingleResult() -> Self {
|
||||
with(\.expectsSingleResult, true)
|
||||
}
|
||||
|
||||
func limit(_ limit: Int, offset: Int? = nil) -> Self {
|
||||
with(\.limit, SQLLimit(limit: limit, offset: offset))
|
||||
}
|
||||
@@ -29,11 +34,11 @@ extension SQLQuery: Refinable {
|
||||
}
|
||||
|
||||
extension SQLQuery: SelectionRequest {
|
||||
func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
func select(_ selection: [SQLSelectable]) -> Self {
|
||||
map(\.relation) { $0.select(selection) }
|
||||
}
|
||||
|
||||
func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
func annotated(with selection: [SQLSelectable]) -> Self {
|
||||
map(\.relation) { $0.annotated(with: selection) }
|
||||
}
|
||||
}
|
||||
@@ -63,12 +68,8 @@ extension SQLQuery: AggregatingRequest {
|
||||
with(\.groupPromise, DatabasePromise { db in try expressions(db).map(\.sqlExpression) })
|
||||
}
|
||||
|
||||
func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
|
||||
map(\.havingExpressionsPromise) { havingExpressionsPromise in
|
||||
DatabasePromise { db in
|
||||
try havingExpressionsPromise.resolve(db) + [predicate(db).sqlExpression]
|
||||
}
|
||||
}
|
||||
func having(_ predicate: SQLExpressible) -> Self {
|
||||
mapInto(\.havingExpressions) { $0.append(predicate.sqlExpression) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,10 +97,11 @@ extension SQLQuery: _JoinableRequest {
|
||||
|
||||
extension SQLQuery {
|
||||
func fetchCount(_ db: Database) throws -> Int {
|
||||
try QueryInterfaceRequest<Int>(query: countQuery(db)).fetchOne(db)!
|
||||
let (statement, adapter) = try SQLQueryGenerator(countQuery).prepare(db)
|
||||
return try Int.fetchOne(statement, adapter: adapter)!
|
||||
}
|
||||
|
||||
private func countQuery(_ db: Database) throws -> SQLQuery {
|
||||
private var countQuery: SQLQuery {
|
||||
guard groupPromise == nil && limit == nil else {
|
||||
// SELECT ... GROUP BY ...
|
||||
// SELECT ... LIMIT ...
|
||||
@@ -116,10 +118,9 @@ extension SQLQuery {
|
||||
return trivialCountQuery
|
||||
}
|
||||
|
||||
let selection = try relation.selectionPromise.resolve(db)
|
||||
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
|
||||
if selection.count == 1 {
|
||||
guard let count = selection[0].count(distinct: isDistinct) else {
|
||||
GRDBPrecondition(!relation.selection.isEmpty, "Can't generate SQL with empty selection")
|
||||
if relation.selection.count == 1 {
|
||||
guard let count = relation.selection[0].count(distinct: isDistinct) else {
|
||||
return trivialCountQuery
|
||||
}
|
||||
var countQuery = self.unordered()
|
||||
@@ -148,8 +149,8 @@ extension SQLQuery {
|
||||
// SELECT COUNT(*) FROM (self)
|
||||
private var trivialCountQuery: SQLQuery {
|
||||
let relation = SQLRelation(
|
||||
source: .subquery(unordered()),
|
||||
selectionPromise: DatabasePromise(value: [SQLExpressionCount(AllColumns())]))
|
||||
source: .query(unordered()),
|
||||
selection: [SQLExpressionCount(AllColumns())])
|
||||
return SQLQuery(relation: relation)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,12 +158,15 @@ struct SQLRelation {
|
||||
}
|
||||
|
||||
var source: SQLSource
|
||||
var selectionPromise: DatabasePromise<[SQLSelectable]> = DatabasePromise(value: [])
|
||||
var selection: [SQLSelectable] = []
|
||||
// Filter is an array of expressions that we'll join with the AND operator.
|
||||
// This gives nicer output in generated SQL: `(a AND b AND c)` instead of
|
||||
// `((a AND b) AND c)`.
|
||||
var filtersPromise: DatabasePromise<[SQLExpression]> = DatabasePromise(value: [])
|
||||
var ordering: SQLRelation.Ordering = SQLRelation.Ordering()
|
||||
// If true, the relation refers to the first row only, and we'll need to
|
||||
// perform explicit limit at the SQL level.
|
||||
var firstOnly = false
|
||||
var children: OrderedDictionary<String, Child> = [:]
|
||||
|
||||
var prefetchedAssociations: [SQLAssociation] {
|
||||
@@ -184,44 +187,56 @@ struct SQLRelation {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns nil if there is no way to express the primary key of the
|
||||
/// relation as an expression.
|
||||
func primaryKeyExpression(_ db: Database) throws -> SQLExpression? {
|
||||
switch source {
|
||||
case .query:
|
||||
// No primary key for sub query
|
||||
return nil
|
||||
case let .table(tableName: tableName, alias: _):
|
||||
return try db.primaryKeyExpression(tableName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRelation: Refinable {
|
||||
func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
with(\.selectionPromise, DatabasePromise(selection))
|
||||
}
|
||||
|
||||
// Convenience
|
||||
func select(_ selection: [SQLSelectable]) -> Self {
|
||||
select { _ in selection }
|
||||
with(\.selection, selection)
|
||||
}
|
||||
|
||||
/// Removes all selections from chidren
|
||||
func selectOnly(_ selection: [SQLSelectable]) -> Self {
|
||||
select(selection).map(\.children, { $0.mapValues { $0.map(\.relation, { $0.selectOnly([]) }) } })
|
||||
self.with(\.selection, selection)
|
||||
.map(\.children, { $0.mapValues { $0.map(\.relation, { $0.selectOnly([]) }) } })
|
||||
}
|
||||
|
||||
func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
map(\.selectionPromise) { selectionPromise in
|
||||
DatabasePromise { db in
|
||||
try selectionPromise.resolve(db) + selection(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience
|
||||
func annotated(with selection: [SQLSelectable]) -> Self {
|
||||
annotated(with: { _ in selection })
|
||||
mapInto(\.selection) { $0.append(contentsOf: selection) }
|
||||
}
|
||||
|
||||
func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
|
||||
map(\.filtersPromise) { filtersPromise in
|
||||
DatabasePromise { db in
|
||||
try filtersPromise.resolve(db) + [predicate(db).sqlExpression]
|
||||
filtersPromise.flatMap { filters in
|
||||
DatabasePromise { try filters + [predicate($0).sqlExpression] }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prepending filters for aesthetic reasons
|
||||
func prependingFilters(_ filters: [SQLExpression]) -> Self {
|
||||
map(\.filtersPromise) { filtersPromise in
|
||||
filtersPromise.flatMap { existingFilters in
|
||||
DatabasePromise { _ in filters + existingFilters }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func unfiltered() -> Self {
|
||||
with(\.filtersPromise, DatabasePromise(value: []))
|
||||
}
|
||||
|
||||
func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
|
||||
with(\.ordering, SQLRelation.Ordering(orderings: orderings))
|
||||
}
|
||||
@@ -391,7 +406,7 @@ extension SQLRelation: _JoinableRequest {
|
||||
|
||||
enum SQLSource {
|
||||
case table(tableName: String, alias: TableAlias?)
|
||||
indirect case subquery(SQLQuery)
|
||||
indirect case query(SQLQuery)
|
||||
|
||||
func qualified(with alias: TableAlias) -> SQLSource {
|
||||
switch self {
|
||||
@@ -403,8 +418,8 @@ enum SQLSource {
|
||||
alias.setTableName(tableName)
|
||||
return .table(tableName: tableName, alias: alias)
|
||||
}
|
||||
case .subquery:
|
||||
return self
|
||||
case let .query(query):
|
||||
return .query(query.qualified(with: alias))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -572,7 +587,7 @@ struct SQLAssociationCondition: Equatable {
|
||||
/// - parameter leftAlias: A TableAlias for the table on the left of the
|
||||
/// JOIN operator.
|
||||
/// - Returns: An array of SQL expression that should be joined with
|
||||
/// the AND operator and qualified with the right table.
|
||||
/// the AND operator.
|
||||
func expressions(_ db: Database, leftAlias: TableAlias) throws -> [SQLExpression] {
|
||||
try columnMappings(db).map {
|
||||
Column($0.right) == QualifiedColumn($0.left, alias: leftAlias)
|
||||
@@ -584,44 +599,33 @@ struct SQLAssociationCondition: Equatable {
|
||||
///
|
||||
/// Given `right.a = left.b`, returns `right.a = 1` or
|
||||
/// `right.a IN (1, 2, 3)`.
|
||||
func filteringExpression<Row: ColumnAddressable>(_ db: Database, leftRows: [Row]) throws -> SQLExpression {
|
||||
guard let firstLeftRow = leftRows.first else {
|
||||
func filteringExpression(_ db: Database, leftRows: [Row]) throws -> SQLExpression {
|
||||
if leftRows.isEmpty {
|
||||
// Degenerate case: there is no row to attach
|
||||
return false.sqlExpression
|
||||
}
|
||||
|
||||
// The (left, right) column mapping pairs
|
||||
let columnMappings = try self.columnMappings(db)
|
||||
|
||||
// We assume that all rows have the same layout, and that addressing
|
||||
// rows by index is faster than addressing them by column name.
|
||||
// So we use the first left row in order to convert left column names
|
||||
// into row indexes.
|
||||
let mappings: [(leftIndex: Row.ColumnIndex, rightColumn: Column)] = columnMappings.map { mapping in
|
||||
guard let leftIndex = firstLeftRow.index(forColumn: mapping.left) else {
|
||||
fatalError("Missing column: \(mapping.left)")
|
||||
}
|
||||
return (leftIndex: leftIndex, rightColumn: Column(mapping.right))
|
||||
}
|
||||
guard let mapping = mappings.first else {
|
||||
guard let columnMapping = columnMappings.first else {
|
||||
// Degenerate case: no joining column
|
||||
return true.sqlExpression
|
||||
}
|
||||
|
||||
if mappings.count == 1 {
|
||||
if columnMappings.count == 1 {
|
||||
// Join on a single right column.
|
||||
let rightColumn = Column(columnMapping.right)
|
||||
|
||||
// Unique database values and filter out NULL:
|
||||
let leftIndex = mapping.leftIndex
|
||||
var dbValues = Set(leftRows.map { $0.databaseValue(at: leftIndex) })
|
||||
var dbValues = Set(leftRows.map { $0[columnMapping.left] as DatabaseValue })
|
||||
dbValues.remove(.null)
|
||||
|
||||
if dbValues.isEmpty {
|
||||
return mapping.rightColumn == nil
|
||||
// Can't join
|
||||
return false.sqlExpression
|
||||
} else {
|
||||
// table.a IN (1, 2, 3, ...)
|
||||
// Sort database values for nicer output.
|
||||
return dbValues.sorted(by: <).contains(mapping.rightColumn)
|
||||
return dbValues.sorted(by: <).contains(rightColumn)
|
||||
}
|
||||
} else {
|
||||
// Join on a multiple columns.
|
||||
@@ -629,10 +633,11 @@ struct SQLAssociationCondition: Equatable {
|
||||
return leftRows
|
||||
.map({ leftRow in
|
||||
// (table.a = 1) AND (table.b = 2)
|
||||
mappings
|
||||
.map({ mapping -> SQLExpression in
|
||||
let leftValue = leftRow.databaseValue(at: mapping.leftIndex)
|
||||
return mapping.rightColumn == leftValue
|
||||
columnMappings
|
||||
.map({ columns -> SQLExpression in
|
||||
let rightColumn = Column(columns.right)
|
||||
let leftValue = leftRow[columns.left] as DatabaseValue
|
||||
return rightColumn == leftValue
|
||||
})
|
||||
.joined(operator: .and)
|
||||
})
|
||||
@@ -641,39 +646,6 @@ struct SQLAssociationCondition: Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
/// A protocol for row-like containers
|
||||
protocol ColumnAddressable {
|
||||
associatedtype ColumnIndex
|
||||
func index(forColumn column: String) -> ColumnIndex?
|
||||
func databaseValue(at index: ColumnIndex) -> DatabaseValue
|
||||
}
|
||||
|
||||
/// A "row" that contains null values for all columns
|
||||
struct NullRow: ColumnAddressable {
|
||||
struct DummyIndex { }
|
||||
func index(forColumn column: String) -> DummyIndex? { DummyIndex() }
|
||||
@inline(__always)
|
||||
func databaseValue(at index: DummyIndex) -> DatabaseValue { .null }
|
||||
}
|
||||
|
||||
/// Row has columns
|
||||
extension Row: ColumnAddressable {
|
||||
@inline(__always)
|
||||
func databaseValue(at index: Int) -> DatabaseValue { self[index] }
|
||||
}
|
||||
|
||||
/// PersistenceContainer has columns
|
||||
extension PersistenceContainer: ColumnAddressable {
|
||||
func index(forColumn column: String) -> String? { column }
|
||||
@inline(__always)
|
||||
func databaseValue(at column: String) -> DatabaseValue {
|
||||
guard let value = self[caseInsensitive: column] else {
|
||||
fatalError("Missing column: \(column)")
|
||||
}
|
||||
return value.databaseValue
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Merging
|
||||
//
|
||||
// "Merging" is an operation that takes two relations and, if they are
|
||||
@@ -692,13 +664,18 @@ extension PersistenceContainer: ColumnAddressable {
|
||||
extension SQLRelation {
|
||||
/// Returns nil if relations can't be merged (conflict in source, joins...)
|
||||
func merged(with other: SQLRelation) -> Self? {
|
||||
guard firstOnly == other.firstOnly else {
|
||||
// can't merge
|
||||
return nil
|
||||
}
|
||||
|
||||
guard let mergedSource = source.merged(with: other.source) else {
|
||||
// can't merge
|
||||
return nil
|
||||
}
|
||||
|
||||
let mergedFiltersPromise = DatabasePromise<[SQLExpression]> { db in
|
||||
try self.filtersPromise.resolve(db) + other.filtersPromise.resolve(db)
|
||||
let mergedFiltersPromise: DatabasePromise<[SQLExpression]> = filtersPromise.flatMap { filters in
|
||||
DatabasePromise { try filters + other.filtersPromise.resolve($0) }
|
||||
}
|
||||
|
||||
var mergedChildren: OrderedDictionary<String, SQLRelation.Child> = [:]
|
||||
@@ -718,23 +695,17 @@ extension SQLRelation {
|
||||
}
|
||||
|
||||
// replace selection unless empty
|
||||
let mergedSelectionPromise = DatabasePromise { db -> [SQLSelectable] in
|
||||
let otherSelection = try other.selectionPromise.resolve(db)
|
||||
if otherSelection.isEmpty {
|
||||
return try self.selectionPromise.resolve(db)
|
||||
} else {
|
||||
return otherSelection
|
||||
}
|
||||
}
|
||||
let mergedSelection = other.selection.isEmpty ? selection : other.selection
|
||||
|
||||
// replace ordering unless empty
|
||||
let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering
|
||||
|
||||
return SQLRelation(
|
||||
source: mergedSource,
|
||||
selectionPromise: mergedSelectionPromise,
|
||||
selection: mergedSelection,
|
||||
filtersPromise: mergedFiltersPromise,
|
||||
ordering: mergedOrdering,
|
||||
firstOnly: firstOnly,
|
||||
children: mergedChildren)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,13 +21,13 @@ public struct AllColumns {
|
||||
extension AllColumns: SQLSelectable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func resultColumnSQL(_ context: SQLGenerationContext) -> String {
|
||||
public func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
"*"
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// :nodoc:
|
||||
public func countedSQL(_ context: SQLGenerationContext) -> String {
|
||||
public func countedSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
"*"
|
||||
}
|
||||
|
||||
@@ -70,18 +70,35 @@ struct QualifiedAllColumns {
|
||||
}
|
||||
|
||||
extension QualifiedAllColumns: SQLSelectable {
|
||||
func resultColumnSQL(_ context: SQLGenerationContext) -> String {
|
||||
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
if let qualifier = context.qualifier(for: alias) {
|
||||
return qualifier.quotedDatabaseIdentifier + ".*"
|
||||
}
|
||||
return "*"
|
||||
}
|
||||
|
||||
func countedSQL(_ context: SQLGenerationContext) -> String {
|
||||
if context.qualifier(for: alias) != nil {
|
||||
// SELECT COUNT(t.*) is invalid SQL
|
||||
fatalError("Not implemented, or invalid query")
|
||||
}
|
||||
func countedSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
// TODO: restore the check below.
|
||||
//
|
||||
// It is currently disabled because of AssociationAggregateTests.testHasManyIsEmpty:
|
||||
//
|
||||
// let request = Team.having(Team.players.isEmpty)
|
||||
// try XCTAssertEqual(request.fetchCount(db), 1)
|
||||
//
|
||||
// This should build the trivial count query `SELECT COUNT(*) FROM (SELECT ...)`
|
||||
//
|
||||
// Unfortunately, we don't support anonymous table aliases that would be
|
||||
// required here. Because we don't support anonymous tables aliases,
|
||||
// everything happens as if we wanted to generate
|
||||
// `SELECT COUNT(team.*) FROM (SELECT ...)`, which is invalid SQL.
|
||||
//
|
||||
// So let's always return `*`, and fix this later.
|
||||
|
||||
// if context.qualifier(for: alias) != nil {
|
||||
// // SELECT COUNT(t.*) is invalid SQL
|
||||
// fatalError("Not implemented, or invalid query")
|
||||
// }
|
||||
|
||||
return "*"
|
||||
}
|
||||
|
||||
@@ -108,12 +125,12 @@ struct SQLAliasedExpression: SQLSelectable {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
func resultColumnSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try expression.resultColumnSQL(context) + " AS " + name.quotedDatabaseIdentifier
|
||||
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
expression.resultColumnSQL(&context) + " AS " + name.quotedDatabaseIdentifier
|
||||
}
|
||||
|
||||
func countedSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
try expression.countedSQL(context)
|
||||
func countedSQL(_ context: inout SQLGenerationContext) -> String {
|
||||
expression.countedSQL(&context)
|
||||
}
|
||||
|
||||
func count(distinct: Bool) -> SQLCount? {
|
||||
|
||||
@@ -8,10 +8,10 @@
|
||||
/// :nodoc:
|
||||
public protocol SQLSelectable {
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func resultColumnSQL(_ context: SQLGenerationContext) throws -> String
|
||||
func resultColumnSQL(_ context: inout SQLGenerationContext) -> String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func countedSQL(_ context: SQLGenerationContext) throws -> String
|
||||
func countedSQL(_ context: inout SQLGenerationContext) -> String
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
func count(distinct: Bool) -> SQLCount?
|
||||
|
||||
@@ -1,84 +1,54 @@
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// SQLGenerationContext supports SQL generation:
|
||||
///
|
||||
/// - It provides a database connection during SQL generation, for any purpose
|
||||
/// such as schema introspection.
|
||||
///
|
||||
/// - It provides unique table aliases in order to disambiguates table names
|
||||
/// and columns.
|
||||
///
|
||||
/// - It gathers SQL arguments in order to prevent SQL injection.
|
||||
/// SQLGenerationContext is responsible for preventing SQL injection and
|
||||
/// disambiguating table names when GRDB generates SQL queries.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class SQLGenerationContext {
|
||||
private enum Parent {
|
||||
case none(db: Database, argumentsSink: StatementArgumentsSink)
|
||||
case context(SQLGenerationContext)
|
||||
public struct SQLGenerationContext {
|
||||
var arguments: StatementArguments {
|
||||
_arguments ?? StatementArguments()
|
||||
}
|
||||
private var _arguments: StatementArguments?
|
||||
private var resolvedNames: [TableAlias: String]
|
||||
private var qualifierNeeded: Bool
|
||||
|
||||
// TODO: make internal when FetchRequest is a closed protocol.
|
||||
/// A database connection.
|
||||
public var db: Database {
|
||||
switch parent {
|
||||
case let .none(db: db, argumentsSink: _): return db
|
||||
case let .context(context): return context.db
|
||||
}
|
||||
}
|
||||
/// Used for pure SQL generation. Arguments are always empty.
|
||||
static let rawSQLContext = SQLGenerationContext(
|
||||
_arguments: nil,
|
||||
resolvedNames: [:],
|
||||
qualifierNeeded: false)
|
||||
|
||||
/// All gathered arguments
|
||||
var arguments: StatementArguments { argumentsSink.arguments }
|
||||
/// Used for SQLLiteral generation
|
||||
static let sqlLiteralContext = SQLGenerationContext(
|
||||
_arguments: [],
|
||||
resolvedNames: [:],
|
||||
qualifierNeeded: false)
|
||||
|
||||
/// Access to the database connection, the arguments sink, and resolved
|
||||
/// names of table aliases from outer contexts (useful in case of
|
||||
/// subquery generation).
|
||||
private let parent: Parent
|
||||
/// Used for TableRecord.selectionSQL
|
||||
static let selectionContext = SQLGenerationContext(
|
||||
_arguments: nil,
|
||||
resolvedNames: [:],
|
||||
qualifierNeeded: true)
|
||||
|
||||
/// The arguments sink which prevents SQL injection.
|
||||
private var argumentsSink: StatementArgumentsSink {
|
||||
switch parent {
|
||||
case let .none(db: _, argumentsSink: argumentsSink): return argumentsSink
|
||||
case let .context(context): return context.argumentsSink
|
||||
}
|
||||
}
|
||||
|
||||
private let resolvedNames: [TableAlias: String]
|
||||
private let ownAliases: Set<TableAlias>
|
||||
|
||||
/// Creates a generation context.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter argumentsSink: An arguments sink.
|
||||
/// - parameter aliases: An array of table aliases to disambiguate.
|
||||
init(
|
||||
_ db: Database,
|
||||
argumentsSink: StatementArgumentsSink = StatementArgumentsSink(),
|
||||
aliases: [TableAlias] = [])
|
||||
{
|
||||
self.parent = .none(db: db, argumentsSink: argumentsSink)
|
||||
self.resolvedNames = aliases.resolvedNames
|
||||
self.ownAliases = Set(aliases)
|
||||
}
|
||||
|
||||
/// Creates a generation context.
|
||||
///
|
||||
/// - parameter parent: A parent context.
|
||||
/// - parameter aliases: An array of table aliases to disambiguate.
|
||||
init(
|
||||
parent: SQLGenerationContext,
|
||||
aliases: [TableAlias] = [])
|
||||
{
|
||||
self.parent = .context(parent)
|
||||
self.resolvedNames = aliases.resolvedNames
|
||||
self.ownAliases = Set(aliases)
|
||||
/// Used for SQLQueryGenerator
|
||||
static func queryContext(aliases: [TableAlias]) -> SQLGenerationContext {
|
||||
SQLGenerationContext(
|
||||
_arguments: [],
|
||||
resolvedNames: aliases.resolvedNames,
|
||||
qualifierNeeded: aliases.count > 1)
|
||||
}
|
||||
|
||||
/// Returns whether arguments could be appended.
|
||||
///
|
||||
/// A false result means that the generation context does not support
|
||||
/// SQL arguments.
|
||||
func append(arguments: StatementArguments) -> Bool {
|
||||
argumentsSink.append(arguments: arguments)
|
||||
/// May be false for SQLGenerationContext.rawSQLContext
|
||||
mutating func append(arguments newArguments: StatementArguments) -> Bool {
|
||||
if newArguments.isEmpty {
|
||||
return true
|
||||
}
|
||||
guard let arguments = _arguments else {
|
||||
return false
|
||||
}
|
||||
self._arguments = arguments + newArguments
|
||||
return true
|
||||
}
|
||||
|
||||
/// May be nil, when a qualifier is not needed:
|
||||
@@ -92,26 +62,15 @@ public final class SQLGenerationContext {
|
||||
if alias.hasUserName {
|
||||
return alias.identityName
|
||||
}
|
||||
if !ownAliases.contains(alias) {
|
||||
return resolvedName(for: alias)
|
||||
if qualifierNeeded == false {
|
||||
return nil
|
||||
}
|
||||
if ownAliases.count > 1 {
|
||||
return resolvedName(for: alias)
|
||||
}
|
||||
return nil
|
||||
return resolvedName(for: alias)
|
||||
}
|
||||
|
||||
/// WHERE <resolvedName> MATCH pattern
|
||||
func resolvedName(for alias: TableAlias) -> String {
|
||||
if let name = resolvedNames[alias] {
|
||||
return name
|
||||
}
|
||||
switch parent {
|
||||
case .none:
|
||||
return alias.identityName
|
||||
case let .context(context):
|
||||
return context.resolvedName(for: alias)
|
||||
}
|
||||
resolvedNames[alias] ?? alias.identityName
|
||||
}
|
||||
|
||||
/// FROM tableName <alias>
|
||||
@@ -124,40 +83,6 @@ public final class SQLGenerationContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// A class that gathers statement arguments, and can be shared between
|
||||
/// several SQLGenerationContext.
|
||||
class StatementArgumentsSink {
|
||||
private(set) var arguments: StatementArguments
|
||||
private let rawSQL: Bool
|
||||
|
||||
/// A sink which does not accept any arguments.
|
||||
static let forRawSQL = StatementArgumentsSink(rawSQL: true)
|
||||
|
||||
private init(rawSQL: Bool) {
|
||||
self.arguments = []
|
||||
self.rawSQL = rawSQL
|
||||
}
|
||||
|
||||
/// A sink which accepts arguments
|
||||
convenience init() {
|
||||
self.init(rawSQL: false)
|
||||
}
|
||||
|
||||
// fileprivate so that SQLGenerationContext.append(arguments:) is the only
|
||||
// available api.
|
||||
/// Returns false for SQLGenerationContext.rawSQLContext
|
||||
fileprivate func append(arguments: StatementArguments) -> Bool {
|
||||
if arguments.isEmpty {
|
||||
return true
|
||||
}
|
||||
if rawSQL {
|
||||
return false
|
||||
}
|
||||
self.arguments += arguments
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TableAlias
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
@@ -351,12 +276,6 @@ public class TableAlias: Hashable {
|
||||
expression.qualifiedExpression(with: self)
|
||||
}
|
||||
|
||||
/// Returns a qualified ordering that is able to resolve ambiguities in
|
||||
/// joined queries.
|
||||
public subscript(_ ordering: SQLOrderingTerm) -> SQLOrderingTerm {
|
||||
ordering.qualifiedOrdering(with: self)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(ObjectIdentifier(root))
|
||||
|
||||
@@ -3,20 +3,10 @@ struct SQLQueryGenerator: Refinable {
|
||||
fileprivate private(set) var relation: SQLQualifiedRelation
|
||||
private let isDistinct: Bool
|
||||
private let groupPromise: DatabasePromise<[SQLExpression]>?
|
||||
private let havingExpressionsPromise: DatabasePromise<[SQLExpression]>
|
||||
private let havingExpressions: [SQLExpression]
|
||||
private let limit: SQLLimit?
|
||||
private let singleResult: Bool
|
||||
// For database region
|
||||
private let prefetchedAssociations: [SQLAssociation]
|
||||
|
||||
/// Creates an SQL query generator.
|
||||
///
|
||||
/// - parameter singleResult: A hint as to whether the query should be
|
||||
/// optimized for a single result.
|
||||
init(
|
||||
query: SQLQuery,
|
||||
forSingleResult singleResult: Bool = false)
|
||||
{
|
||||
init(_ query: SQLQuery) {
|
||||
// To generate SQL, we need a "qualified" relation, where all tables,
|
||||
// expressions, etc, are identified with table aliases.
|
||||
//
|
||||
@@ -44,94 +34,60 @@ struct SQLQueryGenerator: Refinable {
|
||||
//
|
||||
// This turns `GROUP BY id` INTO `GROUP BY book.id`, and
|
||||
// `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`.
|
||||
if let alias = relation.source.alias {
|
||||
groupPromise = query.groupPromise?.map {
|
||||
$0.map { $0.qualifiedExpression(with: alias) }
|
||||
}
|
||||
havingExpressionsPromise = query.havingExpressionsPromise.map {
|
||||
$0.map { $0.qualifiedExpression(with: alias) }
|
||||
}
|
||||
} else {
|
||||
groupPromise = query.groupPromise
|
||||
havingExpressionsPromise = query.havingExpressionsPromise
|
||||
}
|
||||
let alias = relation.sourceAlias
|
||||
groupPromise = query.groupPromise?.map { $0.map { $0.qualifiedExpression(with: alias) } }
|
||||
havingExpressions = query.havingExpressions.map { $0.qualifiedExpression(with: alias) }
|
||||
|
||||
limit = query.limit
|
||||
// Preserve other flags
|
||||
isDistinct = query.isDistinct
|
||||
self.singleResult = singleResult
|
||||
prefetchedAssociations = query.relation.prefetchedAssociations
|
||||
limit = query.limit
|
||||
}
|
||||
|
||||
func requestSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
// Build an SQL generation context with all aliases found in the query,
|
||||
// so that we can disambiguate tables that are used several times with
|
||||
// SQL aliases.
|
||||
let context = SQLGenerationContext(parent: context, aliases: relation.allAliases)
|
||||
|
||||
func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String {
|
||||
var sql = "SELECT"
|
||||
|
||||
if isDistinct {
|
||||
sql += " DISTINCT"
|
||||
}
|
||||
|
||||
let selection = try relation.selectionPromise.resolve(context.db)
|
||||
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with an empty selection")
|
||||
sql += try " " + selection.map { try $0.resultColumnSQL(context) }.joined(separator: ", ")
|
||||
let selection = relation.selection
|
||||
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
|
||||
sql += " " + selection.map { $0.resultColumnSQL(&context) }.joined(separator: ", ")
|
||||
|
||||
sql += " FROM "
|
||||
sql += try relation.source.sql(context)
|
||||
sql += try relation.source.sql(db, &context)
|
||||
|
||||
if relation.joins.isEmpty == false {
|
||||
guard let sourceAlias = relation.source.alias else {
|
||||
// This never happens as long as we only use subqueries as sources
|
||||
// in the `SELECT COUNT(*) FROM (SELECT ...)` case: see
|
||||
// SQLQuery.trivialCountQuery.
|
||||
fatalError("Not implemented: join on a subquery")
|
||||
}
|
||||
for (_, join) in relation.joins {
|
||||
sql += " "
|
||||
sql += try join.sql(context, leftAlias: sourceAlias)
|
||||
}
|
||||
for (_, join) in relation.joins {
|
||||
sql += " "
|
||||
sql += try join.sql(db, &context, leftAlias: relation.sourceAlias)
|
||||
}
|
||||
|
||||
let filters = try relation.filtersPromise.resolve(context.db)
|
||||
let filters = try relation.filtersPromise.resolve(db)
|
||||
if filters.isEmpty == false {
|
||||
sql += " WHERE "
|
||||
sql += try filters.joined(operator: .and).expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
|
||||
let groupExpressions = try groupPromise?.resolve(context.db) ?? []
|
||||
if !groupExpressions.isEmpty {
|
||||
if let groupExpressions = try groupPromise?.resolve(db), !groupExpressions.isEmpty {
|
||||
sql += " GROUP BY "
|
||||
sql += try groupExpressions
|
||||
.map { try $0.expressionSQL(context, wrappedInParenthesis: false) }
|
||||
sql += groupExpressions
|
||||
.map { $0.expressionSQL(&context, wrappedInParenthesis: false) }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
|
||||
let havingExpressions = try havingExpressionsPromise.resolve(context.db)
|
||||
if havingExpressions.isEmpty == false {
|
||||
sql += " HAVING "
|
||||
sql += try havingExpressions.joined(operator: .and).expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += havingExpressions.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
|
||||
let orderings = try relation.ordering.resolve(context.db)
|
||||
let orderings = try relation.ordering.resolve(db)
|
||||
if !orderings.isEmpty {
|
||||
sql += " ORDER BY "
|
||||
sql += try orderings
|
||||
.map { try $0.orderingTermSQL(context) }
|
||||
sql += orderings
|
||||
.map { $0.orderingTermSQL(&context) }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
|
||||
var limit = self.limit
|
||||
if try singleResult && !expectsSingleResult(
|
||||
context.db,
|
||||
selection: selection,
|
||||
filters: filters,
|
||||
groupExpressions: groupExpressions)
|
||||
{
|
||||
limit = SQLLimit(limit: 1, offset: limit?.offset)
|
||||
}
|
||||
|
||||
if let limit = limit {
|
||||
sql += " LIMIT "
|
||||
sql += limit.sql
|
||||
@@ -140,35 +96,8 @@ struct SQLQueryGenerator: Refinable {
|
||||
return sql
|
||||
}
|
||||
|
||||
func makePreparedRequest(_ db: Database) throws -> PreparedRequest {
|
||||
try PreparedRequest(
|
||||
statement: makeSelectStatement(db),
|
||||
adapter: rowAdapter(db))
|
||||
}
|
||||
|
||||
/// Returns a select statement
|
||||
func makeSelectStatement(_ db: Database) throws -> SelectStatement {
|
||||
// Build
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try requestSQL(context)
|
||||
|
||||
// Compile & set arguments
|
||||
let statement = try db.makeSelectStatement(sql: sql)
|
||||
statement.arguments = context.arguments
|
||||
|
||||
// Optimize statement region. This allows us to track individual rowids.
|
||||
statement.databaseRegion = try optimizedSelectedRegion(db, statement.databaseRegion)
|
||||
|
||||
// Also append the prefetched region. This makes sure we observe the
|
||||
// correct database region when the statement is executed, even if we
|
||||
// don't execute all request statements due to lacking database content.
|
||||
// For example, fetching `parent.including(all: children)` will select
|
||||
// parents, but won't attempt to select any children if there is no
|
||||
// parent in the database. And yet we need to observe the table for
|
||||
// children. This is why we include the prefetched region.
|
||||
try statement.databaseRegion.formUnion(prefetchedRegion(db, associations: prefetchedAssociations))
|
||||
|
||||
return statement
|
||||
func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?) {
|
||||
try (makeSelectStatement(db), rowAdapter(db))
|
||||
}
|
||||
|
||||
private func optimizedSelectedRegion(_ db: Database, _ selectedRegion: DatabaseRegion) throws -> DatabaseRegion {
|
||||
@@ -197,103 +126,6 @@ struct SQLQueryGenerator: Refinable {
|
||||
return selectedRegion.tableIntersection(canonicalTableName, rowIds: rowIds)
|
||||
}
|
||||
|
||||
/// If true, executing this query yields at most one row.
|
||||
/// If false, we don't know how many rows this query returns.
|
||||
private func expectsSingleResult(
|
||||
_ db: Database,
|
||||
selection: [SQLSelectable],
|
||||
filters: [SQLExpression],
|
||||
groupExpressions: [SQLExpression])
|
||||
throws -> Bool
|
||||
{
|
||||
if relation.allAliases.count > 1 {
|
||||
// Don't expect single results as soon as several tables are involved
|
||||
return false
|
||||
}
|
||||
|
||||
// Do we filter on a unique key?
|
||||
if case let .table(tableName, sourceAlias) = relation.source {
|
||||
let filteredColumns = filters.flatMap(\.truthComponents).compactMap { expression -> String? in
|
||||
guard let equalExpression = expression as? SQLExpressionEqual,
|
||||
(equalExpression.op == .equal || equalExpression.op == .is) else
|
||||
{
|
||||
// Not Column("foo") == value
|
||||
return nil
|
||||
}
|
||||
|
||||
if equalExpression.lhs is DatabaseValue,
|
||||
let qualifiedColumn = equalExpression.rhs as? QualifiedColumn,
|
||||
qualifiedColumn.alias == sourceAlias
|
||||
{
|
||||
// value == Column("foo")
|
||||
return qualifiedColumn.name
|
||||
}
|
||||
|
||||
if equalExpression.rhs is DatabaseValue,
|
||||
let qualifiedColumn = equalExpression.lhs as? QualifiedColumn,
|
||||
qualifiedColumn.alias == sourceAlias
|
||||
{
|
||||
// Column("foo") == value
|
||||
return qualifiedColumn.name
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
if try db.table(tableName, hasUniqueKey: filteredColumns) {
|
||||
// Filter by unique key: guaranteed single row!
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// Do we aggregate without grouping?
|
||||
if groupExpressions.isEmpty {
|
||||
// https://www.sqlite.org/lang_aggfunc.html#groupconcat
|
||||
let aggregateFunctionNames: Set<String> = [
|
||||
"AVG", "COUNT", "GROUP_CONCAT", "MAX", "MIN", "SUM", "TOTAL"
|
||||
]
|
||||
for selectable in selection {
|
||||
switch selectable {
|
||||
case is SQLExpressionCount:
|
||||
// Selection contains COUNT(...): guaranteed single row!
|
||||
return true
|
||||
case is SQLExpressionCountDistinct:
|
||||
// Selection contains COUNT(DISTINCT ...): guaranteed single row!
|
||||
return true
|
||||
case let expression as SQLExpressionFunction:
|
||||
let functionName = expression.functionName.sql.uppercased()
|
||||
guard aggregateFunctionNames.contains(functionName) else {
|
||||
// Not an aggregate function.
|
||||
// (We miss custom aggregates)
|
||||
continue
|
||||
}
|
||||
guard expression.arguments.allSatisfy({ $0 is QualifiedColumn }) else {
|
||||
// Aggregate function argument is not a column.
|
||||
// (We miss expressions such as `max(column + 1)`)
|
||||
continue
|
||||
}
|
||||
if functionName == "GROUP_CONCAT" {
|
||||
switch expression.arguments.count {
|
||||
case 1, 2:
|
||||
// Selection contains an aggregate function: guaranteed single row!
|
||||
return true
|
||||
default:
|
||||
break
|
||||
}
|
||||
} else if expression.arguments.count == 1 {
|
||||
// Selection contains an aggregate function: guaranteed single row!
|
||||
return true
|
||||
}
|
||||
default:
|
||||
// Not an aggregate
|
||||
// (We miss expressions such as `max(column) + 1`)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
|
||||
switch try grouping(db) {
|
||||
case .none:
|
||||
@@ -306,22 +138,19 @@ struct SQLQueryGenerator: Refinable {
|
||||
return try makeTrivialDeleteStatement(db)
|
||||
}
|
||||
|
||||
let context = SQLGenerationContext(db, aliases: relation.allAliases)
|
||||
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
|
||||
|
||||
var sql = try "DELETE FROM " + relation.source.sql(context)
|
||||
var sql = try "DELETE FROM " + relation.source.sql(db, &context)
|
||||
|
||||
let filters = try relation.filtersPromise.resolve(db)
|
||||
if filters.isEmpty == false {
|
||||
sql += " WHERE "
|
||||
sql += try filters
|
||||
.joined(operator: .and)
|
||||
.expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += " WHERE " + filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
|
||||
if let limit = limit {
|
||||
let orderings = try relation.ordering.resolve(db)
|
||||
if !orderings.isEmpty {
|
||||
sql += try " ORDER BY " + orderings.map { try $0.orderingTermSQL(context) }.joined(separator: ", ")
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
|
||||
}
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
@@ -346,13 +175,13 @@ struct SQLQueryGenerator: Refinable {
|
||||
fatalError("Can't delete without any database table")
|
||||
}
|
||||
|
||||
let context = SQLGenerationContext(db)
|
||||
let primaryKey = SQLPrimaryKeyExpression(tableName: tableName)
|
||||
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
|
||||
let primaryKey = try db.primaryKeyExpression(tableName)
|
||||
|
||||
var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE "
|
||||
sql += try primaryKey.expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += primaryKey.expressionSQL(&context, wrappedInParenthesis: false)
|
||||
sql += " IN ("
|
||||
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(context)
|
||||
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).sql(db, &context)
|
||||
sql += ")"
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql: sql)
|
||||
@@ -387,7 +216,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
return nil
|
||||
}
|
||||
|
||||
let context = SQLGenerationContext(db, aliases: relation.allAliases)
|
||||
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
|
||||
|
||||
var sql = "UPDATE "
|
||||
|
||||
@@ -395,25 +224,22 @@ struct SQLQueryGenerator: Refinable {
|
||||
sql += "OR \(conflictResolution.rawValue) "
|
||||
}
|
||||
|
||||
sql += try relation.source.sql(context)
|
||||
sql += try relation.source.sql(db, &context)
|
||||
|
||||
let assignmentsSQL = try assignments
|
||||
.map { try $0.sql(context) }
|
||||
let assignmentsSQL = assignments
|
||||
.map { $0.sql(&context) }
|
||||
.joined(separator: ", ")
|
||||
sql += " SET " + assignmentsSQL
|
||||
|
||||
let filters = try relation.filtersPromise.resolve(db)
|
||||
if filters.isEmpty == false {
|
||||
sql += " WHERE "
|
||||
sql += try filters
|
||||
.joined(operator: .and)
|
||||
.expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += " WHERE " + filters.joined(operator: .and).expressionSQL(&context, wrappedInParenthesis: false)
|
||||
}
|
||||
|
||||
if let limit = limit {
|
||||
let orderings = try relation.ordering.resolve(db)
|
||||
if !orderings.isEmpty {
|
||||
sql += try " ORDER BY " + orderings.map { try $0.orderingTermSQL(context) }.joined(separator: ", ")
|
||||
sql += " ORDER BY " + orderings.map { $0.orderingTermSQL(&context) }.joined(separator: ", ")
|
||||
}
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
@@ -450,8 +276,8 @@ struct SQLQueryGenerator: Refinable {
|
||||
return nil
|
||||
}
|
||||
|
||||
let context = SQLGenerationContext(db)
|
||||
let primaryKey = SQLPrimaryKeyExpression(tableName: tableName)
|
||||
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
|
||||
let primaryKey = try db.primaryKeyExpression(tableName)
|
||||
|
||||
// UPDATE table...
|
||||
var sql = "UPDATE "
|
||||
@@ -461,16 +287,16 @@ struct SQLQueryGenerator: Refinable {
|
||||
sql += tableName.quotedDatabaseIdentifier
|
||||
|
||||
// SET column = value...
|
||||
let assignmentsSQL = try assignments
|
||||
.map { try $0.sql(context) }
|
||||
let assignmentsSQL = assignments
|
||||
.map { $0.sql(&context) }
|
||||
.joined(separator: ", ")
|
||||
sql += " SET " + assignmentsSQL
|
||||
|
||||
// WHERE id IN (SELECT id FROM ...)
|
||||
// WHERE id IN (SELECT rowid FROM ...)
|
||||
sql += " WHERE "
|
||||
sql += try primaryKey.expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += primaryKey.expressionSQL(&context, wrappedInParenthesis: false)
|
||||
sql += " IN ("
|
||||
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).requestSQL(context)
|
||||
sql += try map(\.relation, { $0.selectOnly([primaryKey]) }).sql(db, &context)
|
||||
sql += ")"
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql: sql)
|
||||
@@ -478,6 +304,25 @@ struct SQLQueryGenerator: Refinable {
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a select statement
|
||||
func makeSelectStatement(_ db: Database) throws -> SelectStatement {
|
||||
// Build an SQK generation context with all aliases found in the query,
|
||||
// so that we can disambiguate tables that are used several times with
|
||||
// SQL aliases.
|
||||
var context = SQLGenerationContext.queryContext(aliases: relation.allAliases)
|
||||
|
||||
// Generate SQL
|
||||
let sql = try self.sql(db, &context)
|
||||
|
||||
// Compile & set arguments
|
||||
let statement = try db.makeSelectStatement(sql: sql)
|
||||
statement.arguments = context.arguments
|
||||
|
||||
// Optimize databaseRegion
|
||||
statement.selectedRegion = try optimizedSelectedRegion(db, statement.selectedRegion)
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Informs about the query grouping
|
||||
private enum GroupingInfo {
|
||||
/// No grouping at all: SELECT ... FROM player
|
||||
@@ -566,11 +411,14 @@ struct SQLQueryGenerator: Refinable {
|
||||
/// | | | • filterPromise
|
||||
/// | | • joins
|
||||
/// | • source
|
||||
/// • selectionPromise
|
||||
/// • selection
|
||||
private struct SQLQualifiedRelation {
|
||||
/// The source alias
|
||||
var sourceAlias: TableAlias { source.alias }
|
||||
|
||||
/// All aliases, including aliases of joined relations
|
||||
var allAliases: [TableAlias] {
|
||||
joins.reduce(into: [source.alias].compactMap { $0 }) {
|
||||
joins.reduce(into: source.allAliases) {
|
||||
$0.append(contentsOf: $1.value.relation.allAliases)
|
||||
}
|
||||
}
|
||||
@@ -583,20 +431,16 @@ private struct SQLQualifiedRelation {
|
||||
let source: SQLQualifiedSource
|
||||
|
||||
/// The selection from source, not including selection of joined relations
|
||||
private var sourceSelectionPromise: DatabasePromise<[SQLSelectable]>
|
||||
private var sourceSelection: [SQLSelectable]
|
||||
|
||||
/// The full selection, including selection of joined relations
|
||||
///
|
||||
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
|
||||
/// |
|
||||
/// • selectionPromise
|
||||
var selectionPromise: DatabasePromise<[SQLSelectable]> {
|
||||
DatabasePromise { db in
|
||||
let selection = try self.sourceSelectionPromise.resolve(db)
|
||||
return try self.joins.values.reduce(into: selection) { selection, join in
|
||||
let joinedSelection = try join.relation.selectionPromise.resolve(db)
|
||||
selection.append(contentsOf: joinedSelection)
|
||||
}
|
||||
/// • selection
|
||||
var selection: [SQLSelectable] {
|
||||
joins.reduce(into: sourceSelection) {
|
||||
$0.append(contentsOf: $1.value.relation.selection)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -635,23 +479,14 @@ private struct SQLQualifiedRelation {
|
||||
// SQLGenerationContext, when the SQLSelectQueryGenerator which owns
|
||||
// this SQLQualifiedRelation generates SQL.
|
||||
source = SQLQualifiedSource(relation.source)
|
||||
let sourceAlias = source.alias
|
||||
|
||||
// Qualify all joins, selection, filter, and ordering, so that all
|
||||
// identifiers can be correctly disambiguated and qualified.
|
||||
joins = relation.children.compactMapValues { SQLQualifiedJoin($0) }
|
||||
if let sourceAlias = source.alias {
|
||||
sourceSelectionPromise = relation.selectionPromise.map {
|
||||
$0.map { $0.qualifiedSelectable(with: sourceAlias) }
|
||||
}
|
||||
filtersPromise = relation.filtersPromise.map {
|
||||
$0.map { $0.qualifiedExpression(with: sourceAlias) }
|
||||
}
|
||||
sourceOrdering = relation.ordering.qualified(with: sourceAlias)
|
||||
} else {
|
||||
sourceSelectionPromise = relation.selectionPromise
|
||||
filtersPromise = relation.filtersPromise
|
||||
sourceOrdering = relation.ordering
|
||||
}
|
||||
sourceSelection = relation.selection.map { $0.qualifiedSelectable(with: sourceAlias) }
|
||||
filtersPromise = relation.filtersPromise.map { $0.map { $0.qualifiedExpression(with: sourceAlias) } }
|
||||
sourceOrdering = relation.ordering.qualified(with: sourceAlias)
|
||||
}
|
||||
|
||||
/// See SQLQueryGenerator.rowAdapter(_:)
|
||||
@@ -672,7 +507,7 @@ private struct SQLQualifiedRelation {
|
||||
|
||||
// The number of columns in source selection. Columns selected by joined
|
||||
// relations are appended after.
|
||||
let sourceSelectionWidth = try sourceSelectionPromise.resolve(db).reduce(0) {
|
||||
let sourceSelectionWidth = try sourceSelection.reduce(0) {
|
||||
try $0 + $1.columnCount(db)
|
||||
}
|
||||
|
||||
@@ -716,14 +551,7 @@ private struct SQLQualifiedRelation {
|
||||
|
||||
/// Removes all selections from joins
|
||||
func selectOnly(_ selection: [SQLSelectable]) -> Self {
|
||||
let sourceSelectionPromise: DatabasePromise<[SQLSelectable]>
|
||||
if let sourceAlias = source.alias {
|
||||
sourceSelectionPromise = DatabasePromise(value: selection.map { $0.qualifiedSelectable(with: sourceAlias) })
|
||||
} else {
|
||||
sourceSelectionPromise = DatabasePromise(value: selection)
|
||||
}
|
||||
return self
|
||||
.with(\.sourceSelectionPromise, sourceSelectionPromise)
|
||||
self.with(\.sourceSelection, selection.map { $0.qualifiedSelectable(with: sourceAlias) })
|
||||
.map(\.joins, { $0.mapValues { $0.selectOnly([]) } })
|
||||
}
|
||||
}
|
||||
@@ -733,24 +561,23 @@ extension SQLQualifiedRelation: Refinable { }
|
||||
/// A "qualified" source, where all tables are identified with a table alias.
|
||||
private enum SQLQualifiedSource {
|
||||
case table(tableName: String, alias: TableAlias)
|
||||
indirect case subquery(SQLQueryGenerator)
|
||||
indirect case query(SQLQueryGenerator)
|
||||
|
||||
/// Nil for subquery sources.
|
||||
///
|
||||
/// Maybe one day we'll support aliased subqueries, as below:
|
||||
///
|
||||
/// SELECT alias.* FROM (SELECT ...) alias
|
||||
///
|
||||
/// But today we only use subqueries for SQLQuery.trivialCountQuery,
|
||||
/// which does not need any alias:
|
||||
///
|
||||
/// SELECT COUNT(*) FROM (SELECT ...)
|
||||
var alias: TableAlias? {
|
||||
var alias: TableAlias {
|
||||
switch self {
|
||||
case let .table(_, alias):
|
||||
case .table(_, let alias):
|
||||
return alias
|
||||
case .subquery:
|
||||
return nil
|
||||
case .query(let query):
|
||||
return query.relation.sourceAlias
|
||||
}
|
||||
}
|
||||
|
||||
var allAliases: [TableAlias] {
|
||||
switch self {
|
||||
case .table(_, let alias):
|
||||
return [alias]
|
||||
case .query(let query):
|
||||
return query.relation.allAliases
|
||||
}
|
||||
}
|
||||
|
||||
@@ -759,12 +586,12 @@ private enum SQLQualifiedSource {
|
||||
case let .table(tableName, alias):
|
||||
let alias = alias ?? TableAlias(tableName: tableName)
|
||||
self = .table(tableName: tableName, alias: alias)
|
||||
case let .subquery(subquery):
|
||||
self = .subquery(SQLQueryGenerator(query: subquery))
|
||||
case let .query(query):
|
||||
self = .query(SQLQueryGenerator(query))
|
||||
}
|
||||
}
|
||||
|
||||
func sql(_ context: SQLGenerationContext) throws -> String {
|
||||
func sql(_ db: Database, _ context: inout SQLGenerationContext) throws -> String {
|
||||
switch self {
|
||||
case let .table(tableName, alias):
|
||||
if let aliasName = context.aliasName(for: alias) {
|
||||
@@ -772,9 +599,8 @@ private enum SQLQualifiedSource {
|
||||
} else {
|
||||
return "\(tableName.quotedDatabaseIdentifier)"
|
||||
}
|
||||
case let .subquery(generator):
|
||||
let sql = try generator.requestSQL(context)
|
||||
return "(\(sql))"
|
||||
case let .query(query):
|
||||
return try "(\(query.sql(db, &context)))"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -798,9 +624,15 @@ private struct SQLQualifiedJoin: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
enum Target {
|
||||
case all
|
||||
case first(SQLRelation)
|
||||
}
|
||||
|
||||
var kind: Kind
|
||||
var condition: SQLAssociationCondition
|
||||
var relation: SQLQualifiedRelation
|
||||
var target: Target
|
||||
|
||||
init?(_ child: SQLRelation.Child) {
|
||||
guard let kind = Kind(child.kind) else {
|
||||
@@ -808,25 +640,53 @@ private struct SQLQualifiedJoin: Refinable {
|
||||
}
|
||||
self.kind = kind
|
||||
self.condition = child.condition
|
||||
self.relation = SQLQualifiedRelation(child.relation)
|
||||
|
||||
// Remove non-joined grand children
|
||||
let relation = child.relation.filteringChildren { Kind($0.kind) != nil }
|
||||
|
||||
if relation.firstOnly {
|
||||
// Split relation into an "outer" relation exposed to the rest of
|
||||
// the query, and a "subRelation", private to the join, limited
|
||||
// to a single row:
|
||||
//
|
||||
// v--- outer relation
|
||||
// JOIN child ON id = (SELECT id FROM child ... LIMIT 1)
|
||||
// ^--- subRelation
|
||||
//
|
||||
// Outer relation has no filter or ordering: those are handled
|
||||
// by the subRelation.
|
||||
|
||||
let outerRelation = relation
|
||||
.with(\.firstOnly, false)
|
||||
.unfiltered()
|
||||
.unordered()
|
||||
|
||||
self.relation = SQLQualifiedRelation(outerRelation)
|
||||
self.target = .first(relation)
|
||||
} else {
|
||||
self.relation = SQLQualifiedRelation(relation)
|
||||
self.target = .all
|
||||
}
|
||||
}
|
||||
|
||||
func sql(_ context: SQLGenerationContext, leftAlias: TableAlias) throws -> String {
|
||||
try sql(context, leftAlias: leftAlias, allowingInnerJoin: true)
|
||||
func sql(_ db: Database, _ context: inout SQLGenerationContext, leftAlias: TableAlias) throws -> String {
|
||||
try sql(db, &context, leftAlias: leftAlias, allowingInnerJoin: true)
|
||||
}
|
||||
|
||||
/// Removes all selections from joins
|
||||
func selectOnly(_ selection: [SQLSelectable]) -> SQLQualifiedJoin {
|
||||
func selectOnly(_ selection: [SQLSelectable]) -> Self {
|
||||
map(\.relation) { $0.selectOnly(selection) }
|
||||
}
|
||||
|
||||
private func sql(
|
||||
_ context: SQLGenerationContext,
|
||||
_ db: Database,
|
||||
_ context: inout SQLGenerationContext,
|
||||
leftAlias: TableAlias,
|
||||
allowingInnerJoin allowsInnerJoin: Bool)
|
||||
throws -> String
|
||||
{
|
||||
var allowsInnerJoin = allowsInnerJoin
|
||||
var sql = ""
|
||||
|
||||
switch self.kind {
|
||||
case .innerJoin:
|
||||
@@ -843,28 +703,45 @@ private struct SQLQualifiedJoin: Refinable {
|
||||
}
|
||||
|
||||
// JOIN table...
|
||||
var sql = try "\(kind.rawValue) \(relation.source.sql(context))"
|
||||
guard let rightAlias = relation.source.alias else {
|
||||
// This never happens as long as we only use subqueries as sources
|
||||
// in the `SELECT COUNT(*) FROM (SELECT ...)` case: see
|
||||
// SQLQuery.trivialCountQuery.
|
||||
fatalError("Not implemented: join on a subquery")
|
||||
}
|
||||
sql += try "\(kind.rawValue) \(relation.source.sql(db, &context))"
|
||||
|
||||
// ... ON <join conditions> AND <other filters>
|
||||
var filters = try condition.expressions(context.db, leftAlias: leftAlias)
|
||||
filters += try relation.filtersPromise.resolve(context.db)
|
||||
if filters.isEmpty == false {
|
||||
let filterSQL = try filters
|
||||
.joined(operator: .and)
|
||||
.qualifiedExpression(with: rightAlias)
|
||||
.expressionSQL(context, wrappedInParenthesis: false)
|
||||
sql += " ON \(filterSQL)"
|
||||
let rightAlias = relation.sourceAlias
|
||||
switch target {
|
||||
case .all:
|
||||
// ... ON <join conditions> AND <other filters>
|
||||
var filters = try condition.expressions(db, leftAlias: leftAlias)
|
||||
filters += try relation.filtersPromise.resolve(db)
|
||||
if filters.isEmpty == false {
|
||||
let filterSQL = filters
|
||||
.joined(operator: .and)
|
||||
.qualifiedExpression(with: rightAlias)
|
||||
.expressionSQL(&context, wrappedInParenthesis: false)
|
||||
sql += " ON \(filterSQL)"
|
||||
}
|
||||
case var .first(subRelation):
|
||||
// Subquery: SELECT id ...
|
||||
guard let primaryKey = try subRelation.primaryKeyExpression(db) else {
|
||||
fatalError("Not implemented: support for WITHOUT ROWID optimization")
|
||||
}
|
||||
subRelation = subRelation.selectOnly([primaryKey])
|
||||
|
||||
// Subquery: ... WHERE <condition filters> AND <other filters>
|
||||
let filters = try condition.expressions(db, leftAlias: leftAlias)
|
||||
subRelation = subRelation.prependingFilters(filters)
|
||||
|
||||
// Subquery: ... LIMIT 1
|
||||
let subQuery = SQLQuery(relation: subRelation, limit: SQLLimit(limit: 1, offset: nil))
|
||||
|
||||
// ... ON id = (SELECT id FROM table WHERE <condition filters> AND <other filters> LIMIT 1)
|
||||
sql += " ON "
|
||||
sql += rightAlias[primaryKey].expressionSQL(&context, wrappedInParenthesis: false)
|
||||
sql += " = ("
|
||||
sql += try SQLQueryGenerator(subQuery).sql(db, &context)
|
||||
sql += ")"
|
||||
}
|
||||
|
||||
for (_, join) in relation.joins {
|
||||
// Right becomes left as we dig further
|
||||
sql += try " \(join.sql(context, leftAlias: rightAlias, allowingInnerJoin: allowsInnerJoin))"
|
||||
sql += try " \(join.sql(db, &context, leftAlias: rightAlias, allowingInnerJoin: allowsInnerJoin))"
|
||||
}
|
||||
|
||||
return sql
|
||||
|
||||
@@ -1,24 +1,10 @@
|
||||
/// :nodoc:
|
||||
extension SQLInterpolation {
|
||||
|
||||
// MARK: - TableRecord
|
||||
|
||||
/// Appends the table name of the record type.
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// let request: SQLRequest<Player> = "SELECT * FROM \(Player.self)"
|
||||
public mutating func appendInterpolation<T>(_ table: T.Type)
|
||||
where T: TableRecord
|
||||
{
|
||||
appendLiteral(table.databaseTableName.quotedDatabaseIdentifier)
|
||||
}
|
||||
|
||||
/// Appends the table name of the record type.
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// let request: SQLRequest<Player> = "SELECT * FROM \(Player.self)"
|
||||
@_disfavoredOverload
|
||||
public mutating func appendInterpolation(_ table: TableRecord.Type) {
|
||||
public mutating func appendInterpolation<T: TableRecord>(_ table: T.Type) {
|
||||
appendLiteral(table.databaseTableName.quotedDatabaseIdentifier)
|
||||
}
|
||||
|
||||
@@ -27,127 +13,58 @@ extension SQLInterpolation {
|
||||
/// // INSERT INTO player ...
|
||||
/// let player: Player = ...
|
||||
/// let request: SQLRequest<Player> = "INSERT INTO \(tableOf: player) ..."
|
||||
public mutating func appendInterpolation<T>(tableOf record: T)
|
||||
where T: TableRecord
|
||||
{
|
||||
public mutating func appendInterpolation<T: TableRecord>(tableOf record: T) {
|
||||
appendInterpolation(type(of: record))
|
||||
}
|
||||
|
||||
/// Appends the table name of the record.
|
||||
///
|
||||
/// // INSERT INTO player ...
|
||||
/// let player: Player = ...
|
||||
/// let request: SQLRequest<Player> = "INSERT INTO \(tableOf: player) ..."
|
||||
@_disfavoredOverload
|
||||
public mutating func appendInterpolation(tableOf record: TableRecord) {
|
||||
appendInterpolation(type(of: record))
|
||||
}
|
||||
|
||||
/// Appends the selection of the record type.
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// let player: Player = ...
|
||||
/// let request: SQLRequest<Player> = "SELECT \(columnsOf: Player.self) FROM player"
|
||||
///
|
||||
/// // SELECT p.* FROM player p
|
||||
/// let player: Player = ...
|
||||
/// let request: SQLRequest<Player> = "SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p"
|
||||
public mutating func appendInterpolation<T>(columnsOf record: T.Type, tableAlias: String? = nil)
|
||||
where T: TableRecord
|
||||
{
|
||||
let alias = TableAlias(name: tableAlias ?? T.databaseTableName)
|
||||
elements.append(contentsOf: T.databaseSelection
|
||||
.map { CollectionOfOne(.selectable($0.qualifiedSelectable(with: alias))) }
|
||||
.joined(separator: CollectionOfOne(.sql(", "))))
|
||||
}
|
||||
|
||||
// MARK: - SQLSelectable
|
||||
|
||||
/// Appends the selectable SQL.
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT \(AllColumns()) FROM player
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ selection: T)
|
||||
where T: SQLSelectable
|
||||
{
|
||||
public mutating func appendInterpolation(_ selection: SQLSelectable) {
|
||||
elements.append(.selectable(selection))
|
||||
}
|
||||
|
||||
/// Appends the selectable SQL, or NULL if it is nil.
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT \(AllColumns()) FROM player
|
||||
/// """
|
||||
@_disfavoredOverload
|
||||
public mutating func appendInterpolation(_ selection: SQLSelectable?) {
|
||||
if let selection = selection {
|
||||
elements.append(.selectable(selection))
|
||||
} else {
|
||||
appendLiteral("NULL")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLOrderingTerm
|
||||
|
||||
/// Appends the ordering SQL.
|
||||
///
|
||||
/// // SELECT name FROM player ORDER BY name DESC
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player ORDER BY \(Column("name").desc)
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ orderingTerm: T)
|
||||
where T: SQLOrderingTerm
|
||||
{
|
||||
elements.append(.orderingTerm(orderingTerm))
|
||||
}
|
||||
|
||||
/// Appends the ordering SQL.
|
||||
///
|
||||
/// // SELECT name FROM player ORDER BY name DESC
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player ORDER BY \(Column("name").desc)
|
||||
/// """
|
||||
@_disfavoredOverload
|
||||
public mutating func appendInterpolation(_ orderingTerm: SQLOrderingTerm) {
|
||||
elements.append(.orderingTerm(orderingTerm))
|
||||
}
|
||||
|
||||
// MARK: - SQLExpressible
|
||||
|
||||
/// Appends the expression SQL.
|
||||
///
|
||||
/// // SELECT name FROM player
|
||||
/// let request: SQLRequest<String> = """
|
||||
/// SELECT \(Column("name")) FROM player
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ expressible: T)
|
||||
where T: SQLExpressible
|
||||
{
|
||||
public mutating func appendInterpolation(_ expressible: SQLExpressible & SQLSelectable & SQLOrderingTerm) {
|
||||
elements.append(.expression(expressible.sqlExpression))
|
||||
}
|
||||
|
||||
/// Appends the expression SQL.
|
||||
/// Appends the name of the coding key.
|
||||
///
|
||||
/// // SELECT name FROM player
|
||||
/// let request: SQLRequest<String> = """
|
||||
/// SELECT \(Column("name")) FROM player
|
||||
/// let request: SQLRequest<String> = "
|
||||
/// SELECT \(CodingKey.name) FROM player
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ expressible: T)
|
||||
where T: SQLExpressible & SQLSelectable & SQLOrderingTerm
|
||||
public mutating func appendInterpolation(
|
||||
_ codingKey: SQLExpressible & SQLSelectable & SQLOrderingTerm & CodingKey)
|
||||
{
|
||||
elements.append(.expression(expressible.sqlExpression))
|
||||
elements.append(.expression(codingKey.sqlExpression))
|
||||
}
|
||||
|
||||
/// Appends the expression SQL, or NULL if it is nil.
|
||||
///
|
||||
/// // SELECT name FROM player
|
||||
/// let request: SQLRequest<String> = """
|
||||
/// SELECT \(Column("name")) FROM player
|
||||
/// // SELECT score + ? FROM player
|
||||
/// let bonus = 1000
|
||||
/// let request: SQLRequest<Int> = """
|
||||
/// SELECT score + \(bonus) FROM player
|
||||
/// """
|
||||
@_disfavoredOverload
|
||||
///
|
||||
/// You can also derive literal expressions from other expressions:
|
||||
///
|
||||
/// func date(_ value: SQLExpressible) -> SQLExpression {
|
||||
/// SQLLiteral("DATE(\(value))").sqlExpression
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player WHERE DATE(createdAt) = '2020-02-25'
|
||||
/// let request = Player.filter(date(Column("createdAt")) == "2020-02-25")
|
||||
public mutating func appendInterpolation(_ expressible: SQLExpressible?) {
|
||||
if let expressible = expressible {
|
||||
elements.append(.expression(expressible.sqlExpression))
|
||||
@@ -156,78 +73,25 @@ extension SQLInterpolation {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CodingKey
|
||||
|
||||
/// Appends the name of the coding key.
|
||||
///
|
||||
/// // SELECT name FROM player
|
||||
/// let request: SQLRequest<String> = "
|
||||
/// let request: SQLRequest<String> = """
|
||||
/// SELECT \(CodingKey.name) FROM player
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ key: T)
|
||||
where T: CodingKey
|
||||
public mutating func appendInterpolation(_ codingKey: CodingKey) {
|
||||
appendInterpolation(Column(codingKey.stringValue))
|
||||
}
|
||||
|
||||
// When a value is both an expression and a sequence of expressions,
|
||||
// favor the expression side. Use case: Foundation.Data interpolation.
|
||||
/// :nodoc:
|
||||
public mutating func appendInterpolation<T>(_ expressible: T)
|
||||
where T: Sequence, T.Element: SQLExpressible, T: SQLExpressible
|
||||
{
|
||||
appendInterpolation(Column(key.stringValue))
|
||||
elements.append(.expression(expressible.sqlExpression))
|
||||
}
|
||||
|
||||
/// Appends the name of the coding key.
|
||||
///
|
||||
/// // SELECT name FROM player
|
||||
/// let request: SQLRequest<String> = "
|
||||
/// SELECT \(CodingKey.name) FROM player
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ key: T)
|
||||
where T: CodingKey & SQLExpressible & SQLSelectable & SQLOrderingTerm
|
||||
{
|
||||
appendInterpolation(Column(key.stringValue))
|
||||
}
|
||||
|
||||
/// Appends the name of the coding key.
|
||||
///
|
||||
/// // SELECT name FROM player
|
||||
/// let request: SQLRequest<String> = "
|
||||
/// SELECT \(CodingKey.name) FROM player
|
||||
/// """
|
||||
@_disfavoredOverload
|
||||
public mutating func appendInterpolation(_ key: CodingKey) {
|
||||
appendInterpolation(Column(key.stringValue))
|
||||
}
|
||||
|
||||
// MARK: - SQLRequestProtocol
|
||||
|
||||
/// Appends the request SQL (not wrapped inside parentheses).
|
||||
///
|
||||
/// let subquery = Player.select(max(Column("score")))
|
||||
/// // or
|
||||
/// let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
///
|
||||
/// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player)
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE score = (\(subquery))
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ request: T)
|
||||
where T: SQLRequestProtocol
|
||||
{
|
||||
elements.append(.subquery(request))
|
||||
}
|
||||
|
||||
/// Appends the request SQL (not wrapped inside parentheses).
|
||||
///
|
||||
/// let subquery = Player.select(max(Column("score")))
|
||||
/// // or
|
||||
/// let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
///
|
||||
/// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player)
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE score = (\(subquery))
|
||||
/// """
|
||||
@_disfavoredOverload
|
||||
public mutating func appendInterpolation(_ request: SQLRequestProtocol) {
|
||||
elements.append(.subquery(request))
|
||||
}
|
||||
|
||||
// MARK: - Sequence
|
||||
|
||||
|
||||
/// Appends a sequence of expressions, wrapped in parentheses.
|
||||
///
|
||||
/// // SELECT * FROM player WHERE id IN (?,?,?)
|
||||
@@ -243,9 +107,7 @@ extension SQLInterpolation {
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE id IN \(ids)
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ sequence: T)
|
||||
where T: Sequence, T.Element: SQLExpressible
|
||||
{
|
||||
public mutating func appendInterpolation<S>(_ sequence: S) where S: Sequence, S.Element: SQLExpressible {
|
||||
appendInterpolation(sequence.lazy.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
@@ -264,9 +126,7 @@ extension SQLInterpolation {
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE a IN \(expressions)
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ sequence: T)
|
||||
where T: Sequence, T.Element == SQLExpression
|
||||
{
|
||||
public mutating func appendInterpolation<S>(_ sequence: S) where S: Sequence, S.Element == SQLExpression {
|
||||
let e: [SQLLiteral.Element] = sequence.map { .expression($0.sqlExpression) }
|
||||
if e.isEmpty {
|
||||
appendLiteral("(SELECT NULL WHERE NULL)")
|
||||
@@ -277,12 +137,24 @@ extension SQLInterpolation {
|
||||
}
|
||||
}
|
||||
|
||||
// When a value is both an expression and a sequence of expressions,
|
||||
// favor the expression side. Use case: Foundation.Data interpolation.
|
||||
/// :nodoc:
|
||||
public mutating func appendInterpolation<T>(_ expressible: T)
|
||||
where T: Sequence, T: SQLExpressible, T.Element: SQLExpressible
|
||||
{
|
||||
elements.append(.expression(expressible.sqlExpression))
|
||||
/// Appends the ordering SQL.
|
||||
///
|
||||
/// // SELECT name FROM player ORDER BY name DESC
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player ORDER BY \(Column("name").desc)
|
||||
/// """
|
||||
public mutating func appendInterpolation(_ ordering: SQLOrderingTerm) {
|
||||
elements.append(.orderingTerm(ordering))
|
||||
}
|
||||
|
||||
/// Appends the request SQL, wrapped in parentheses
|
||||
///
|
||||
/// // SELECT name FROM player WHERE score = (SELECT MAX(score) FROM player)
|
||||
/// let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE score = \(subQuery)
|
||||
/// """
|
||||
public mutating func appendInterpolation<T>(_ request: SQLRequest<T>) {
|
||||
elements.append(.subQuery(request.sqlLiteral))
|
||||
}
|
||||
}
|
||||
@@ -115,7 +115,7 @@ extension Database {
|
||||
unique: unique,
|
||||
ifNotExists: ifNotExists,
|
||||
condition: condition?.sqlExpression)
|
||||
let sql = try definition.sql(self)
|
||||
let sql = definition.sql()
|
||||
try execute(sql: sql)
|
||||
}
|
||||
|
||||
@@ -457,7 +457,7 @@ public final class TableDefinition {
|
||||
|
||||
for checkExpression in checkConstraints {
|
||||
var chunks: [String] = []
|
||||
try chunks.append("CHECK (\(checkExpression.quotedSQL(db)))")
|
||||
chunks.append("CHECK (\(checkExpression.quotedSQL()))")
|
||||
items.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
@@ -470,9 +470,9 @@ public final class TableDefinition {
|
||||
statements.append(chunks.joined(separator: " "))
|
||||
}
|
||||
|
||||
let indexStatements = try columns
|
||||
let indexStatements = columns
|
||||
.compactMap { $0.indexDefinition(in: name) }
|
||||
.map { try $0.sql(db) }
|
||||
.map { $0.sql() }
|
||||
statements.append(contentsOf: indexStatements)
|
||||
return statements.joined(separator: "; ")
|
||||
}
|
||||
@@ -571,7 +571,7 @@ public final class TableAlteration {
|
||||
statements.append(statement)
|
||||
|
||||
if let indexDefinition = column.indexDefinition(in: name) {
|
||||
try statements.append(indexDefinition.sql(db))
|
||||
statements.append(indexDefinition.sql())
|
||||
}
|
||||
case let .rename(oldName, newName):
|
||||
var chunks: [String] = []
|
||||
@@ -884,11 +884,11 @@ public final class ColumnDefinition {
|
||||
}
|
||||
|
||||
for checkConstraint in checkConstraints {
|
||||
try chunks.append("CHECK (\(checkConstraint.quotedSQL(db)))")
|
||||
chunks.append("CHECK (\(checkConstraint.quotedSQL()))")
|
||||
}
|
||||
|
||||
if let defaultExpression = defaultExpression {
|
||||
try chunks.append("DEFAULT \(defaultExpression.quotedSQL(db))")
|
||||
chunks.append("DEFAULT \(defaultExpression.quotedSQL())")
|
||||
}
|
||||
|
||||
if let collationName = collationName {
|
||||
@@ -958,7 +958,7 @@ private struct IndexDefinition {
|
||||
let ifNotExists: Bool
|
||||
let condition: SQLExpression?
|
||||
|
||||
func sql(_ db: Database) throws -> String {
|
||||
func sql() -> String {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CREATE")
|
||||
if unique {
|
||||
@@ -976,7 +976,7 @@ private struct IndexDefinition {
|
||||
)
|
||||
""")
|
||||
if let condition = condition {
|
||||
try chunks.append("WHERE \(condition.quotedSQL(db))")
|
||||
chunks.append("WHERE \(condition.quotedSQL())")
|
||||
}
|
||||
return chunks.joined(separator: " ")
|
||||
}
|
||||
|
||||
@@ -487,9 +487,23 @@ extension TableRecord where Self: EncodableRecord {
|
||||
where A.OriginRowDecoder == Self
|
||||
{
|
||||
let destinationRelation = association.sqlAssociation.destinationRelation(fromOriginRows: { db in
|
||||
try [PersistenceContainer(db, self)]
|
||||
try [Row(PersistenceContainer(db, self))]
|
||||
})
|
||||
return QueryInterfaceRequest(relation: destinationRelation)
|
||||
let request = QueryInterfaceRequest<A.RowDecoder>(relation: destinationRelation)
|
||||
|
||||
// Deal with "firstOnly" relations
|
||||
guard let firstOnlyIndex = association.sqlAssociation.steps.firstIndex(where: { $0.relation.firstOnly }) else {
|
||||
return request
|
||||
}
|
||||
|
||||
if
|
||||
let toManyIndex = association.sqlAssociation.steps.lastIndex(where: { !$0.isSingular }),
|
||||
toManyIndex > firstOnlyIndex
|
||||
{
|
||||
fatalError("Not implemented: loading multiple records associated to a `first` or `last` to-one association")
|
||||
}
|
||||
|
||||
return request.limit(1)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -547,29 +561,32 @@ extension TableRecord {
|
||||
|
||||
// MARK: - Association Aggregates
|
||||
|
||||
// TODO: replace rowid with actual primary key in the doc when implemented
|
||||
/// Creates a request with *aggregates* appended to the selection.
|
||||
///
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
|
||||
/// // FROM player LEFT JOIN book ...
|
||||
/// var request = Player.annotated(with: Player.books.count)
|
||||
public static func annotated(with aggregates: AssociationAggregate<Self>...) -> QueryInterfaceRequest<Self> {
|
||||
all().annotated(with: aggregates)
|
||||
}
|
||||
|
||||
// TODO: replace rowid with actual primary key in the doc when implemented
|
||||
/// Creates a request with *aggregates* appended to the selection.
|
||||
///
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.rowid) AS bookCount
|
||||
/// // FROM player LEFT JOIN book ...
|
||||
/// var request = Player.annotated(with: [Player.books.count])
|
||||
public static func annotated(with aggregates: [AssociationAggregate<Self>]) -> QueryInterfaceRequest<Self> {
|
||||
all().annotated(with: aggregates)
|
||||
}
|
||||
|
||||
// TODO: replace rowid with actual primary key in the doc when implemented
|
||||
/// Creates a request with the provided aggregate *predicate*.
|
||||
///
|
||||
/// // SELECT player.*
|
||||
/// // FROM player LEFT JOIN book ...
|
||||
/// // HAVING COUNT(DISTINCT book.id) = 0
|
||||
/// // HAVING COUNT(DISTINCT book.rowid) = 0
|
||||
/// var request = Player.all()
|
||||
/// request = request.having(Player.books.isEmpty)
|
||||
///
|
||||
|
||||
@@ -2,12 +2,6 @@ extension TableRecord {
|
||||
|
||||
// MARK: Request Derivation
|
||||
|
||||
static var relationForAll: SQLRelation {
|
||||
SQLRelation(
|
||||
source: .table(tableName: databaseTableName, alias: nil),
|
||||
selectionPromise: DatabasePromise(value: databaseSelection))
|
||||
}
|
||||
|
||||
/// Creates a request which fetches all records.
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
@@ -17,7 +11,10 @@ extension TableRecord {
|
||||
/// all requests by the `TableRecord.databaseSelection` property, or
|
||||
/// for individual requests with the `TableRecord.select` method.
|
||||
public static func all() -> QueryInterfaceRequest<Self> {
|
||||
QueryInterfaceRequest(relation: relationForAll)
|
||||
let relation = SQLRelation(
|
||||
source: .table(tableName: databaseTableName, alias: nil),
|
||||
selection: databaseSelection)
|
||||
return QueryInterfaceRequest(relation: relation)
|
||||
}
|
||||
|
||||
/// Creates a request which fetches no record.
|
||||
@@ -126,31 +123,6 @@ extension TableRecord {
|
||||
all().select(literal: sqlLiteral, as: type)
|
||||
}
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// Creates a request which selects the primary key of the table.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player: TableRecord { ... }
|
||||
///
|
||||
/// let playerIds = dbQueue.read { db in
|
||||
/// try Player.selectPrimaryKey(as: Int64.self).fetchAll(db)
|
||||
/// }
|
||||
///
|
||||
/// For tables that have no explicit primary key, the request selects the
|
||||
/// `rowid` column.
|
||||
///
|
||||
/// For tables whose primary key spans several columns, the current
|
||||
/// implementation also returns a request that selects the `rowid` column.
|
||||
/// Future GRDB versions may return a [row value](https://www.sqlite.org/rowvalue.html).
|
||||
public static func selectPrimaryKey<RowDecoder>(
|
||||
as type: RowDecoder.Type = RowDecoder.self)
|
||||
-> QueryInterfaceRequest<RowDecoder>
|
||||
{
|
||||
all().selectPrimaryKey(as: type)
|
||||
}
|
||||
|
||||
/// Creates a request which appends *selection*.
|
||||
///
|
||||
/// // SELECT id, email, name FROM player
|
||||
|
||||
@@ -320,7 +320,7 @@ extension JSONRequiredEncoder: UnkeyedEncodingContainer {
|
||||
mutating func superEncoder() -> Encoder { self }
|
||||
}
|
||||
|
||||
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
|
||||
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
|
||||
private var iso8601Formatter: ISO8601DateFormatter = {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
formatter.formatOptions = .withInternetDateTime
|
||||
@@ -342,7 +342,7 @@ extension DatabaseDateEncodingStrategy {
|
||||
case .secondsSince1970:
|
||||
return Int64(floor(date.timeIntervalSince1970))
|
||||
case .iso8601:
|
||||
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
|
||||
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
|
||||
return iso8601Formatter.string(from: date)
|
||||
} else {
|
||||
fatalError("ISO8601DateFormatter is unavailable on this platform.")
|
||||
|
||||
@@ -348,7 +348,7 @@ public enum DatabaseDateEncodingStrategy {
|
||||
case millisecondsSince1970
|
||||
|
||||
/// Encodes dates according to the ISO 8601 and RFC 3339 standards
|
||||
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
|
||||
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
|
||||
case iso8601
|
||||
|
||||
/// Encodes a String, according to the provided formatter
|
||||
|
||||
@@ -45,7 +45,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
throw DecodingError.keyNotFound(
|
||||
codingKey,
|
||||
DecodingError.Context(
|
||||
codingPath: Array(codingPath.dropLast()),
|
||||
codingPath: Array(codingPath.dropLast()), // TODO: remove Array initializer when Swift >= 5
|
||||
debugDescription: debugDescription))
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
guard let key = codingPath.last else {
|
||||
fatalError("single value decoding from database row is not supported")
|
||||
}
|
||||
guard let index = row.index(forColumn: key.stringValue) else {
|
||||
guard let index = row.index(ofColumn: key.stringValue) else {
|
||||
// Don't use DecodingError.keyNotFound:
|
||||
// We need to specifically recognize missing columns in order to
|
||||
// provide correct feedback.
|
||||
@@ -73,24 +73,20 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
self.decoder = decoder
|
||||
}
|
||||
|
||||
lazy var allKeys: [Key] = {
|
||||
var allKeys: [Key] {
|
||||
let row = decoder.row
|
||||
return Set(row.columnNames)
|
||||
.union(row.scopesTree.names)
|
||||
.union(row.prefetchedRows.keys)
|
||||
.compactMap(Key.init(stringValue:))
|
||||
}()
|
||||
.union(Set(row.scopesTree.names))
|
||||
.union(Set(row.prefetchedRows.keys))
|
||||
.compactMap { Key(stringValue: $0) }
|
||||
}
|
||||
|
||||
func contains(_ key: Key) -> Bool {
|
||||
let row = decoder.row
|
||||
return row.hasColumn(key.stringValue)
|
||||
|| (row.scopesTree[key.stringValue] != nil)
|
||||
|| (row.prefetchedRows[key.stringValue] != nil)
|
||||
return row.hasColumn(key.stringValue) || (row.scopesTree[key.stringValue] != nil)
|
||||
}
|
||||
|
||||
func decodeNil(forKey key: Key) throws -> Bool {
|
||||
// Nil is only possible for columns and scopes (optional
|
||||
// associations), not for prefetched rows.
|
||||
let row = decoder.row
|
||||
return row[key.stringValue] == nil && (row.scopesTree[key.stringValue] == nil)
|
||||
}
|
||||
@@ -117,7 +113,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
let keyName = key.stringValue
|
||||
|
||||
// Column?
|
||||
if let index = row.index(forColumn: keyName) {
|
||||
if let index = row.index(ofColumn: keyName) {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
if type == Date.self {
|
||||
@@ -147,7 +143,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
let keyName = key.stringValue
|
||||
|
||||
// Column?
|
||||
if let index = row.index(forColumn: keyName) {
|
||||
if let index = row.index(ofColumn: keyName) {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows decoding Date from String, or DatabaseValue from NULL.
|
||||
if type == Date.self {
|
||||
@@ -200,14 +196,15 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
// Our current strategy is to assume that a missing key (such as
|
||||
// "book", which is not the name of a column, and not the name of a
|
||||
// scope) has to be decoded right from the base row.
|
||||
//
|
||||
// Yeah, there may be better ways to handle this.
|
||||
if let decodedRootKey = decodedRootKey {
|
||||
throw DecodingError.keyNotFound(decodedRootKey, DecodingError.Context(
|
||||
codingPath: codingPath,
|
||||
debugDescription: "No such key: \(decodedRootKey.stringValue)"))
|
||||
} else {
|
||||
decodedRootKey = key
|
||||
return try decode(type, fromRow: row, codingPath: codingPath + [key])
|
||||
debugDescription: "No such key: \(decodedRootKey.stringValue)")) // TODO: better error message
|
||||
}
|
||||
decodedRootKey = key
|
||||
return try decode(type, fromRow: row, codingPath: codingPath + [key])
|
||||
}
|
||||
|
||||
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key)
|
||||
@@ -412,7 +409,7 @@ private struct MissingColumnError: Error {
|
||||
var column: String
|
||||
}
|
||||
|
||||
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
|
||||
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
|
||||
private var iso8601Formatter: ISO8601DateFormatter = {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
formatter.formatOptions = .withInternetDateTime
|
||||
@@ -461,7 +458,7 @@ extension DatabaseDateDecodingStrategy {
|
||||
let timeInterval = TimeInterval(sqliteStatement: sqliteStatement, index: index)
|
||||
return Date(timeIntervalSince1970: timeInterval / 1000.0)
|
||||
case .iso8601:
|
||||
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
|
||||
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
|
||||
let string = String(sqliteStatement: sqliteStatement, index: index)
|
||||
guard let date = iso8601Formatter.date(from: string) else {
|
||||
fatalConversionError(to: Date.self, sqliteStatement: sqliteStatement, index: index)
|
||||
@@ -540,7 +537,7 @@ extension DatabaseDateDecodingStrategy {
|
||||
.fromDatabaseValue(dbValue)
|
||||
.map { Date(timeIntervalSince1970: $0 / 1000.0) }
|
||||
case .iso8601:
|
||||
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
|
||||
if #available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
|
||||
return String
|
||||
.fromDatabaseValue(dbValue)
|
||||
.flatMap { iso8601Formatter.date(from: $0) }
|
||||
|
||||
@@ -497,7 +497,7 @@ public enum DatabaseDateDecodingStrategy {
|
||||
case millisecondsSince1970
|
||||
|
||||
/// Decodes dates according to the ISO 8601 standards
|
||||
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
|
||||
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
|
||||
case iso8601
|
||||
|
||||
/// Decodes a String, according to the provided formatter
|
||||
|
||||
@@ -103,7 +103,7 @@ public final class FetchedRecordsController<Record: FetchableRecord> {
|
||||
where Request: FetchRequest, Request.RowDecoder == Record
|
||||
{
|
||||
self.itemsAreIdenticalFactory = itemsAreIdenticalFactory
|
||||
self.request = AnyFetchRequest(request).asRequest(of: Item<Record>.self)
|
||||
self.request = ItemRequest(request)
|
||||
(self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
|
||||
let region = try request.databaseRegion(db)
|
||||
let itemsAreIdentical = try itemsAreIdenticalFactory(db)
|
||||
@@ -166,7 +166,7 @@ public final class FetchedRecordsController<Record: FetchableRecord> {
|
||||
throws
|
||||
where Request: FetchRequest, Request.RowDecoder == Record
|
||||
{
|
||||
self.request = AnyFetchRequest(request).asRequest(of: Item<Record>.self)
|
||||
self.request = ItemRequest(request)
|
||||
(self.region, self.itemsAreIdentical) = try databaseWriter.unsafeRead { db in
|
||||
let region = try request.databaseRegion(db)
|
||||
let itemsAreIdentical = try itemsAreIdenticalFactory(db)
|
||||
@@ -389,7 +389,8 @@ public final class FetchedRecordsController<Record: FetchableRecord> {
|
||||
private let itemsAreIdenticalFactory: ItemComparatorFactory<Record>
|
||||
|
||||
/// The request
|
||||
fileprivate var request: AnyFetchRequest<Item<Record>>
|
||||
fileprivate typealias ItemRequest = AnyFetchRequest<Item<Record>>
|
||||
fileprivate var request: ItemRequest
|
||||
|
||||
/// The observed database region
|
||||
private var region: DatabaseRegion
|
||||
|
||||
@@ -975,9 +975,9 @@ private struct InsertQuery: Hashable {
|
||||
}
|
||||
|
||||
extension InsertQuery {
|
||||
@ReadWriteBox private static var sqlCache: [InsertQuery: String] = [:]
|
||||
static let sqlCache = ReadWriteBox(value: [InsertQuery: String]())
|
||||
var sql: String {
|
||||
if let sql = Self.sqlCache[self] {
|
||||
if let sql = InsertQuery.sqlCache.read({ $0[self] }) {
|
||||
return sql
|
||||
}
|
||||
let columnsSQL = insertedColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ")
|
||||
@@ -996,7 +996,7 @@ extension InsertQuery {
|
||||
VALUES (\(valuesSQL))
|
||||
"""
|
||||
}
|
||||
Self.sqlCache[self] = sql
|
||||
InsertQuery.sqlCache.write { $0[self] = sql }
|
||||
return sql
|
||||
}
|
||||
}
|
||||
@@ -1012,9 +1012,9 @@ private struct UpdateQuery: Hashable {
|
||||
}
|
||||
|
||||
extension UpdateQuery {
|
||||
@ReadWriteBox private static var sqlCache: [UpdateQuery: String] = [:]
|
||||
static let sqlCache = ReadWriteBox(value: [UpdateQuery: String]())
|
||||
var sql: String {
|
||||
if let sql = Self.sqlCache[self] {
|
||||
if let sql = UpdateQuery.sqlCache.read({ $0[self] }) {
|
||||
return sql
|
||||
}
|
||||
let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ")
|
||||
@@ -1034,7 +1034,7 @@ extension UpdateQuery {
|
||||
WHERE \(whereSQL)
|
||||
"""
|
||||
}
|
||||
Self.sqlCache[self] = sql
|
||||
UpdateQuery.sqlCache.write { $0[self] = sql }
|
||||
return sql
|
||||
}
|
||||
}
|
||||
|
||||
@@ -114,6 +114,28 @@ extension TableRecord {
|
||||
|
||||
// MARK: - SQL Generation
|
||||
|
||||
/// The selection as an SQL String.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// static let databaseTableName = "player"
|
||||
/// }
|
||||
///
|
||||
/// // SELECT "player".* FROM player
|
||||
/// let sql = "SELECT \(Player.selectionSQL()) FROM player"
|
||||
///
|
||||
/// // SELECT "p".* FROM player AS p
|
||||
/// let sql = "SELECT \(Player.selectionSQL(alias: "p")) FROM player p"
|
||||
public static func selectionSQL(alias: String? = nil) -> String {
|
||||
let alias = TableAlias(tableName: databaseTableName, userName: alias)
|
||||
let selection = databaseSelection.map { $0.qualifiedSelectable(with: alias) }
|
||||
var context = SQLGenerationContext.selectionContext
|
||||
return selection
|
||||
.map { $0.resultColumnSQL(&context) }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
|
||||
/// Returns the number of selected columns.
|
||||
///
|
||||
/// For example:
|
||||
@@ -140,32 +162,6 @@ extension TableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
extension TableRecord {
|
||||
// MARK: - Primary Key
|
||||
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The primary key of the table.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct Player: TableRecord { ... }
|
||||
///
|
||||
/// let player = dbQueue.read { db in
|
||||
/// try Player.filter(Player.primaryKey == 12).fetchOne(db)
|
||||
/// }
|
||||
///
|
||||
/// For tables that have no explicit primary key, this property returns the
|
||||
/// `rowid` column.
|
||||
///
|
||||
/// For tables whose primary key spans several columns, the current
|
||||
/// implementation also returns the `rowid` column. Future GRDB versions
|
||||
/// may return a [row value](https://www.sqlite.org/rowvalue.html).
|
||||
public static var primaryKey: SQLPrimaryKeyExpression {
|
||||
SQLPrimaryKeyExpression(tableName: databaseTableName)
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculating `defaultDatabaseTableName` is somewhat expensive due to the regular expression evaluation
|
||||
///
|
||||
/// This cache mitigates the cost of the calculation by storing the name for later retrieval
|
||||
|
||||
+10
-13
@@ -1,39 +1,36 @@
|
||||
import Foundation
|
||||
|
||||
/// A LockedBox protects a value with an NSLock.
|
||||
@propertyWrapper
|
||||
final class LockedBox<T> {
|
||||
private var _wrappedValue: T
|
||||
private var _value: T
|
||||
private var lock = NSLock()
|
||||
|
||||
var wrappedValue: T {
|
||||
var value: T {
|
||||
get { read { $0 } }
|
||||
set { update { $0 = newValue } }
|
||||
set { write { $0 = newValue } }
|
||||
}
|
||||
|
||||
var projectedValue: LockedBox<T> { self }
|
||||
|
||||
init(wrappedValue: T) {
|
||||
_wrappedValue = wrappedValue
|
||||
init(value: T) {
|
||||
_value = value
|
||||
}
|
||||
|
||||
func read<U>(_ block: (T) throws -> U) rethrows -> U {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return try block(_wrappedValue)
|
||||
return try block(_value)
|
||||
}
|
||||
|
||||
func update<U>(_ block: (inout T) throws -> U) rethrows -> U {
|
||||
func write<U>(_ block: (inout T) throws -> U) rethrows -> U {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return try block(&_wrappedValue)
|
||||
return try block(&_value)
|
||||
}
|
||||
}
|
||||
|
||||
extension LockedBox where T: Numeric {
|
||||
@discardableResult
|
||||
func increment() -> T {
|
||||
update { n in
|
||||
write { n in
|
||||
n += 1
|
||||
return n
|
||||
}
|
||||
@@ -41,7 +38,7 @@ extension LockedBox where T: Numeric {
|
||||
|
||||
@discardableResult
|
||||
func decrement() -> T {
|
||||
update { n in
|
||||
write { n in
|
||||
n -= 1
|
||||
return n
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ final class Pool<T> {
|
||||
}
|
||||
|
||||
private let makeElement: () throws -> T
|
||||
@ReadWriteBox private var items: [Item] = []
|
||||
private var items: ReadWriteBox<[Item]> = ReadWriteBox(value: [])
|
||||
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
|
||||
private let itemsGroup: DispatchGroup // knows when no element is used
|
||||
private let barrierQueue: DispatchQueue
|
||||
@@ -67,7 +67,7 @@ final class Pool<T> {
|
||||
itemsSemaphore.wait()
|
||||
itemsGroup.enter()
|
||||
do {
|
||||
let item = try $items.update { items -> Item in
|
||||
let item = try items.write { items -> Item in
|
||||
if let item = items.first(where: \.isAvailable) {
|
||||
item.isAvailable = false
|
||||
return item
|
||||
@@ -96,7 +96,7 @@ final class Pool<T> {
|
||||
}
|
||||
|
||||
private func release(_ item: Item) {
|
||||
$items.update { _ in
|
||||
items.write { _ in
|
||||
// This is why Item is a class, not a struct: so that we can
|
||||
// release it without having to find in it the items array.
|
||||
item.isAvailable = true
|
||||
@@ -108,7 +108,7 @@ final class Pool<T> {
|
||||
/// Performs a block on each pool element, available or not.
|
||||
/// The block is run is some arbitrary dispatch queue.
|
||||
func forEach(_ body: (T) throws -> Void) rethrows {
|
||||
try $items.read { items in
|
||||
try items.read { items in
|
||||
for item in items {
|
||||
try body(item.element)
|
||||
}
|
||||
@@ -118,7 +118,9 @@ final class Pool<T> {
|
||||
/// Removes all elements from the pool.
|
||||
/// Currently used elements won't be reused.
|
||||
func removeAll() {
|
||||
items = []
|
||||
items.write {
|
||||
$0.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocks until no element is used, and runs the `barrier` function before
|
||||
|
||||
@@ -1,33 +1,29 @@
|
||||
import Dispatch
|
||||
|
||||
/// A ReadWriteBox grants multiple readers and single-writer guarantees on a
|
||||
/// value. It is backed by a concurrent DispatchQueue.
|
||||
@propertyWrapper
|
||||
/// A ReadWriteBox grants multiple readers and single-writer guarantees on a value.
|
||||
final class ReadWriteBox<T> {
|
||||
private var _wrappedValue: T
|
||||
private var _value: T
|
||||
private var queue: DispatchQueue
|
||||
|
||||
var wrappedValue: T {
|
||||
var value: T {
|
||||
get { read { $0 } }
|
||||
set { update { $0 = newValue } }
|
||||
set { write { $0 = newValue } }
|
||||
}
|
||||
|
||||
var projectedValue: ReadWriteBox<T> { self }
|
||||
|
||||
init(wrappedValue: T) {
|
||||
_wrappedValue = wrappedValue
|
||||
init(value: T) {
|
||||
_value = value
|
||||
queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent])
|
||||
}
|
||||
|
||||
func read<U>(_ block: (T) throws -> U) rethrows -> U {
|
||||
try queue.sync {
|
||||
try block(_wrappedValue)
|
||||
try block(_value)
|
||||
}
|
||||
}
|
||||
|
||||
func update<U>(_ block: (inout T) throws -> U) rethrows -> U {
|
||||
func write<U>(_ block: (inout T) throws -> U) rethrows -> U {
|
||||
try queue.sync(flags: [.barrier]) {
|
||||
try block(&_wrappedValue)
|
||||
try block(&_value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,7 +31,7 @@ final class ReadWriteBox<T> {
|
||||
extension ReadWriteBox where T: Numeric {
|
||||
@discardableResult
|
||||
func increment() -> T {
|
||||
update { n in
|
||||
write { n in
|
||||
n += 1
|
||||
return n
|
||||
}
|
||||
@@ -43,7 +39,7 @@ extension ReadWriteBox where T: Numeric {
|
||||
|
||||
@discardableResult
|
||||
func decrement() -> T {
|
||||
update { n in
|
||||
write { n in
|
||||
n -= 1
|
||||
return n
|
||||
}
|
||||
|
||||
@@ -87,8 +87,6 @@
|
||||
563B071321862C3E00B38F35 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */; };
|
||||
563B071B21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
|
||||
563B071C21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */; };
|
||||
563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; };
|
||||
563C67B924628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; };
|
||||
563DE4F8231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; };
|
||||
563DE4F9231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; };
|
||||
563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */; };
|
||||
@@ -109,6 +107,10 @@
|
||||
5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */; };
|
||||
564B3D72239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
|
||||
564B3D73239BDBD6007BF308 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */; };
|
||||
564C2456244A44F8003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2454244A44F7003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
|
||||
564C2457244A44F8003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C2454244A44F7003D7B05 /* AssociationHasManyFirstSQLTests.swift */; };
|
||||
564C245E244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C245D244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
|
||||
564C245F244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564C245D244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */; };
|
||||
564CE43C21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; };
|
||||
564CE43D21AA955B00652B19 /* ValueObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE43B21AA955B00652B19 /* ValueObserver.swift */; };
|
||||
564CE4E321B2E05400652B19 /* ValueObservationMapTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */; };
|
||||
@@ -313,6 +315,8 @@
|
||||
56781B09243F7B5300650A83 /* GRDB-Bridging.h in Headers */ = {isa = PBXBuildFile; fileRef = 56781B06243F7B4B00650A83 /* GRDB-Bridging.h */; settings = {ATTRIBUTES = (Public, ); }; };
|
||||
567A80561D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
|
||||
567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567A80521D41350C00C7DCEC /* IndexInfoTests.swift */; };
|
||||
567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
567DAF211EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
|
||||
567DAF3C1EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
|
||||
567E4209242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */; };
|
||||
@@ -424,8 +428,6 @@
|
||||
56C0539D22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */; };
|
||||
56C0539E22ACEECD0029D27D /* RemoveDuplicates.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */; };
|
||||
56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; };
|
||||
56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
56C9EB9C2495324700FE5D55 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 56C9EB9A2495324700FE5D55 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; };
|
||||
56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; };
|
||||
56CC923B201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */; };
|
||||
@@ -466,12 +468,8 @@
|
||||
56ED8A801DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; };
|
||||
56F3E74C1E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
|
||||
56F3E7501E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
|
||||
56F409282465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */; };
|
||||
56F409292465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */; };
|
||||
56FBFED62210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; };
|
||||
56FBFED72210731100945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED52210731000945324 /* SQLRequest.swift */; };
|
||||
56FEB8FE248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; };
|
||||
56FEB8FF248403270081AF83 /* DatabaseTraceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */; };
|
||||
56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
|
||||
56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FEE7FA1F47253700D930EA /* TableRecordTests.swift */; };
|
||||
56FF45431D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; };
|
||||
@@ -782,7 +780,6 @@
|
||||
563B0701218627DE00B38F35 /* ValueObservationRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRowTests.swift; sourceTree = "<group>"; };
|
||||
563B071121862C3E00B38F35 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
|
||||
563B071A21862F5600B38F35 /* ValueObservationDatabaseValueConvertibleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationDatabaseValueConvertibleTests.swift; sourceTree = "<group>"; };
|
||||
563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = "<group>"; };
|
||||
563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = "<group>"; };
|
||||
563EF41E215F8A76007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = "<group>"; };
|
||||
563EF441216131F5007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = "<group>"; };
|
||||
@@ -794,6 +791,8 @@
|
||||
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = "<group>"; };
|
||||
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
|
||||
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
|
||||
564C2454244A44F7003D7B05 /* AssociationHasManyFirstSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyFirstSQLTests.swift; sourceTree = "<group>"; };
|
||||
564C245D244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughFirstSQLTests.swift; sourceTree = "<group>"; };
|
||||
564CE43B21AA955B00652B19 /* ValueObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObserver.swift; sourceTree = "<group>"; };
|
||||
564CE4E221B2E05400652B19 /* ValueObservationMapTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationMapTests.swift; sourceTree = "<group>"; };
|
||||
564CE5B521B8FBEA00652B19 /* DatabaseRegionObservation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservation.swift; sourceTree = "<group>"; };
|
||||
@@ -905,6 +904,7 @@
|
||||
5676FBA822F5CEB8004717D9 /* ValueObservationRegionRecordingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRegionRecordingTests.swift; sourceTree = "<group>"; };
|
||||
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDB-Bridging.h"; path = "SQLiteCustom/GRDB-Bridging.h"; sourceTree = "<group>"; };
|
||||
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
|
||||
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
|
||||
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
|
||||
567E4207242AB3CB00CAAD2C /* FailableTestCase.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FailableTestCase.swift; sourceTree = "<group>"; };
|
||||
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
|
||||
@@ -993,6 +993,7 @@
|
||||
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
|
||||
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
|
||||
56B86E6E220FF4C800524C16 /* SQLLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLLiteralTests.swift; sourceTree = "<group>"; };
|
||||
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDB.xcconfig; sourceTree = "<group>"; };
|
||||
56B9649C1DA51B4C0002DA19 /* FTS5.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5.swift; sourceTree = "<group>"; };
|
||||
56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerDescriptor.swift; sourceTree = "<group>"; };
|
||||
56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Pattern.swift; sourceTree = "<group>"; };
|
||||
@@ -1006,8 +1007,9 @@
|
||||
56C0538E22ACEECD0029D27D /* Map.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = "<group>"; };
|
||||
56C0538F22ACEECD0029D27D /* RemoveDuplicates.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RemoveDuplicates.swift; sourceTree = "<group>"; };
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
|
||||
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
|
||||
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
|
||||
56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBDeploymentTarget.xcconfig; path = SQLiteCustom/GRDBDeploymentTarget.xcconfig; sourceTree = "<group>"; };
|
||||
56C9EB9A2495324700FE5D55 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = grdb_config.h; path = SQLiteCustom/grdb_config.h; sourceTree = "<group>"; };
|
||||
56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = "<group>"; };
|
||||
56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = "<group>"; };
|
||||
56CC9248201E058900CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1035,10 +1037,8 @@
|
||||
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
|
||||
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
|
||||
56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = "<group>"; };
|
||||
56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestProtocol.swift; sourceTree = "<group>"; };
|
||||
56FBFED52210731000945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
|
||||
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
|
||||
56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = "<group>"; };
|
||||
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRecordTests.swift; sourceTree = "<group>"; };
|
||||
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = "<group>"; };
|
||||
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1162,7 +1162,6 @@
|
||||
560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */,
|
||||
569531361C919DF700CF1A2B /* DatabasePoolFunctionTests.swift */,
|
||||
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */,
|
||||
563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */,
|
||||
);
|
||||
name = DatabasePool;
|
||||
sourceTree = "<group>";
|
||||
@@ -1346,9 +1345,11 @@
|
||||
5653EB6220961FB200F46237 /* AssociationBelongsToSQLTests.swift */,
|
||||
5653EB6020961FB100F46237 /* AssociationChainRowScopesTests.swift */,
|
||||
5653EB6320961FB200F46237 /* AssociationChainSQLTests.swift */,
|
||||
564C2454244A44F7003D7B05 /* AssociationHasManyFirstSQLTests.swift */,
|
||||
561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */,
|
||||
56057C572291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift */,
|
||||
56959635222D058B002CB7C9 /* AssociationHasManySQLTests.swift */,
|
||||
564C245D244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift */,
|
||||
561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */,
|
||||
56057C642291C7E500A7CB10 /* AssociationHasManyThroughRowScopeTests.swift */,
|
||||
5695961E222C4589002CB7C9 /* AssociationHasManyThroughSQLTests.swift */,
|
||||
@@ -1559,7 +1560,6 @@
|
||||
566A843420413DE400E50BFD /* DatabaseSnapshotTests.swift */,
|
||||
564B3D70239BDBD6007BF308 /* DatabaseSuspensionTests.swift */,
|
||||
56A238131B9C74A90082EB20 /* DatabaseTests.swift */,
|
||||
56FEB8FC248403270081AF83 /* DatabaseTraceTests.swift */,
|
||||
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */,
|
||||
56A2381B1B9C74A90082EB20 /* DatabaseValueConversionTests.swift */,
|
||||
56A238191B9C74A90082EB20 /* DatabaseValueConvertible */,
|
||||
@@ -1670,7 +1670,6 @@
|
||||
56E9FAC32210468500C703A8 /* SQLInterpolation.swift */,
|
||||
56E9FAD42210538400C703A8 /* SQLLiteral.swift */,
|
||||
56FBFED52210731000945324 /* SQLRequest.swift */,
|
||||
56F409262465C8F500A7A152 /* SQLRequestProtocol.swift */,
|
||||
56A238781B9C75030082EB20 /* Statement.swift */,
|
||||
566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */,
|
||||
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */,
|
||||
@@ -1818,9 +1817,13 @@
|
||||
DC37743319C8CFCE004FCF85 /* Supporting Files */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567DAF141EAB61ED00FC0928 /* grdb_config.h */,
|
||||
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */,
|
||||
DC3773F819C8CBB3004FCF85 /* GRDB.h */,
|
||||
56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */,
|
||||
56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */,
|
||||
DC3773F719C8CBB3004FCF85 /* Info.plist */,
|
||||
56C48E731C9A9923005DF1D9 /* module.modulemap */,
|
||||
);
|
||||
name = "Supporting Files";
|
||||
path = ../Support;
|
||||
@@ -1838,16 +1841,15 @@
|
||||
F3BA7FED1CFB21F8003DC1BA /* GRDBCustomSQLite */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56C9EB9A2495324700FE5D55 /* grdb_config.h */,
|
||||
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */,
|
||||
F3BA7FF11CFB23D3003DC1BA /* GRDB.h */,
|
||||
F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */,
|
||||
F3BA7FEF1CFB23BF003DC1BA /* module.modulemap */,
|
||||
EED476F41CFD174D0026A4EC /* Customize */,
|
||||
F3BA7FEE1CFB23B7003DC1BA /* GRDB.xcconfig */,
|
||||
F3BA813B1CFB3770003DC1BA /* GRDBCustomSQLite-Testing.xcconfig */,
|
||||
56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */,
|
||||
F3BA7FEF1CFB23BF003DC1BA /* module.modulemap */,
|
||||
F3BA7FF01CFB23C9003DC1BA /* sqlite3.h */,
|
||||
F3BA7FF11CFB23D3003DC1BA /* GRDB.h */,
|
||||
56781B06243F7B4B00650A83 /* GRDB-Bridging.h */,
|
||||
F3BA7FF31CFB23E4003DC1BA /* SQLiteLib.xcodeproj */,
|
||||
EED476F41CFD174D0026A4EC /* Customize */,
|
||||
);
|
||||
name = GRDBCustomSQLite;
|
||||
sourceTree = "<group>";
|
||||
@@ -1868,9 +1870,9 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
F3BA80381CFB2932003DC1BA /* GRDB.h in Headers */,
|
||||
56C9EB9C2495324700FE5D55 /* grdb_config.h in Headers */,
|
||||
56781B09243F7B5300650A83 /* GRDB-Bridging.h in Headers */,
|
||||
F3BA803A1CFB293A003DC1BA /* sqlite3.h in Headers */,
|
||||
567DAF211EAB61ED00FC0928 /* grdb_config.h in Headers */,
|
||||
EED476F31CFD172C0026A4EC /* GRDBCustomSQLite-USER.h in Headers */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -1880,9 +1882,9 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
F3BA80931CFB2F13003DC1BA /* GRDB.h in Headers */,
|
||||
56C9EB9B2495324700FE5D55 /* grdb_config.h in Headers */,
|
||||
56781B08243F7B5300650A83 /* GRDB-Bridging.h in Headers */,
|
||||
F3BA80951CFB2F18003DC1BA /* sqlite3.h in Headers */,
|
||||
567DAF1E1EAB61ED00FC0928 /* grdb_config.h in Headers */,
|
||||
EED476F21CFD17270026A4EC /* GRDBCustomSQLite-USER.h in Headers */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -2196,7 +2198,6 @@
|
||||
5656A87E2295BD56001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
F3BA80131CFB2876003DC1BA /* DatabaseValue.swift in Sources */,
|
||||
56C0539822ACEECD0029D27D /* ValueReducer.swift in Sources */,
|
||||
56F409292465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */,
|
||||
56A2FA3A24424F4200E97D23 /* Export.swift in Sources */,
|
||||
56B964B61DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
F3BA80171CFB2876003DC1BA /* RowAdapter.swift in Sources */,
|
||||
@@ -2320,7 +2321,6 @@
|
||||
56B14E861D4DAE54000BF4A3 /* RowFromDictionaryLiteralTests.swift in Sources */,
|
||||
566AD8CD1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */,
|
||||
5653EB7B20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
|
||||
563C67B924628C0C00E94EDC /* DatabasePoolTests.swift in Sources */,
|
||||
5698AC871DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */,
|
||||
F3BA80D11CFB2FF3003DC1BA /* MutablePersistableRecordTests.swift in Sources */,
|
||||
5653EB7320961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */,
|
||||
@@ -2349,6 +2349,7 @@
|
||||
F3BA80AF1CFB2FB1003DC1BA /* DatabaseCollationTests.swift in Sources */,
|
||||
56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */,
|
||||
567E4209242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */,
|
||||
564C245F244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
|
||||
56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
|
||||
5615B286222B17BA00061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
|
||||
5657AB651D108BA9006283EF /* FoundationNSURLTests.swift in Sources */,
|
||||
@@ -2391,7 +2392,6 @@
|
||||
567A805A1D41350C00C7DCEC /* IndexInfoTests.swift in Sources */,
|
||||
5674A7291F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
|
||||
56057C5A2291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
|
||||
56FEB8FF248403270081AF83 /* DatabaseTraceTests.swift in Sources */,
|
||||
56FEE8021F47253700D930EA /* TableRecordTests.swift in Sources */,
|
||||
F3BA81211CFB3063003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */,
|
||||
F3BA80F71CFB3021003DC1BA /* SelectStatementTests.swift in Sources */,
|
||||
@@ -2407,6 +2407,7 @@
|
||||
F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */,
|
||||
5653EB7520961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
5691578D231BF2BE00E1D237 /* PoolTests.swift in Sources */,
|
||||
564C2457244A44F8003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
|
||||
5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */,
|
||||
5665FA3E2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
56677C28241E6EA20050755D /* ValueObservationRecorder.swift in Sources */,
|
||||
@@ -2534,7 +2535,6 @@
|
||||
5656A87D2295BD56001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */,
|
||||
56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */,
|
||||
56F409282465C8F500A7A152 /* SQLRequestProtocol.swift in Sources */,
|
||||
56A2FA3924424F4200E97D23 /* Export.swift in Sources */,
|
||||
56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */,
|
||||
@@ -2658,7 +2658,6 @@
|
||||
F3BA81301CFB3064003DC1BA /* RecordPrimaryKeyRowIDTests.swift in Sources */,
|
||||
56DAA2D51DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
|
||||
5653EB7A20961FB200F46237 /* AssociationParallelRowScopesTests.swift in Sources */,
|
||||
563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */,
|
||||
F3BA80FB1CFB3021003DC1BA /* StatementArgumentsTests.swift in Sources */,
|
||||
F3BA80EE1CFB3017003DC1BA /* RowAdapterTests.swift in Sources */,
|
||||
5653EB7220961FB200F46237 /* AssociationHasOneSQLTests.swift in Sources */,
|
||||
@@ -2687,6 +2686,7 @@
|
||||
56B964DB1DA5216B0002DA19 /* FTS5RecordTests.swift in Sources */,
|
||||
56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */,
|
||||
567E420A242AB3CB00CAAD2C /* FailableTestCase.swift in Sources */,
|
||||
564C245E244A468C003D7B05 /* AssociationHasManyThroughFirstSQLTests.swift in Sources */,
|
||||
56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */,
|
||||
5615B285222B17BA00061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
|
||||
F3BA80B01CFB2FB2003DC1BA /* DatabaseCollationTests.swift in Sources */,
|
||||
@@ -2729,7 +2729,6 @@
|
||||
F3BA80FA1CFB3021003DC1BA /* SelectStatementTests.swift in Sources */,
|
||||
5674A7271F30A9090095F066 /* FetchableRecordDecodableTests.swift in Sources */,
|
||||
56057C592291B18E00A7CB10 /* AssociationHasManyRowScopeTests.swift in Sources */,
|
||||
56FEB8FE248403270081AF83 /* DatabaseTraceTests.swift in Sources */,
|
||||
56FEE7FE1F47253700D930EA /* TableRecordTests.swift in Sources */,
|
||||
F3BA81191CFB305F003DC1BA /* QueryInterfaceRequestTests.swift in Sources */,
|
||||
F3BA812F1CFB3064003DC1BA /* RecordPrimaryKeyNoneTests.swift in Sources */,
|
||||
@@ -2745,6 +2744,7 @@
|
||||
F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
|
||||
5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
5691578E231BF2BE00E1D237 /* PoolTests.swift in Sources */,
|
||||
564C2456244A44F8003D7B05 /* AssociationHasManyFirstSQLTests.swift in Sources */,
|
||||
5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
|
||||
5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */,
|
||||
56677C27241E6EA20050755D /* ValueObservationRecorder.swift in Sources */,
|
||||
|
||||
@@ -49,18 +49,11 @@ endif
|
||||
TEST_ACTIONS = clean build build-for-testing test-without-building
|
||||
|
||||
# When adding support for an Xcode version, look for available devices with `instruments -s devices`
|
||||
ifeq ($(XCODEVERSION),11.5)
|
||||
ifeq ($(XCODEVERSION),11.4)
|
||||
MAX_SWIFT_VERSION = 5.2
|
||||
MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.5"
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1"
|
||||
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.4"
|
||||
MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2"
|
||||
else ifeq ($(XCODEVERSION),11.4)
|
||||
MAX_SWIFT_VERSION = 5.2
|
||||
MIN_SWIFT_VERSION = # MAX_SWIFT_VERSION is the minimum supported Swift version
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.4.1"
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=10.3.1"
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 11,OS=13.4"
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5,OS=10.3.1"
|
||||
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV 4K,OS=13.4"
|
||||
MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=10.2"
|
||||
else
|
||||
@@ -115,7 +108,7 @@ test_framework_GRDBOSX_maxSwift:
|
||||
-scheme GRDBOSX \
|
||||
SWIFT_VERSION=$(MAX_SWIFT_VERSION) \
|
||||
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
|
||||
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
|
||||
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
@@ -126,7 +119,7 @@ ifdef MIN_SWIFT_VERSION
|
||||
-scheme GRDBOSX \
|
||||
SWIFT_VERSION=$(MIN_SWIFT_VERSION) \
|
||||
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
|
||||
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
|
||||
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
endif
|
||||
@@ -150,7 +143,7 @@ test_framework_GRDBiOS_maxTarget_maxSwift:
|
||||
-destination $(MAX_IOS_DESTINATION) \
|
||||
SWIFT_VERSION=$(MAX_SWIFT_VERSION) \
|
||||
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
|
||||
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
|
||||
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
@@ -162,7 +155,7 @@ ifdef MIN_SWIFT_VERSION
|
||||
-destination $(MAX_IOS_DESTINATION) \
|
||||
SWIFT_VERSION=$(MIN_SWIFT_VERSION) \
|
||||
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
|
||||
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
|
||||
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
endif
|
||||
@@ -186,7 +179,7 @@ test_framework_GRDBtvOS_maxTarget_maxSwift:
|
||||
-destination $(MAX_TVOS_DESTINATION) \
|
||||
SWIFT_VERSION=$(MAX_SWIFT_VERSION) \
|
||||
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
|
||||
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
|
||||
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
@@ -198,7 +191,7 @@ ifdef MIN_SWIFT_VERSION
|
||||
-destination $(MAX_TVOS_DESTINATION) \
|
||||
SWIFT_VERSION=$(MIN_SWIFT_VERSION) \
|
||||
'OTHER_SWIFT_FLAGS=$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' \
|
||||
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1 GRDB_SQLITE_ENABLE_SNAPSHOT=1' \
|
||||
'GCC_PREPROCESSOR_DEFINITIONS=$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
endif
|
||||
@@ -394,10 +387,10 @@ ifdef JAZZY
|
||||
--author 'Gwendal Roué' \
|
||||
--author_url https://github.com/groue \
|
||||
--github_url https://github.com/groue/GRDB.swift \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.0.0-beta.5 \
|
||||
--module-version 5.0.0-beta.5 \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v4.14.0 \
|
||||
--module-version 4.14.0 \
|
||||
--module GRDB \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.0.0-beta.5/ \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/4.14/ \
|
||||
--output Documentation/Reference \
|
||||
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
|
||||
else
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import PackageDescription
|
||||
let package = Package(
|
||||
name: "GRDB",
|
||||
platforms: [
|
||||
.iOS("10.0"),
|
||||
.iOS("9.0"),
|
||||
.macOS("10.10"),
|
||||
.tvOS("9.0"),
|
||||
.watchOS("2.0"),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 10.0
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 9.0
|
||||
MACOSX_DEPLOYMENT_TARGET = 10.10
|
||||
TVOS_DEPLOYMENT_TARGET = 9.0
|
||||
WATCHOS_DEPLOYMENT_TARGET = 2.0
|
||||
@@ -1,91 +0,0 @@
|
||||
#ifndef grdb_config_h
|
||||
#define grdb_config_h
|
||||
|
||||
typedef void(*errorLogCallback)(void *pArg, int iErrCode, const char *zMsg);
|
||||
|
||||
/// Wrapper around sqlite3_config(SQLITE_CONFIG_LOG, ...) which is a variadic
|
||||
/// function that can't be used from Swift.
|
||||
static inline void registerErrorLogCallback(errorLogCallback callback) {
|
||||
sqlite3_config(SQLITE_CONFIG_LOG, callback, 0);
|
||||
}
|
||||
|
||||
#if SQLITE_VERSION_NUMBER >= 3029000
|
||||
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
|
||||
/// be used from Swift.
|
||||
static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) {
|
||||
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 0, (void *)0);
|
||||
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 0, (void *)0);
|
||||
}
|
||||
|
||||
/// Wrapper around sqlite3_db_config() which is a variadic function that can't
|
||||
/// be used from Swift.
|
||||
static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) {
|
||||
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DDL, 1, (void *)0);
|
||||
sqlite3_db_config(db, SQLITE_DBCONFIG_DQS_DML, 1, (void *)0);
|
||||
}
|
||||
#else
|
||||
static inline void disableDoubleQuotedStringLiterals(sqlite3 *db) { }
|
||||
static inline void enableDoubleQuotedStringLiterals(sqlite3 *db) { }
|
||||
#endif
|
||||
|
||||
/*
|
||||
Snapshots
|
||||
=========
|
||||
|
||||
We have a linker/C-interop difficulty here:
|
||||
|
||||
- Not all SQLite versions ship with the sqlite3_snapshot_get function.
|
||||
- Not all iOS/macOS versions ship a <sqlite3.h> header that contains
|
||||
the declaration for sqlite3_snapshot_get(), even when SQLite is
|
||||
actually compiled with SQLITE_ENABLE_SNAPSHOT.
|
||||
|
||||
This makes it really difficult to deal with system SQLite, custom
|
||||
SQLite builds, SQLCipher, and SPM.
|
||||
|
||||
To avoid those problems, we add grdb_snapshot_xxx shim functions in the
|
||||
following header files:
|
||||
|
||||
- SQLiteCustom/grdb_config.h
|
||||
- Sources/CSQLite/shim.h
|
||||
- Support/grdb_config.h
|
||||
*/
|
||||
#ifdef SQLITE_ENABLE_SNAPSHOT
|
||||
static inline int grdb_snapshot_get(
|
||||
sqlite3 *db,
|
||||
const char *zSchema,
|
||||
sqlite3_snapshot **ppSnapshot)
|
||||
{
|
||||
return sqlite3_snapshot_get(db, zSchema, ppSnapshot);
|
||||
}
|
||||
|
||||
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
|
||||
sqlite3_snapshot_free(ppSnapshot);
|
||||
}
|
||||
|
||||
static inline int grdb_snapshot_cmp(
|
||||
sqlite3_snapshot *p1,
|
||||
sqlite3_snapshot *p2)
|
||||
{
|
||||
return sqlite3_snapshot_cmp(p1, p2);
|
||||
}
|
||||
#else
|
||||
static inline int grdb_snapshot_get(
|
||||
sqlite3 *db,
|
||||
const char *zSchema,
|
||||
sqlite3_snapshot **ppSnapshot)
|
||||
{
|
||||
return SQLITE_MISUSE;
|
||||
}
|
||||
|
||||
static inline void grdb_snapshot_free(sqlite3_snapshot* ppSnapshot) {
|
||||
}
|
||||
|
||||
static inline int grdb_snapshot_cmp(
|
||||
sqlite3_snapshot *p1,
|
||||
sqlite3_snapshot *p2)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
#endif /* SQLITE_ENABLE_SNAPSHOT */
|
||||
|
||||
#endif /* grdb_config_h */
|
||||
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user