mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-28 04:24:20 +00:00
Merge branch 'development'
This commit is contained in:
commit
eda960de58
142 files changed
+7423
-2326
No files matched your search
@@ -61,4 +61,3 @@ opt_in_rules:
|
||||
|
||||
vertical_whitespace:
|
||||
max_empty_lines: 2
|
||||
|
||||
+44
-44
@@ -41,121 +41,121 @@ jobs:
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test GRDB Xcode 12.2
|
||||
## Test GRDB Xcode 12.5
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.3"
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBOSX - Swift 5.3"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBOSX_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBOSX - Swift 5.2"
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBOSX - Swift 5.2"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBOSX_minSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBWatchOS"
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBWatchOS"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBWatchOS
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS maxTarget"
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBiOS iOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBiOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBiOS iOS minTarget"
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBiOS iOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBiOS_minTarget
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - GRDBtvOS maxTarget"
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBtvOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBtvOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDB Xcode 12 - GRDBtvOS minTarget"
|
||||
- name: "Test GRDB Xcode 12.5 - GRDBtvOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBtvOS_minTarget
|
||||
|
||||
- name: "Test GRDB Xcode 12.2 - SPM"
|
||||
- name: "Test GRDB Xcode 12.5 - SPM"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_SPM
|
||||
|
||||
###########################################
|
||||
## Test GRDBCustom Xcode 12.2
|
||||
## Test GRDBCustom Xcode 12.5
|
||||
|
||||
- name: "Test GRDBCustom Xcode 12.2 - GRDBOSX"
|
||||
- name: "Test GRDBCustom Xcode 12.5 - GRDBOSX"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBCustomSQLiteOSX
|
||||
|
||||
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS maxTarget"
|
||||
- name: "Test GRDBCustom Xcode 12.5 - GRDBiOS maxTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_maxTarget_maxSwift
|
||||
|
||||
- name: "Test GRDBCustom Xcode 12.2 - GRDBiOS minTarget"
|
||||
- name: "Test GRDBCustom Xcode 12.5 - GRDBiOS minTarget"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_GRDBCustomSQLiteiOS_minTarget
|
||||
|
||||
###########################################
|
||||
## Test SQLCipher Xcode 12.2
|
||||
## Test SQLCipher Xcode 12.5
|
||||
|
||||
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 3"
|
||||
- name: "Test SQLCipher Xcode 12.5 - SQLCipher 3"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_SQLCipher3
|
||||
|
||||
- name: "Test SQLCipher Xcode 12.2 - SQLCipher 4"
|
||||
- name: "Test SQLCipher Xcode 12.5 - SQLCipher 4"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_framework_SQLCipher4
|
||||
|
||||
###########################################
|
||||
## Test Installation Xcode 12.2
|
||||
## Test Installation Xcode 12.5
|
||||
|
||||
# Manual Install
|
||||
- name: "Test Installation Xcode 12.2 - Manual Install"
|
||||
- name: "Test Installation Xcode 12.5 - Manual Install"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_install_manual
|
||||
|
||||
# Travis is much too slow, and always fail this job
|
||||
# # CocoaPods Lint
|
||||
# - name: "Test Installation Xcode 12.2 - CocoaPods Lint"
|
||||
# - name: "Test Installation Xcode 12.5 - CocoaPods Lint"
|
||||
# gemfile: .ci/gemfiles/Gemfile.travis
|
||||
# osx_image: xcode12.2
|
||||
# osx_image: xcode12.5
|
||||
# script: make test_CocoaPodsLint_GRDB
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- name: "Test Installation Xcode 12.2 - CocoaPods Framework"
|
||||
- name: "Test Installation Xcode 12.5 - CocoaPods Framework"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_install_GRDB_CocoaPods_framework
|
||||
|
||||
# CocoaPods Install GRDB
|
||||
- name: "Test Installation Xcode 12.2 - CocoaPods Static"
|
||||
- name: "Test Installation Xcode 12.5 - CocoaPods Static"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_install_GRDB_CocoaPods_static
|
||||
|
||||
# SPM Install
|
||||
- name: "Test Installation Xcode 12.2 - SPM Package"
|
||||
- name: "Test Installation Xcode 12.5 - SPM Package"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_install_SPM_Package
|
||||
|
||||
# SPM Install
|
||||
- name: "Test Installation Xcode 12.2 - SPM Package in Xcode Project"
|
||||
- name: "Test Installation Xcode 12.5 - SPM Package in Xcode Project"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_install_SPM_Project
|
||||
|
||||
# Custom SQLite Install
|
||||
- name: "Test Installation Xcode 12.2 - Custom SQLite"
|
||||
- name: "Test Installation Xcode 12.5 - Custom SQLite"
|
||||
gemfile: .ci/gemfiles/Gemfile.travis
|
||||
osx_image: xcode12.2
|
||||
osx_image: xcode12.5
|
||||
script: make test_install_customSQLite
|
||||
+25
-2
@@ -7,7 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- [Development Branch](#development-branch)
|
||||
- `5.9.x` Releases - [5.9.0](#590)
|
||||
- `5.8.x` Releases - [5.8.0](#580)
|
||||
- `5.7.x` Releases - [5.7.0](#570) | [5.7.1](#571) | [5.7.2](#572) | [5.7.3](#573) | [5.7.4](#574)
|
||||
- `5.6.x` Releases - [5.6.0](#560)
|
||||
@@ -76,9 +76,32 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## Development Branch
|
||||
## 5.9.0
|
||||
|
||||
Released August 15, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.8.0...v5.9.0)
|
||||
|
||||
- **Fixed**: [#980](https://github.com/groue/GRDB.swift/pull/980) by [@jroselightricks](https://github.com/jroselightricks): Fix spelling
|
||||
- **Fixed**: [#989](https://github.com/groue/GRDB.swift/pull/989) by [@pp5x](https://github.com/pp5x): FTS: add support of ifNotExists in synchronize()
|
||||
- **Fixed**: [#999](https://github.com/groue/GRDB.swift/issues/999): `request(for: association)` no longer crashes when the foreign key contains a NULL value.
|
||||
- **Fixed**: [#1025](https://github.com/groue/GRDB.swift/issues/1025) by [@mattgallagher](https://github.com/mattgallagher): Fix ValueObservation crash
|
||||
- **Fixed**: Fix thread unsafety in `ValueObservation.print()`
|
||||
- **New**: The `selectID()` method is now available for [Identifiable Records](README.md#identifiable-records)
|
||||
- **New**: Cached prepared statements can profit from [SQL Interpolation](Documentation/SQLInterpolation.md):
|
||||
|
||||
```swift
|
||||
let updateStatement = try db.cachedStatement(literal: "INSERT ...")
|
||||
// ~~~~~~~
|
||||
```
|
||||
|
||||
- **New**: [#993](https://github.com/groue/GRDB.swift/pull/993) by [@groue](https://github.com/groue): QueryInterfaceRequest builder with dynamic table/view name
|
||||
- **New**: Types that adopt both `DatabaseValueConvertible` and `Codable` now profit from automatic JSON encoding and decoding.
|
||||
- **New**: [#1010](https://github.com/groue/GRDB.swift/pull/1010) by [@tternes](https://github.com/tternes): Add VACUUM INTO Support
|
||||
- **New**: [#1012](https://github.com/groue/GRDB.swift/pull/1012) by [@ZevEisenberg](https://github.com/ZevEisenberg): Add brackets to urls in doc comments to make them clickable
|
||||
- **New**: [#1019](https://github.com/groue/GRDB.swift/pull/1019) by [@groue](https://github.com/groue): Merge prepared statement types, and introduce statement cursor
|
||||
- **Documentation Update**: The [Requests](README.md#requests) chapter was updated for the new `Table` type that can build requests without any record type.
|
||||
- **Documentation Update**: The [Custom Value Types](README.md#custom-value-types) chapter was extended about the new support for codable value types encoded as JSON arrays or objects.
|
||||
- **Documentation Update**: The [Fetching Methods](README.md#fetching-methods) and [Prepared Statements](README.md#prepared-statements) chapters have been updated for the unique `Statement` class, and the new `Database.allStatements()` method.
|
||||
|
||||
|
||||
## 5.8.0
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import GRDB
|
||||
/// AppDatabase lets the application access the database.
|
||||
///
|
||||
/// It applies the pratices recommended at
|
||||
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
@@ -17,12 +17,12 @@ struct AppDatabase {
|
||||
/// Application can use a `DatabasePool`, while SwiftUI previews and tests
|
||||
/// can use a fast in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
|
||||
private let dbWriter: DatabaseWriter
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ extension Player {
|
||||
|
||||
/// Make Player a Codable Record.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#records>
|
||||
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
// Define database columns from CodingKeys
|
||||
fileprivate enum Columns {
|
||||
@@ -69,8 +69,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
|
||||
@@ -3,7 +3,7 @@ import GRDB
|
||||
/// AppDatabase lets the application access the database.
|
||||
///
|
||||
/// It applies the pratices recommended at
|
||||
/// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
final class AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
@@ -16,12 +16,12 @@ final class AppDatabase {
|
||||
/// Application can use a `DatabasePool`, and tests can use a fast
|
||||
/// in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
|
||||
private let dbWriter: DatabaseWriter
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/Migrations.md>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ extension Player {
|
||||
|
||||
/// Make Player a Codable Record.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#records
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#records>
|
||||
extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
// Define database columns from CodingKeys
|
||||
fileprivate enum Columns {
|
||||
@@ -68,8 +68,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#requests
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
|
||||
@@ -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.8/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.9/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.8/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
|
||||
@@ -68,7 +68,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.8/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.9/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
|
||||
+9
-9
@@ -212,30 +212,30 @@ extension Base: MyDatabaseDecoder {
|
||||
//: **prepared statement**:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: let statement = try db.makeSelectStatement(sql: "SELECT ...")
|
||||
//: let statement = try db.makeStatement(sql: "SELECT ...")
|
||||
//: try Base.fetchCursor(statement) // Cursor of Base
|
||||
//: try Base.fetchAll(statement) // [Base]
|
||||
//: try Base.fetchOne(statement) // Base?
|
||||
//: }
|
||||
|
||||
extension MyDatabaseDecoder {
|
||||
// MARK: - Fetch from SelectStatement
|
||||
// MARK: - Fetch from Prepared Statement
|
||||
|
||||
// SelectStatement, StatementArguments, and RowAdapter are the fundamental
|
||||
// Statement, StatementArguments, and RowAdapter are the fundamental
|
||||
// fetching parameters of GRDB. Make sure to accept them all:
|
||||
static func fetchCursor(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
static func fetchCursor(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
// Turn the cursor of raw rows into a cursor of decoded rows
|
||||
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
|
||||
self.decode(row: $0)
|
||||
}
|
||||
}
|
||||
|
||||
static func fetchAll(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
|
||||
static func fetchAll(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
|
||||
// Turn the cursor into an Array
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
static func fetchOne(_ statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
|
||||
static func fetchOne(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
|
||||
// Consume the first value of the cursor
|
||||
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next()
|
||||
}
|
||||
@@ -243,7 +243,7 @@ extension MyDatabaseDecoder {
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch from prepared statement")
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT * FROM base")
|
||||
let statement = try db.makeStatement(sql: "SELECT * FROM base")
|
||||
let bases = try Base.fetchAll(statement)
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
@@ -422,7 +422,7 @@ protocol ContextFetchableRecord {
|
||||
|
||||
extension ContextFetchableRecord {
|
||||
static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil,
|
||||
context: Context)
|
||||
@@ -454,7 +454,7 @@ protocol FailableFetchableRecord {
|
||||
|
||||
extension FailableFetchableRecord {
|
||||
static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> MapCursor<RowCursor, Self>
|
||||
|
||||
@@ -173,7 +173,7 @@ do {
|
||||
|
||||
> The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension.
|
||||
|
||||
See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for more information about this exception.
|
||||
See https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report for more information about this exception.
|
||||
|
||||
1. If you use SQLCipher, use SQLCipher 4+, and call the [`cipher_plaintext_header_size` pragma](https://www.zetetic.net/sqlcipher/sqlcipher-api/#cipher_plaintext_header_size) from your database preparation function:
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.8.0'
|
||||
s.version = '5.9.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -99,9 +99,9 @@
|
||||
56176C701EACCCC9000F3F2B /* FTS5WrapperTokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */; };
|
||||
56176C7D1EACCD2D000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
|
||||
56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
|
||||
561CFA7823735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */; };
|
||||
561CFA7923735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */; };
|
||||
561CFA7A23735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */; };
|
||||
561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; };
|
||||
561CFA7923735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; };
|
||||
561CFA7A23735016000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */; };
|
||||
561CFA982376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
|
||||
561CFA992376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
|
||||
561CFA9A2376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
|
||||
@@ -129,6 +129,10 @@
|
||||
5623936D1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */; };
|
||||
562393721DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
|
||||
562393761DEE104400A6B01F /* MapCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393711DEE104400A6B01F /* MapCursorTests.swift */; };
|
||||
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
|
||||
56256ED125D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
|
||||
56256ED225D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
|
||||
56256ED325D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
56256EDA25D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
56256EDB25D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
@@ -179,6 +183,9 @@
|
||||
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 */; };
|
||||
563B5336267E2F90009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5335267E2F90009549B5 /* TableTests.swift */; };
|
||||
563B5337267E2F90009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5335267E2F90009549B5 /* TableTests.swift */; };
|
||||
563B5338267E2F90009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5335267E2F90009549B5 /* TableTests.swift */; };
|
||||
563B8F92249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; };
|
||||
563B8F93249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; };
|
||||
563B8F94249E6171007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F91249E6171007A48C9 /* Trace.swift */; };
|
||||
@@ -471,6 +478,10 @@
|
||||
566BE7212342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
|
||||
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
56713FDE2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
56713FDF2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
56713FE02691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
567156181CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */; };
|
||||
56717271261C68E900423B6F /* CaseInsensitiveIdentifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */; };
|
||||
56717272261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */; };
|
||||
@@ -773,7 +784,7 @@
|
||||
56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B601C53C42C005A543B /* FetchableRecord+QueryInterfaceRequestTests.swift */; };
|
||||
56D496691D813086008276D7 /* QueryInterfaceExpressionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B671C53D25E005A543B /* QueryInterfaceExpressionsTests.swift */; };
|
||||
56D4966A1D813086008276D7 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */; };
|
||||
56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; };
|
||||
56D4966B1D81309E008276D7 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; };
|
||||
56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238261B9C74A90082EB20 /* RecordMinimalPrimaryKeyRowIDTests.swift */; };
|
||||
56D4966D1D81309E008276D7 /* RecordMinimalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238271B9C74A90082EB20 /* RecordMinimalPrimaryKeySingleTests.swift */; };
|
||||
56D4966E1D81309E008276D7 /* RecordPrimaryKeyMultipleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238281B9C74A90082EB20 /* RecordPrimaryKeyMultipleTests.swift */; };
|
||||
@@ -901,7 +912,7 @@
|
||||
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 */; };
|
||||
56FF45441D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; };
|
||||
56FF455A1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; };
|
||||
6340BF801E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; };
|
||||
6340BF841E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; };
|
||||
@@ -1019,7 +1030,7 @@
|
||||
AAA4DD0D230F262000C74B15 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B841C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift */; };
|
||||
AAA4DD0E230F262000C74B15 /* RowAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565F03C11CE5D3AA00DE108F /* RowAdapterTests.swift */; };
|
||||
AAA4DD0F230F262000C74B15 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
|
||||
AAA4DD10230F262000C74B15 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; };
|
||||
AAA4DD10230F262000C74B15 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; };
|
||||
AAA4DD11230F262000C74B15 /* RecordPrimaryKeyNoneTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238291B9C74A90082EB20 /* RecordPrimaryKeyNoneTests.swift */; };
|
||||
AAA4DD12230F262000C74B15 /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
|
||||
AAA4DD13230F262000C74B15 /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; };
|
||||
@@ -1279,7 +1290,7 @@
|
||||
561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = "<group>"; };
|
||||
5616AAF0207CD45E00AC3664 /* RequestProtocols.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RequestProtocols.swift; sourceTree = "<group>"; };
|
||||
56172947223533F40006E219 /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = "<group>"; };
|
||||
561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = "<group>"; };
|
||||
561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = "<group>"; };
|
||||
561CFA912376E546000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
|
||||
561CFA9B2376EC86000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
|
||||
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1290,6 +1301,7 @@
|
||||
562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FlattenCursorTests.swift; sourceTree = "<group>"; };
|
||||
562393711DEE104400A6B01F /* MapCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MapCursorTests.swift; sourceTree = "<group>"; };
|
||||
5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
|
||||
56256ECF25D1ACD0008C2BDD /* Table.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
|
||||
56256ED825D1B316008C2BDD /* ForeignKey.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForeignKey.swift; sourceTree = "<group>"; };
|
||||
562756421E963AAC0035B653 /* DatabaseWriterTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseWriterTests.swift; sourceTree = "<group>"; };
|
||||
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1318,6 +1330,7 @@
|
||||
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>"; };
|
||||
563B5335267E2F90009549B5 /* TableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableTests.swift; sourceTree = "<group>"; };
|
||||
563B8F91249E6171007A48C9 /* Trace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = "<group>"; };
|
||||
563B8FA0249E8ACB007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = "<group>"; };
|
||||
563B8FAB24A1CE43007A48C9 /* DatabasePublishers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabasePublishers.swift; sourceTree = "<group>"; };
|
||||
@@ -1422,6 +1435,7 @@
|
||||
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = "<group>"; };
|
||||
566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = "<group>"; };
|
||||
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = "<group>"; };
|
||||
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = "<group>"; };
|
||||
56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CaseInsensitiveIdentifier.swift; sourceTree = "<group>"; };
|
||||
@@ -1605,7 +1619,7 @@
|
||||
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>"; };
|
||||
56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = "<group>"; };
|
||||
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
|
||||
6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = "<group>"; };
|
||||
AAA4DCFE230F1E0600C74B15 /* GRDB.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDB.framework; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
@@ -1725,6 +1739,7 @@
|
||||
5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */,
|
||||
5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */,
|
||||
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */,
|
||||
56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */,
|
||||
5605F1581C672E4000235C62 /* StandardLibrary.swift */,
|
||||
);
|
||||
path = StandardLibrary;
|
||||
@@ -1759,11 +1774,9 @@
|
||||
5665FA322129EEA0004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
|
||||
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
|
||||
566A843F2041914000E50BFD /* MutablePersistableRecordChangesTests.swift */,
|
||||
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */,
|
||||
5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */,
|
||||
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
|
||||
563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */,
|
||||
561CFA7123735015000C8BAA /* MutablePersistableRecordUpdateTests.swift */,
|
||||
563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */,
|
||||
);
|
||||
name = PersistableRecord;
|
||||
@@ -1803,7 +1816,9 @@
|
||||
56176C9C1EACEA8C000F3F2B /* TableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */,
|
||||
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */,
|
||||
561CFA7123735015000C8BAA /* TableRecordUpdateTests.swift */,
|
||||
);
|
||||
name = TableRecord;
|
||||
sourceTree = "<group>";
|
||||
@@ -1873,6 +1888,7 @@
|
||||
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */,
|
||||
566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */,
|
||||
56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */,
|
||||
563B5335267E2F90009549B5 /* TableTests.swift */,
|
||||
5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */,
|
||||
5653EABF20944B1300F46237 /* Association */,
|
||||
);
|
||||
@@ -2060,6 +2076,7 @@
|
||||
56D91AA12205E03700770D8D /* SQLRelation.swift */,
|
||||
568ECA8925D7013000B71526 /* SQLSelection.swift */,
|
||||
568ECB1725D9161500B71526 /* SQLSubquery.swift */,
|
||||
56256ECF25D1ACD0008C2BDD /* Table.swift */,
|
||||
);
|
||||
path = SQL;
|
||||
sourceTree = "<group>";
|
||||
@@ -2867,6 +2884,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
56256ED225D1ACD0008C2BDD /* Table.swift in Sources */,
|
||||
56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
56D51D061EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
565490CE1D5AE252005622CB /* NSNull.swift in Sources */,
|
||||
@@ -2962,6 +2980,7 @@
|
||||
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */,
|
||||
56F5ABD91D814330001F60CB /* Data.swift in Sources */,
|
||||
565490D41D5AE252005622CB /* (null) in Sources */,
|
||||
56713FDF2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
565490B61D5AE236005622CB /* Configuration.swift in Sources */,
|
||||
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */,
|
||||
@@ -3019,6 +3038,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECAA025D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56713FDE2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
@@ -3030,6 +3050,7 @@
|
||||
566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
5698AD381DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */,
|
||||
56256ED125D1ACD0008C2BDD /* Table.swift in Sources */,
|
||||
5653EB0A20944C7C00F46237 /* Association.swift in Sources */,
|
||||
56A2387E1B9C75030082EB20 /* Database.swift in Sources */,
|
||||
56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
@@ -3155,7 +3176,7 @@
|
||||
56300B861C54DC95005A543B /* Record+QueryInterfaceRequestTests.swift in Sources */,
|
||||
56F26C1C1CEE3F32007969C4 /* RowAdapterTests.swift in Sources */,
|
||||
56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */,
|
||||
56FF45441D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */,
|
||||
56FF45441D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */,
|
||||
56A238561B9C74A90082EB20 /* RecordPrimaryKeyNoneTests.swift in Sources */,
|
||||
562EA8331F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */,
|
||||
563363BE1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift in Sources */,
|
||||
@@ -3302,7 +3323,7 @@
|
||||
56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
|
||||
5653EAE920944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */,
|
||||
5698ACD21DA8C2620056AF8C /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */,
|
||||
561CFA7923735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
561CFA7923735016000C8BAA /* TableRecordUpdateTests.swift in Sources */,
|
||||
56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */,
|
||||
5653EAE120944B4F00F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
|
||||
5604484A25DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */,
|
||||
@@ -3315,6 +3336,7 @@
|
||||
56677C0E241CD0D00050755D /* ValueObservationRecorder.swift in Sources */,
|
||||
5698ACA21DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
|
||||
56A2385C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
|
||||
563B5337267E2F90009549B5 /* TableTests.swift in Sources */,
|
||||
56A238401B9C74A90082EB20 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
|
||||
564F9C221F069B4E00877A00 /* DatabaseAggregateTests.swift in Sources */,
|
||||
56A8C2481D1918F00096E9D4 /* FoundationUUIDTests.swift in Sources */,
|
||||
@@ -3413,7 +3435,7 @@
|
||||
56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */,
|
||||
56419C6D24A519A2004967E1 /* ValueObservationPublisherTests.swift in Sources */,
|
||||
56D496981D81317B008276D7 /* DatabaseValueTests.swift in Sources */,
|
||||
56D4966B1D81309E008276D7 /* MutablePersistableRecordDeleteTests.swift in Sources */,
|
||||
56D4966B1D81309E008276D7 /* TableRecordDeleteTests.swift in Sources */,
|
||||
563B06F721861D8400B38F35 /* ValueObservationCountTests.swift in Sources */,
|
||||
56DF001B228DDBA300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */,
|
||||
56D4965B1D81304E008276D7 /* FoundationNSDecimalNumberTests.swift in Sources */,
|
||||
@@ -3533,7 +3555,7 @@
|
||||
5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
|
||||
562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */,
|
||||
5653EAE820944B4F00F46237 /* AssociationChainSQLTests.swift in Sources */,
|
||||
561CFA7823735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
561CFA7823735016000C8BAA /* TableRecordUpdateTests.swift in Sources */,
|
||||
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */,
|
||||
5604484925DEEEF7002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */,
|
||||
56D496B61D813434008276D7 /* DatabaseRegionTests.swift in Sources */,
|
||||
@@ -3545,6 +3567,7 @@
|
||||
562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */,
|
||||
56677C0D241CD0D00050755D /* ValueObservationRecorder.swift in Sources */,
|
||||
5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
563B5336267E2F90009549B5 /* TableTests.swift in Sources */,
|
||||
56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */,
|
||||
56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */,
|
||||
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
@@ -3610,6 +3633,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECAA225D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56713FE02691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
AAA4DC77230F1E0600C74B15 /* FetchRequest.swift in Sources */,
|
||||
AAA4DC78230F1E0600C74B15 /* AssociationAggregate.swift in Sources */,
|
||||
AAA4DC79230F1E0600C74B15 /* SchedulingWatchdog.swift in Sources */,
|
||||
@@ -3621,6 +3645,7 @@
|
||||
AAA4DC7F230F1E0600C74B15 /* SQLOperators.swift in Sources */,
|
||||
AAA4DC80230F1E0600C74B15 /* FTS5CustomTokenizer.swift in Sources */,
|
||||
56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */,
|
||||
56256ED325D1ACD0008C2BDD /* Table.swift in Sources */,
|
||||
AAA4DC81230F1E0600C74B15 /* Association.swift in Sources */,
|
||||
AAA4DC82230F1E0600C74B15 /* Database.swift in Sources */,
|
||||
AAA4DC83230F1E0600C74B15 /* FTS3.swift in Sources */,
|
||||
@@ -3746,7 +3771,7 @@
|
||||
AAA4DD0D230F262000C74B15 /* Record+QueryInterfaceRequestTests.swift in Sources */,
|
||||
AAA4DD0E230F262000C74B15 /* RowAdapterTests.swift in Sources */,
|
||||
AAA4DD0F230F262000C74B15 /* DatabaseCursorTests.swift in Sources */,
|
||||
AAA4DD10230F262000C74B15 /* MutablePersistableRecordDeleteTests.swift in Sources */,
|
||||
AAA4DD10230F262000C74B15 /* TableRecordDeleteTests.swift in Sources */,
|
||||
AAA4DD11230F262000C74B15 /* RecordPrimaryKeyNoneTests.swift in Sources */,
|
||||
AAA4DD12230F262000C74B15 /* CompilationSubClassTests.swift in Sources */,
|
||||
AAA4DD13230F262000C74B15 /* DatabaseQueueConcurrencyTests.swift in Sources */,
|
||||
@@ -3893,7 +3918,7 @@
|
||||
AAA4DD8B230F262000C74B15 /* ForeignKeyInfoTests.swift in Sources */,
|
||||
AAA4DD8C230F262000C74B15 /* AssociationChainSQLTests.swift in Sources */,
|
||||
AAA4DD8D230F262000C74B15 /* RecordPrimaryKeyHiddenRowIDTests.swift in Sources */,
|
||||
561CFA7A23735016000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
561CFA7A23735016000C8BAA /* TableRecordUpdateTests.swift in Sources */,
|
||||
AAA4DD8E230F262000C74B15 /* RecordEditedTests.swift in Sources */,
|
||||
AAA4DD8F230F262000C74B15 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
|
||||
5604484B25DEEEF8002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */,
|
||||
@@ -3906,6 +3931,7 @@
|
||||
56677C0F241CD0D00050755D /* ValueObservationRecorder.swift in Sources */,
|
||||
AAA4DD94230F262000C74B15 /* FTS4TableBuilderTests.swift in Sources */,
|
||||
AAA4DD95230F262000C74B15 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */,
|
||||
563B5338267E2F90009549B5 /* TableTests.swift in Sources */,
|
||||
AAA4DD96230F262000C74B15 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
|
||||
AAA4DD97230F262000C74B15 /* DatabaseAggregateTests.swift in Sources */,
|
||||
AAA4DD98230F262000C74B15 /* FoundationUUIDTests.swift in Sources */,
|
||||
@@ -3971,6 +3997,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
@@ -3982,6 +4009,7 @@
|
||||
566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
566B91231FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
|
||||
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */,
|
||||
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */,
|
||||
563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
|
||||
56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
|
||||
5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
|
||||
@@ -9,12 +9,12 @@ public struct Configuration {
|
||||
/// If true, foreign key constraints are checked.
|
||||
///
|
||||
/// Default: true
|
||||
public var foreignKeysEnabled: Bool = true
|
||||
public var foreignKeysEnabled = true
|
||||
|
||||
/// If true, database modifications are disallowed.
|
||||
///
|
||||
/// Default: false
|
||||
public var readonly: Bool = false
|
||||
public var readonly = false
|
||||
|
||||
/// The configuration label.
|
||||
///
|
||||
@@ -91,7 +91,7 @@ public struct Configuration {
|
||||
/// When true, the `Database.suspendNotification` and
|
||||
/// `Database.resumeNotification` suspend and resume the database. Database
|
||||
/// suspension helps avoiding the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
///
|
||||
/// During suspension, all database accesses but reads in WAL mode may throw
|
||||
/// a DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. You can
|
||||
@@ -175,11 +175,11 @@ public struct Configuration {
|
||||
/// never allow leaving a transaction opened at the end of a read access.
|
||||
///
|
||||
/// Default: false
|
||||
public var allowsUnsafeTransactions: Bool = false
|
||||
public var allowsUnsafeTransactions = false
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error. See https://www.sqlite.org/rescode.html#busy
|
||||
/// The behavior in case of SQLITE_BUSY error. See <https://www.sqlite.org/rescode.html#busy>
|
||||
///
|
||||
/// Default: immediateError
|
||||
public var busyMode: Database.BusyMode = .immediateError
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
extension Database {
|
||||
/// A SQLite schema. See https://sqlite.org/lang_naming.html
|
||||
/// A SQLite schema. See <https://sqlite.org/lang_naming.html>
|
||||
enum SchemaIdentifier: Hashable {
|
||||
/// The main database
|
||||
case main
|
||||
@@ -7,7 +7,7 @@ extension Database {
|
||||
/// The temp database
|
||||
case temp
|
||||
|
||||
/// An attached database: https://sqlite.org/lang_attach.html
|
||||
/// An attached database: <https://sqlite.org/lang_attach.html>
|
||||
case attached(String)
|
||||
|
||||
/// The name of the schema in SQL queries
|
||||
@@ -57,8 +57,8 @@ extension Database {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
schemaCache.clear()
|
||||
|
||||
// We also clear updateStatementCache and selectStatementCache despite
|
||||
// the automatic statement recompilation (see https://www.sqlite.org/c3ref/prepare.html)
|
||||
// We also clear statement cache despite the automatic statement
|
||||
// recompilation (see https://www.sqlite.org/c3ref/prepare.html)
|
||||
// because the automatic statement recompilation only happens a
|
||||
// limited number of times.
|
||||
internalStatementCache.clear()
|
||||
@@ -68,7 +68,7 @@ extension Database {
|
||||
/// Clears the database schema cache if the database schema has changed
|
||||
/// since this method was last called.
|
||||
func clearSchemaCacheIfNeeded() throws {
|
||||
let schemaVersion = try Int32.fetchOne(internalCachedSelectStatement(sql: "PRAGMA schema_version"))
|
||||
let schemaVersion = try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))
|
||||
if _lastSchemaVersion != schemaVersion {
|
||||
_lastSchemaVersion = schemaVersion
|
||||
clearSchemaCache()
|
||||
@@ -116,7 +116,7 @@ extension Database {
|
||||
///
|
||||
/// Those are tables whose name begins with `sqlite_` and `pragma_`.
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/fileformat2.html
|
||||
/// For more information, see <https://www.sqlite.org/fileformat2.html>
|
||||
public static func isSQLiteInternalTable(_ tableName: String) -> Bool {
|
||||
// https://www.sqlite.org/fileformat2.html#internal_schema_objects
|
||||
// > The names of internal schema objects always begin with "sqlite_"
|
||||
@@ -131,7 +131,7 @@ extension Database {
|
||||
///
|
||||
/// Those are tables whose name begins with `sqlite_` and `pragma_`.
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/fileformat2.html
|
||||
/// For more information, see <https://www.sqlite.org/fileformat2.html>
|
||||
@available(*, deprecated, message: "Use Database.isSQLiteInternalTable(_:) static method instead.")
|
||||
public func isSQLiteInternalTable(_ tableName: String) -> Bool {
|
||||
Self.isSQLiteInternalTable(tableName)
|
||||
@@ -295,7 +295,7 @@ extension Database {
|
||||
//
|
||||
// TODO: find a way to know if a table is WITHOUT ROWID without
|
||||
// generating an error.
|
||||
_ = try makeSelectStatement(sql: """
|
||||
_ = try makeStatement(sql: """
|
||||
SELECT rowid AS checkWithoutRowidOptimization FROM \(table.quotedDatabaseIdentifier)
|
||||
""")
|
||||
return true
|
||||
@@ -641,7 +641,7 @@ extension Database {
|
||||
/// 1 firstName TEXT 0 0 0
|
||||
/// 2 lastName TEXT 0 0 0
|
||||
///
|
||||
/// See `Database.columns(in:)` and https://www.sqlite.org/pragma.html#pragma_table_info
|
||||
/// See `Database.columns(in:)` and <https://www.sqlite.org/pragma.html#pragma_table_info>
|
||||
public struct ColumnInfo: FetchableRecord {
|
||||
let cid: Int
|
||||
let hidden: Int?
|
||||
@@ -689,8 +689,8 @@ public struct ColumnInfo: FetchableRecord {
|
||||
/// the primary key for columns that are part of the primary key.
|
||||
///
|
||||
/// References:
|
||||
/// - https://sqlite.org/releaselog/3_7_16.html
|
||||
/// - http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html
|
||||
/// - <https://sqlite.org/releaselog/3_7_16.html>
|
||||
/// - <http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html>
|
||||
public let primaryKeyIndex: Int
|
||||
|
||||
/// :nodoc:
|
||||
|
||||
+444
-200
@@ -4,6 +4,62 @@ extension Database {
|
||||
|
||||
// MARK: - Statements
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
public func makeStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try makeStatement(sql: sql)
|
||||
if arguments.isEmpty == false {
|
||||
// Throws if arguments do not match
|
||||
try statement.setArguments(arguments)
|
||||
}
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
@@ -11,19 +67,20 @@ extension Database {
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A SelectStatement.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeSelectStatement(sql: String) throws -> SelectStatement {
|
||||
try makeSelectStatement(sql: sql, prepFlags: 0)
|
||||
@available(*, deprecated, renamed: "makeStatement(sql:)")
|
||||
public func makeSelectStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: An SelectStatement.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// A fatal error is raised otherwise.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try makeSelectStatement(literal: """
|
||||
@@ -38,29 +95,111 @@ extension Database {
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
public func makeSelectStatement(literal sqlLiteral: SQL) throws -> SelectStatement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try makeSelectStatement(sql: sql)
|
||||
if arguments.isEmpty == false {
|
||||
// Crash if arguments do not match
|
||||
statement.arguments = arguments
|
||||
}
|
||||
return statement
|
||||
@available(*, deprecated, renamed: "makeStatement(literal:)")
|
||||
public func makeSelectStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try makeStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
|
||||
/// let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - returns: A SelectStatement.
|
||||
/// SQLite 3.20.0, see <http://www.sqlite.org/c3ref/prepare.html>)
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeSelectStatement(sql: String, prepFlags: Int32) throws -> SelectStatement {
|
||||
try SelectStatement.prepare(self, sql: sql, prepFlags: prepFlags)
|
||||
func makeStatement(sql: String, prepFlags: Int32) throws -> Statement {
|
||||
let statements = SQLStatementCursor(database: self, sql: sql, arguments: nil, prepFlags: prepFlags)
|
||||
guard let statement = try statements.next() else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ERROR,
|
||||
message: "empty statement",
|
||||
sql: sql)
|
||||
}
|
||||
do {
|
||||
guard try statements.next() == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: """
|
||||
Multiple statements found. To execute multiple statements, use \
|
||||
Database.execute(sql:) or Database.allStatements(sql:) instead.
|
||||
""",
|
||||
sql: sql)
|
||||
}
|
||||
} catch {
|
||||
// Something while would not compile was found after the first statement.
|
||||
// Complain about multiple statements anyway.
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: """
|
||||
Multiple statements found. To execute multiple statements, use \
|
||||
Database.execute(sql:) or Database.allStatements(sql:) instead.
|
||||
""",
|
||||
sql: sql)
|
||||
}
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedStatement(sql: String) throws -> Statement {
|
||||
try publicStatementCache.statement(sql)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
public func cachedStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try cachedStatement(sql: sql)
|
||||
if arguments.isEmpty == false {
|
||||
// Throws if arguments do not match
|
||||
try statement.setArguments(arguments)
|
||||
}
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
@@ -73,15 +212,45 @@ extension Database {
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedSelectStatement(sql: String) throws -> SelectStatement {
|
||||
try publicStatementCache.selectStatement(sql)
|
||||
@available(*, deprecated, renamed: "cachedStatement(sql:)")
|
||||
public func cachedSelectStatement(sql: String) throws -> Statement {
|
||||
try cachedStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedSelectStatement(literal: "SELECT COUNT(*) FROM player WHERE score > \(20)")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement)!
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try cachedSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "cachedStatement(literal:)")
|
||||
public func cachedSelectStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try cachedStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedSelectStatement(sql: String) throws -> SelectStatement {
|
||||
try internalStatementCache.selectStatement(sql)
|
||||
func internalCachedStatement(sql: String) throws -> Statement {
|
||||
try internalStatementCache.statement(sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
@@ -93,17 +262,18 @@ extension Database {
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func makeUpdateStatement(sql: String) throws -> UpdateStatement {
|
||||
try makeUpdateStatement(sql: sql, prepFlags: 0)
|
||||
@available(*, deprecated, renamed: "makeStatement(sql:)")
|
||||
public func makeUpdateStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// A fatal error is raised otherwise.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try makeUpdateStatement(literal: """
|
||||
@@ -117,29 +287,9 @@ extension Database {
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?, score = \(10)
|
||||
/// """)
|
||||
public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> UpdateStatement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try makeUpdateStatement(sql: sql)
|
||||
if arguments.isEmpty == false {
|
||||
// Crash if arguments do not match
|
||||
statement.arguments = arguments
|
||||
}
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)", prepFlags: 0)
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeUpdateStatement(sql: String, prepFlags: Int32) throws -> UpdateStatement {
|
||||
try UpdateStatement.prepare(self, sql: sql, prepFlags: prepFlags)
|
||||
@available(*, deprecated, renamed: "makeStatement(literal:)")
|
||||
public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try makeStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
@@ -152,15 +302,120 @@ extension Database {
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
public func cachedUpdateStatement(sql: String) throws -> UpdateStatement {
|
||||
try publicStatementCache.updateStatement(sql)
|
||||
@available(*, deprecated, renamed: "cachedStatement(sql:)")
|
||||
public func cachedUpdateStatement(sql: String) throws -> Statement {
|
||||
try cachedStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedUpdateStatement(sql: String) throws -> UpdateStatement {
|
||||
try internalStatementCache.updateStatement(sql)
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?
|
||||
/// """)
|
||||
/// try cachedUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = \("O'Brien")
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?, score = \(10)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "cachedStatement(sql:)")
|
||||
public func cachedUpdateStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try cachedStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a cursor of all SQL statements separated by semi-colons.
|
||||
///
|
||||
/// let statements = try db.allStatements(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - returns: A cursor of `Statement`
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - precondition: Arguments must be nil, or all arguments must be set.
|
||||
/// The returned cursor will throw an error otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000, 1000])
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000])
|
||||
public func allStatements(sql: String, arguments: StatementArguments? = nil)
|
||||
throws -> SQLStatementCursor
|
||||
{
|
||||
SQLStatementCursor(database: self, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Returns a cursor of all SQL statements separated by semi-colons.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let statements = try db.allStatements(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A cursor of `Statement`
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// The returned cursor will throw an error otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000);
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
public func allStatements(literal sqlLiteral: SQL) throws -> SQLStatementCursor {
|
||||
let context = SQLGenerationContext(self)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
let arguments = context.arguments.isEmpty
|
||||
? nil // builds statements without arguments
|
||||
: context.arguments // force arguments to match
|
||||
return SQLStatementCursor(database: self, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
@@ -205,83 +460,105 @@ extension Database {
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func execute(literal sqlLiteral: SQL) throws {
|
||||
// This method is like sqlite3_exec (https://www.sqlite.org/c3ref/exec.html)
|
||||
// It adds support for arguments, and the tricky part is to consume
|
||||
// arguments as statements are executed.
|
||||
//
|
||||
// This job is performed by StatementArguments.extractBindings(forStatement:allowingRemainingValues:)
|
||||
//
|
||||
// And before we return, we'll check that all arguments were consumed.
|
||||
|
||||
let context = SQLGenerationContext(self)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
var arguments = context.arguments
|
||||
let initialValuesCount = arguments.values.count
|
||||
|
||||
// Build a C string (SQLite wants that), and execute SQL statements one
|
||||
// after the other.
|
||||
try sql.utf8CString.withUnsafeBufferPointer { buffer in
|
||||
guard let sqlStart = buffer.baseAddress else { return }
|
||||
let sqlEnd = sqlStart + buffer.count // past \0
|
||||
var statementStart = sqlStart
|
||||
while statementStart < sqlEnd {
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
let nextStatement: UpdateStatement?
|
||||
|
||||
// Compile
|
||||
do {
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
nextStatement = try withAuthorizer(authorizer) {
|
||||
try UpdateStatement(
|
||||
database: self,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: 0,
|
||||
authorizer: authorizer)
|
||||
}
|
||||
}
|
||||
|
||||
guard let statement = nextStatement else {
|
||||
// End of SQL string
|
||||
break
|
||||
}
|
||||
|
||||
// Extract statement arguments
|
||||
let bindings = try arguments.extractBindings(forStatement: statement, allowingRemainingValues: true)
|
||||
// unsafe is OK because we just extracted the correct number of arguments
|
||||
statement.setUncheckedArguments(StatementArguments(bindings))
|
||||
|
||||
// Execute
|
||||
try statement.execute()
|
||||
|
||||
// Next
|
||||
statementStart = statementEnd!
|
||||
}
|
||||
let statements = try allStatements(literal: sqlLiteral)
|
||||
while let statement = try statements.next() {
|
||||
try statement.execute()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class SQLStatementCursor: Cursor {
|
||||
private let database: Database
|
||||
/// C string
|
||||
private let buffer: UnsafeBufferPointer<CChar>
|
||||
private let prepFlags: CInt
|
||||
private let initialArgumentCount: Int?
|
||||
private let sqlEnd: UnsafePointer<CChar>?
|
||||
private var statementStart: UnsafePointer<CChar>?
|
||||
/// Nil when arguments are set later
|
||||
private var arguments: StatementArguments?
|
||||
|
||||
init(database: Database, sql: String, arguments: StatementArguments?, prepFlags: CInt = 0) {
|
||||
self.database = database
|
||||
self.arguments = arguments
|
||||
self.prepFlags = prepFlags
|
||||
self.initialArgumentCount = arguments?.values.count
|
||||
self.buffer = sql.utf8CString.withUnsafeBufferPointer { buffer in
|
||||
let rawBuffer = UnsafeRawBufferPointer(buffer)
|
||||
let copy = UnsafeMutableRawBufferPointer.allocate(
|
||||
byteCount: rawBuffer.count,
|
||||
alignment: MemoryLayout<CChar>.alignment)
|
||||
copy.copyMemory(from: rawBuffer)
|
||||
return UnsafeBufferPointer(copy.bindMemory(to: CChar.self))
|
||||
}
|
||||
if let sqlStart = buffer.baseAddress {
|
||||
statementStart = sqlStart
|
||||
sqlEnd = sqlStart + buffer.count // past \0
|
||||
} else {
|
||||
statementStart = nil
|
||||
sqlEnd = nil
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
buffer.deallocate()
|
||||
}
|
||||
|
||||
public func next() throws -> Statement? {
|
||||
guard let statementStart = statementStart,
|
||||
let sqlEnd = sqlEnd,
|
||||
statementStart < sqlEnd
|
||||
else {
|
||||
try checkArgumentsAreEmpty()
|
||||
return nil
|
||||
}
|
||||
|
||||
// Check that all arguments were consumed: it is a programmer error to
|
||||
// provide arguments that do not match the statement.
|
||||
if arguments.values.isEmpty == false {
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
let statement = try database.withAuthorizer(authorizer) {
|
||||
try Statement(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: authorizer)
|
||||
}
|
||||
|
||||
self.statementStart = statementEnd!
|
||||
|
||||
if let statement = statement {
|
||||
if arguments != nil {
|
||||
// Extract statement arguments
|
||||
let bindings = try arguments!.extractBindings(forStatement: statement, allowingRemainingValues: true)
|
||||
// unsafe is OK because we just extracted the correct number of arguments
|
||||
statement.setUncheckedArguments(StatementArguments(bindings))
|
||||
}
|
||||
return statement
|
||||
} else {
|
||||
try checkArgumentsAreEmpty()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// Check that all arguments were consumed: it is a programmer error to
|
||||
/// provide arguments that do not match the statements.
|
||||
private func checkArgumentsAreEmpty() throws {
|
||||
if let arguments = arguments,
|
||||
let initialArgumentCount = initialArgumentCount,
|
||||
arguments.values.isEmpty == false
|
||||
{
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: "wrong number of statement arguments: \(initialValuesCount)")
|
||||
message: "wrong number of statement arguments: \(initialArgumentCount)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Database {
|
||||
func executeUpdateStatement(_ statement: UpdateStatement) throws {
|
||||
// Two things must prevent the statement from executing: aborted
|
||||
// transactions, and database suspension.
|
||||
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion.formUnion(statement.databaseRegion)
|
||||
}
|
||||
|
||||
let authorizer = observationBroker.updateStatementWillExecute(statement)
|
||||
func executeStatement(_ statement: Statement) throws {
|
||||
let authorizer = try statementWillExecute(statement)
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
|
||||
var code: Int32 = SQLITE_OK
|
||||
withAuthorizer(authorizer) {
|
||||
while true {
|
||||
@@ -314,40 +591,18 @@ extension Database {
|
||||
// We can now move on further tasks.
|
||||
|
||||
if code == SQLITE_DONE {
|
||||
try updateStatementDidExecute(statement)
|
||||
try statementDidExecute(statement)
|
||||
} else {
|
||||
assert(code != SQLITE_ROW)
|
||||
try updateStatementDidFail(statement)
|
||||
throw DatabaseError(
|
||||
resultCode: code,
|
||||
message: lastErrorMessage,
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
try statementDidFail(statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
|
||||
private func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
try observationBroker.updateStatementDidExecute(statement)
|
||||
}
|
||||
|
||||
private func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
//
|
||||
// So make sure we clear this statement from the cache.
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
|
||||
try observationBroker.updateStatementDidFail(statement)
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
func selectStatementWillExecute(_ statement: SelectStatement) throws {
|
||||
/// Returns the authorizer that should be used during statement execution
|
||||
/// (this allows preventing the truncate optimization when there exists a
|
||||
/// transaction observer for row deletion).
|
||||
@usableFromInline
|
||||
func statementWillExecute(_ statement: Statement) throws -> StatementAuthorizer? {
|
||||
// Two things must prevent the statement from executing: aborted
|
||||
// transactions, and database suspension.
|
||||
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
|
||||
@@ -356,9 +611,24 @@ extension Database {
|
||||
if _isRecordingSelectedRegion {
|
||||
_selectedRegion.formUnion(statement.databaseRegion)
|
||||
}
|
||||
|
||||
return observationBroker.statementWillExecute(statement)
|
||||
}
|
||||
|
||||
func selectStatementDidFail(_ statement: SelectStatement) {
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
/// an empty transaction.
|
||||
@usableFromInline
|
||||
func statementDidExecute(_ statement: Statement) throws {
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
try observationBroker.statementDidExecute(statement)
|
||||
}
|
||||
|
||||
/// Always throws an error
|
||||
@usableFromInline
|
||||
func statementDidFail(_ statement: Statement, withResultCode resultCode: Int32) throws -> Never {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
@@ -366,21 +636,30 @@ extension Database {
|
||||
// So make sure we clear this statement from the cache.
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
|
||||
/// Exposes the user-provided cancelled commit error, if a transaction
|
||||
/// observer has cancelled a transaction.
|
||||
try observationBroker.statementDidFail(statement)
|
||||
|
||||
throw DatabaseError(
|
||||
resultCode: resultCode,
|
||||
message: lastErrorMessage,
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// A thread-unsafe statement cache
|
||||
struct StatementCache {
|
||||
unowned let db: Database
|
||||
private var selectStatements: [String: SelectStatement] = [:]
|
||||
private var updateStatements: [String: UpdateStatement] = [:]
|
||||
private var statements: [String: Statement] = [:]
|
||||
|
||||
init(database: Database) {
|
||||
self.db = database
|
||||
}
|
||||
|
||||
mutating func selectStatement(_ sql: String) throws -> SelectStatement {
|
||||
if let statement = selectStatements[sql] {
|
||||
mutating func statement(_ sql: String) throws -> Statement {
|
||||
if let statement = statements[sql] {
|
||||
return statement
|
||||
}
|
||||
|
||||
@@ -394,61 +673,26 @@ struct StatementCache {
|
||||
// However SQLITE_PREPARE_PERSISTENT was only introduced in
|
||||
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
let statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
let statement = try db.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
#else
|
||||
let statement: SelectStatement
|
||||
let statement: Statement
|
||||
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
|
||||
// SQLite 3.24.0 or more
|
||||
statement = try db.makeSelectStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
statement = try db.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
} else {
|
||||
// SQLite 3.19.3 or less
|
||||
statement = try db.makeSelectStatement(sql: sql)
|
||||
statement = try db.makeStatement(sql: sql)
|
||||
}
|
||||
#endif
|
||||
selectStatements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
|
||||
mutating func updateStatement(_ sql: String) throws -> UpdateStatement {
|
||||
if let statement = updateStatements[sql] {
|
||||
return statement
|
||||
}
|
||||
|
||||
// http://www.sqlite.org/c3ref/c_prepare_persistent.html#sqlitepreparepersistent
|
||||
// > The SQLITE_PREPARE_PERSISTENT flag is a hint to the query
|
||||
// > planner that the prepared statement will be retained for a long
|
||||
// > time and probably reused many times.
|
||||
//
|
||||
// This looks like a perfect match for cached statements.
|
||||
//
|
||||
// However SQLITE_PREPARE_PERSISTENT was only introduced in
|
||||
// SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
let statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
#else
|
||||
let statement: UpdateStatement
|
||||
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
|
||||
// SQLite 3.24.0 or more
|
||||
statement = try db.makeUpdateStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
} else {
|
||||
// SQLite 3.19.3 or less
|
||||
statement = try db.makeUpdateStatement(sql: sql)
|
||||
}
|
||||
#endif
|
||||
updateStatements[sql] = statement
|
||||
statements[sql] = statement
|
||||
return statement
|
||||
}
|
||||
|
||||
mutating func clear() {
|
||||
updateStatements = [:]
|
||||
selectStatements = [:]
|
||||
statements = [:]
|
||||
}
|
||||
|
||||
mutating func remove(_ statement: SelectStatement) {
|
||||
selectStatements.removeFirst { $0.value === statement }
|
||||
}
|
||||
|
||||
mutating func remove(_ statement: UpdateStatement) {
|
||||
updateStatements.removeFirst { $0.value === statement }
|
||||
mutating func remove(_ statement: Statement) {
|
||||
statements.removeFirst { $0.value === statement }
|
||||
}
|
||||
}
|
||||
+40
-49
@@ -33,7 +33,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// The error logging function.
|
||||
///
|
||||
/// Quoting https://www.sqlite.org/errlog.html:
|
||||
/// Quoting <https://www.sqlite.org/errlog.html>:
|
||||
///
|
||||
/// > SQLite can be configured to invoke a callback function containing an
|
||||
/// > error code and a terse error message whenever anomalies occur. This
|
||||
@@ -72,7 +72,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// If no row has ever been inserted using this database connection,
|
||||
/// returns zero.
|
||||
///
|
||||
/// For more detailed information, see https://www.sqlite.org/c3ref/last_insert_rowid.html
|
||||
/// For more detailed information, see <https://www.sqlite.org/c3ref/last_insert_rowid.html>
|
||||
public var lastInsertedRowID: Int64 {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
return sqlite3_last_insert_rowid(sqliteConnection)
|
||||
@@ -81,7 +81,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// The number of rows modified, inserted or deleted by the most recent
|
||||
/// successful INSERT, UPDATE or DELETE statement.
|
||||
///
|
||||
/// For more detailed information, see https://www.sqlite.org/c3ref/changes.html
|
||||
/// For more detailed information, see <https://www.sqlite.org/c3ref/changes.html>
|
||||
public var changesCount: Int {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
return Int(sqlite3_changes(sqliteConnection))
|
||||
@@ -91,7 +91,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// INSERT, UPDATE or DELETE statements since the database connection was
|
||||
/// opened.
|
||||
///
|
||||
/// For more detailed information, see https://www.sqlite.org/c3ref/total_changes.html
|
||||
/// For more detailed information, see <https://www.sqlite.org/c3ref/total_changes.html>
|
||||
public var totalChangesCount: Int {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
return Int(sqlite3_total_changes(sqliteConnection))
|
||||
@@ -162,8 +162,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
|
||||
/// If true, select statement execution is recorded.
|
||||
/// Use recordingSelectedRegion(_:), see `selectStatementWillExecute(_:)`
|
||||
var _isRecordingSelectedRegion: Bool = false
|
||||
/// Use recordingSelectedRegion(_:), see `statementWillExecute(_:)`
|
||||
var _isRecordingSelectedRegion = false
|
||||
var _selectedRegion = DatabaseRegion()
|
||||
|
||||
/// Support for checkForAbortedTransaction()
|
||||
@@ -183,7 +183,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly
|
||||
private var isClosed: Bool = false
|
||||
private var isClosed = false
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
@@ -204,7 +204,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// MARK: - Database Opening
|
||||
|
||||
private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection {
|
||||
// See https://www.sqlite.org/c3ref/open.html
|
||||
// See <https://www.sqlite.org/c3ref/open.html>
|
||||
var sqliteConnection: SQLiteConnection? = nil
|
||||
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
@@ -365,7 +365,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
//
|
||||
// So let's fail early if file is not a database, or encrypted with
|
||||
// another passphrase.
|
||||
try makeSelectStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
try makeStatement(sql: "SELECT * FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
}
|
||||
|
||||
// MARK: - Database Closing
|
||||
@@ -415,7 +415,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// try Player.deleteAll(db, keys: ids)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/limits.html
|
||||
/// See <https://www.sqlite.org/limits.html>
|
||||
/// and `SQLITE_LIMIT_VARIABLE_NUMBER`.
|
||||
public var maximumStatementArgumentCount: Int {
|
||||
Int(sqlite3_limit(sqliteConnection, SQLITE_LIMIT_VARIABLE_NUMBER, -1))
|
||||
@@ -486,7 +486,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
func beginReadOnly() throws {
|
||||
if configuration.readonly { return }
|
||||
if _readOnlyDepth == 0 {
|
||||
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 1").execute()
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 1").execute()
|
||||
}
|
||||
_readOnlyDepth += 1
|
||||
}
|
||||
@@ -495,7 +495,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
if configuration.readonly { return }
|
||||
_readOnlyDepth -= 1
|
||||
if _readOnlyDepth == 0 {
|
||||
try internalCachedUpdateStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -512,7 +512,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
/// Returns a snapshot that must be freed with `sqlite3_snapshot_free`.
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/snapshot.html
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>
|
||||
func takeVersionSnapshot() throws -> UnsafeMutablePointer<sqlite3_snapshot> {
|
||||
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let code = withUnsafeMutablePointer(to: &snapshot) {
|
||||
@@ -592,7 +592,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// // Stop tracing
|
||||
/// db.trace(options: [])
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/trace_v2.html for more information.
|
||||
/// See <https://www.sqlite.org/c3ref/trace_v2.html> for more information.
|
||||
///
|
||||
/// - parameter options: The set of desired event kinds. Defaults to
|
||||
/// `.statement`, which notifies all executed database statements.
|
||||
@@ -700,8 +700,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Runs a WAL checkpoint.
|
||||
///
|
||||
/// See https://www.sqlite.org/wal.html and
|
||||
/// https://www.sqlite.org/c3ref/wal_checkpoint_v2.html for
|
||||
/// See <https://www.sqlite.org/wal.html> and
|
||||
/// <https://www.sqlite.org/c3ref/wal_checkpoint_v2.html> for
|
||||
/// more information.
|
||||
///
|
||||
/// - parameter kind: The checkpoint mode (default passive)
|
||||
@@ -731,7 +731,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Interrupt
|
||||
|
||||
// See https://www.sqlite.org/c3ref/interrupt.html
|
||||
// See <https://www.sqlite.org/c3ref/interrupt.html>
|
||||
func interrupt() {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
@@ -752,7 +752,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Suspends the database. A suspended database prevents database locks in
|
||||
/// order to avoid the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
///
|
||||
/// This method can be called from any thread.
|
||||
///
|
||||
@@ -773,7 +773,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// Interrupt the database because this may trigger an
|
||||
// SQLITE_INTERRUPT error which may itself abort a transaction and
|
||||
// release a lock. See https://www.sqlite.org/c3ref/interrupt.html
|
||||
// release a lock. See <https://www.sqlite.org/c3ref/interrupt.html>
|
||||
interrupt()
|
||||
|
||||
// Now what about the eventual remaining lock? We'll issue a
|
||||
@@ -784,7 +784,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Resumes the database. A resumed database stops preventing database locks
|
||||
/// in order to avoid the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
///
|
||||
/// This method can be called from any thread.
|
||||
///
|
||||
@@ -816,7 +816,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Throws SQLITE_ABORT for suspended databases, if statement would lock
|
||||
/// the database, in order to avoid the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/library/archive/technotes/tn2151/_index.html).
|
||||
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
func checkForSuspensionViolation(from statement: Statement) throws {
|
||||
try $isSuspended.read { isSuspended in
|
||||
guard isSuspended else {
|
||||
@@ -834,9 +834,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return
|
||||
}
|
||||
|
||||
if let updateStatement = statement as? UpdateStatement,
|
||||
updateStatement.releasesDatabaseLock
|
||||
{
|
||||
if statement.releasesDatabaseLock {
|
||||
// Accept statements that release locks:
|
||||
// - COMMIT
|
||||
// - ROLLBACK
|
||||
@@ -910,7 +908,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
@@ -1077,7 +1075,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
///
|
||||
/// - parameter kind: The transaction type (default nil). If nil, the
|
||||
/// transaction type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
|
||||
@@ -1255,7 +1253,7 @@ extension Database {
|
||||
}
|
||||
try usePassphrase(data)
|
||||
}
|
||||
|
||||
|
||||
/// Sets the passphrase used to crypt and decrypt an SQLCipher database.
|
||||
///
|
||||
/// Call this method from `Configuration.prepareDatabase`,
|
||||
@@ -1284,7 +1282,7 @@ extension Database {
|
||||
}
|
||||
try changePassphrase(data)
|
||||
}
|
||||
|
||||
|
||||
/// Changes the passphrase used by an SQLCipher encrypted database.
|
||||
public func changePassphrase(_ passphrase: Data) throws {
|
||||
// FIXME: sqlite3_rekey is discouraged.
|
||||
@@ -1311,7 +1309,7 @@ extension Database {
|
||||
|
||||
// MARK: - Database-Related Types
|
||||
|
||||
/// See BusyMode and https://www.sqlite.org/c3ref/busy_handler.html
|
||||
/// See BusyMode and <https://www.sqlite.org/c3ref/busy_handler.html>
|
||||
public typealias BusyCallback = (_ numberOfTries: Int) -> Bool
|
||||
|
||||
/// When there are several connections to a database, a connection may try
|
||||
@@ -1336,10 +1334,10 @@ extension Database {
|
||||
///
|
||||
/// Relevant SQLite documentation:
|
||||
///
|
||||
/// - https://www.sqlite.org/c3ref/busy_timeout.html
|
||||
/// - https://www.sqlite.org/c3ref/busy_handler.html
|
||||
/// - https://www.sqlite.org/lang_transaction.html
|
||||
/// - https://www.sqlite.org/wal.html
|
||||
/// - <https://www.sqlite.org/c3ref/busy_timeout.html>
|
||||
/// - <https://www.sqlite.org/c3ref/busy_handler.html>
|
||||
/// - <https://www.sqlite.org/lang_transaction.html>
|
||||
/// - <https://www.sqlite.org/wal.html>
|
||||
public enum BusyMode {
|
||||
/// The SQLITE_BUSY error is immediately returned to the connection that
|
||||
/// tries to access the locked database.
|
||||
@@ -1350,7 +1348,7 @@ extension Database {
|
||||
case timeout(TimeInterval)
|
||||
|
||||
/// A custom callback that is called when a database is locked.
|
||||
/// See https://www.sqlite.org/c3ref/busy_handler.html
|
||||
/// See <https://www.sqlite.org/c3ref/busy_handler.html>
|
||||
case callback(BusyCallback)
|
||||
}
|
||||
|
||||
@@ -1371,7 +1369,7 @@ extension Database {
|
||||
|
||||
/// A built-in SQLite collation.
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html#collation
|
||||
/// See <https://www.sqlite.org/datatype3.html#collation>
|
||||
public struct CollationName: RawRepresentable, Hashable {
|
||||
/// :nodoc:
|
||||
public let rawValue: String
|
||||
@@ -1398,7 +1396,7 @@ extension Database {
|
||||
/// t.column("title", .text)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html
|
||||
/// See <https://www.sqlite.org/datatype3.html>
|
||||
public struct ColumnType: RawRepresentable, Hashable {
|
||||
/// :nodoc:
|
||||
public let rawValue: String
|
||||
@@ -1435,7 +1433,7 @@ extension Database {
|
||||
|
||||
/// An SQLite conflict resolution.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_conflict.html.
|
||||
/// See <https://www.sqlite.org/lang_conflict.html>
|
||||
public enum ConflictResolution: String {
|
||||
/// The `ROLLBACK` conflict resolution
|
||||
case rollback = "ROLLBACK"
|
||||
@@ -1455,7 +1453,7 @@ extension Database {
|
||||
|
||||
/// A foreign key action.
|
||||
///
|
||||
/// See https://www.sqlite.org/foreignkeys.html
|
||||
/// See <https://www.sqlite.org/foreignkeys.html>
|
||||
public enum ForeignKeyAction: String {
|
||||
/// The `CASCADE` foreign key action
|
||||
case cascade = "CASCADE"
|
||||
@@ -1477,13 +1475,13 @@ extension Database {
|
||||
public struct TracingOptions: OptionSet {
|
||||
/// The raw "Trace Event Code".
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/c_trace.html
|
||||
/// See <https://www.sqlite.org/c3ref/c_trace.html>
|
||||
public let rawValue: CInt
|
||||
|
||||
/// Creates a `TracingOptions` from a raw "Trace Event Code".
|
||||
///
|
||||
/// See:
|
||||
/// - https://www.sqlite.org/c3ref/c_trace.html
|
||||
/// - <https://www.sqlite.org/c3ref/c_trace.html>
|
||||
/// - `Database.trace(options:_:)`
|
||||
public init(rawValue: CInt) {
|
||||
self.rawValue = rawValue
|
||||
@@ -1584,15 +1582,8 @@ extension Database {
|
||||
/// An event reported by `TracingOptions.statement`.
|
||||
case statement(Statement)
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
/// An event reported by `TracingOptions.profile`.
|
||||
case profile(statement: Statement, duration: TimeInterval)
|
||||
#elseif os(Linux)
|
||||
#else
|
||||
/// An event reported by `TracingOptions.profile`.
|
||||
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
|
||||
case profile(statement: Statement, duration: TimeInterval)
|
||||
#endif
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
@@ -1614,7 +1605,7 @@ extension Database {
|
||||
case rollback
|
||||
}
|
||||
|
||||
/// An SQLite transaction kind. See https://www.sqlite.org/lang_transaction.html
|
||||
/// An SQLite transaction kind. See <https://www.sqlite.org/lang_transaction.html>
|
||||
public enum TransactionKind: String {
|
||||
/// The `DEFERRED` transaction kind
|
||||
case deferred = "DEFERRED"
|
||||
@@ -1626,7 +1617,7 @@ extension Database {
|
||||
case exclusive = "EXCLUSIVE"
|
||||
}
|
||||
|
||||
/// An SQLite threading mode. See https://www.sqlite.org/threadsafe.html.
|
||||
/// An SQLite threading mode. See <https://www.sqlite.org/threadsafe.html>.
|
||||
enum ThreadingMode {
|
||||
case `default`
|
||||
case multiThread
|
||||
|
||||
@@ -51,7 +51,7 @@ extension DatabaseCollation: Hashable {
|
||||
/// Two collations are equal if they share the same name (case insensitive)
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
|
||||
// See https://www.sqlite.org/c3ref/create_collation.html
|
||||
// See <https://www.sqlite.org/c3ref/create_collation.html>
|
||||
return sqlite3_stricmp(lhs.name, rhs.name) == 0
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import Foundation
|
||||
|
||||
/// An SQLite result code.
|
||||
///
|
||||
/// See https://www.sqlite.org/rescode.html
|
||||
/// See <https://www.sqlite.org/rescode.html>
|
||||
public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
/// The raw SQLite result code
|
||||
public let rawValue: CInt
|
||||
@@ -13,7 +13,7 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
}
|
||||
|
||||
/// A result code limited to the least significant 8 bits of the receiver.
|
||||
/// See https://www.sqlite.org/rescode.html for more information.
|
||||
/// See <https://www.sqlite.org/rescode.html> for more information.
|
||||
///
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
@@ -193,7 +193,7 @@ extension ResultCode {
|
||||
public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
|
||||
/// The SQLite error code (see
|
||||
/// https://www.sqlite.org/rescode.html#primary_result_code_list).
|
||||
/// <https://www.sqlite.org/rescode.html#primary_result_code_list>).
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
@@ -203,7 +203,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
///
|
||||
/// This property returns a "primary result code", that is to say the least
|
||||
/// significant 8 bits of any SQLite result code. See
|
||||
/// https://www.sqlite.org/rescode.html for more information.
|
||||
/// <https://www.sqlite.org/rescode.html> for more information.
|
||||
///
|
||||
/// See also `extendedResultCode`.
|
||||
public var resultCode: ResultCode {
|
||||
@@ -211,7 +211,7 @@ public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
}
|
||||
|
||||
/// The SQLite extended error code (see
|
||||
/// https://www.sqlite.org/rescode.html#extended_result_code_list).
|
||||
/// <https://www.sqlite.org/rescode.html#extended_result_code_list>).
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
|
||||
@@ -109,7 +109,7 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
/// Returns an SQL expression that applies the function.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#sql-functions
|
||||
/// See <https://github.com/groue/GRDB.swift/#sql-functions>
|
||||
public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression {
|
||||
switch kind {
|
||||
case .aggregate:
|
||||
@@ -120,7 +120,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See https://sqlite.org/c3ref/create_function.html
|
||||
/// See <https://sqlite.org/c3ref/create_function.html>
|
||||
func install(in db: Database) {
|
||||
// Retain the function definition
|
||||
let definition = kind.definition
|
||||
@@ -147,7 +147,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See https://sqlite.org/c3ref/create_function.html
|
||||
/// See <https://sqlite.org/c3ref/create_function.html>
|
||||
func uninstall(in db: Database) {
|
||||
let code = sqlite3_create_function_v2(
|
||||
db.sqliteConnection,
|
||||
@@ -164,7 +164,7 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
/// The way to compute the result of a function.
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class FunctionDefinition {
|
||||
let compute: (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?
|
||||
init(compute: @escaping (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?) {
|
||||
@@ -174,7 +174,7 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
/// The way to start an aggregate.
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class AggregateDefinition {
|
||||
let makeAggregate: () -> DatabaseAggregate
|
||||
init(makeAggregate: @escaping () -> DatabaseAggregate) {
|
||||
@@ -192,7 +192,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
/// A function kind: an "SQL function" or an "aggregate".
|
||||
/// See http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private enum Kind {
|
||||
/// A regular function: SELECT f(1)
|
||||
case function((Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?)
|
||||
@@ -201,7 +201,7 @@ public final class DatabaseFunction: Hashable {
|
||||
case aggregate(() -> DatabaseAggregate)
|
||||
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var definition: AnyObject {
|
||||
switch self {
|
||||
case .function(let compute):
|
||||
@@ -212,7 +212,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .function = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
@@ -230,7 +230,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
/// Feeds the `xStep` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .aggregate = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
@@ -250,7 +250,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
/// Feeds the `xFinal` parameter of sqlite3_create_function_v2
|
||||
/// http://sqlite.org/capi3ref.html#sqlite3_create_function
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var xFinal: (@convention(c) (OpaquePointer?) -> Void)? {
|
||||
guard case .aggregate = self else { return nil }
|
||||
return { (sqliteContext) in
|
||||
@@ -278,8 +278,8 @@ public final class DatabaseFunction: Hashable {
|
||||
///
|
||||
/// The result must be released when the aggregate concludes.
|
||||
///
|
||||
/// See https://sqlite.org/c3ref/context.html
|
||||
/// See https://sqlite.org/c3ref/aggregate_context.html
|
||||
/// See <https://sqlite.org/c3ref/context.html>
|
||||
/// See <https://sqlite.org/c3ref/aggregate_context.html>
|
||||
private static func unmanagedAggregateContext(_ sqliteContext: OpaquePointer?) -> Unmanaged<AggregateContext> {
|
||||
// > The first time the sqlite3_aggregate_context(C,N) routine is called
|
||||
// > for a particular aggregate function, SQLite allocates N of memory,
|
||||
|
||||
@@ -754,7 +754,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
@@ -1072,7 +1072,7 @@ extension DatabasePool {
|
||||
/// You can create as many snapshots as you need, regardless of the maximum
|
||||
/// number of reader connections in the pool.
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
|
||||
/// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html>
|
||||
public func makeSnapshot() throws -> DatabaseSnapshot {
|
||||
// Sanity check
|
||||
if writer.onValidQueue {
|
||||
|
||||
@@ -361,7 +361,7 @@ extension DatabaseQueue {
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See https://www.sqlite.org/lang_transaction.html
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
|
||||
@@ -20,9 +20,9 @@
|
||||
///
|
||||
/// - `DatabaseRegion(table:)`: the region that covers one database table.
|
||||
///
|
||||
/// - `SelectStatement.databaseRegion`:
|
||||
/// - `Statement.databaseRegion`:
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name, score FROM player")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name, score FROM player")
|
||||
/// let region = statement.databaseRegion
|
||||
///
|
||||
/// - `FetchRequest.databaseRegion(_:)`
|
||||
|
||||
@@ -5,7 +5,7 @@ import Dispatch
|
||||
///
|
||||
/// See DatabasePool.makeSnapshot()
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at https://sqlite.org/isolation.html
|
||||
/// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html>
|
||||
public class DatabaseSnapshot: DatabaseReader {
|
||||
private var serializedDatabase: SerializedDatabase
|
||||
|
||||
@@ -40,7 +40,7 @@ public class DatabaseSnapshot: DatabaseReader {
|
||||
try db.beginTransaction(.deferred)
|
||||
|
||||
// Acquire snapshot isolation
|
||||
try db.internalCachedSelectStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
try db.internalCachedStatement(sql: "SELECT rootpage FROM sqlite_master LIMIT 1").makeCursor().next()
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT
|
||||
// We must expect an error: https://www.sqlite.org/c3ref/snapshot_get.html
|
||||
|
||||
@@ -4,7 +4,7 @@ import Foundation
|
||||
|
||||
/// DatabaseValue is the intermediate type between SQLite and your values.
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html
|
||||
/// See <https://www.sqlite.org/datatype3.html>
|
||||
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLSpecificExpressible {
|
||||
/// The SQLite storage
|
||||
public let storage: Storage
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String?
|
||||
@@ -58,7 +58,7 @@ extension DatabaseValueConvertible {
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
return try decode(fromDatabaseValue: dbValue, context: context())
|
||||
}
|
||||
|
||||
|
||||
@usableFromInline
|
||||
static func decode(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
@@ -71,7 +71,7 @@ extension DatabaseValueConvertible {
|
||||
fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
|
||||
static func decodeIfPresent(
|
||||
fromDatabaseValue dbValue: DatabaseValue,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
@@ -86,7 +86,7 @@ extension DatabaseValueConvertible {
|
||||
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
@@ -103,7 +103,7 @@ extension DatabaseValueConvertible {
|
||||
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self? {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
@@ -130,12 +130,16 @@ extension DatabaseValueConvertible {
|
||||
/// }
|
||||
/// }
|
||||
public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
|
||||
@usableFromInline let _statement: SelectStatement
|
||||
@usableFromInline enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
@usableFromInline let _statement: Statement
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@usableFromInline var _done = false
|
||||
@usableFromInline var _state = _State.idle
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
if let adapter = adapter {
|
||||
@@ -144,13 +148,16 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
}
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
@@ -158,14 +165,28 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor
|
||||
|
||||
@inlinable
|
||||
public func next() throws -> Value? {
|
||||
if _done {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_done = true
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
@@ -174,7 +195,8 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -189,12 +211,16 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor
|
||||
/// }
|
||||
/// }
|
||||
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>: Cursor {
|
||||
@usableFromInline let _statement: SelectStatement
|
||||
@usableFromInline enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
@usableFromInline let _statement: Statement
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@usableFromInline var _done = false
|
||||
@usableFromInline var _state = _State.idle
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
if let adapter = adapter {
|
||||
@@ -203,13 +229,16 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
}
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
@@ -217,14 +246,28 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
|
||||
|
||||
@inlinable
|
||||
public func next() throws -> Value?? {
|
||||
if _done {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_done = true
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
@@ -233,7 +276,8 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -245,7 +289,7 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
|
||||
/// try String.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String]
|
||||
/// try String.fetchOne(db, sql: "SELECT name FROM ...", arguments:...) // String?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try String.fetchCursor(statement, arguments:...) // Cursor of String
|
||||
/// try String.fetchAll(statement, arguments:...) // [String]
|
||||
/// try String.fetchOne(statement, arguments:...) // String
|
||||
@@ -253,11 +297,11 @@ public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>:
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
// MARK: Fetching From Prepared Statement
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
@@ -275,7 +319,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
@@ -285,7 +329,7 @@ extension DatabaseValueConvertible {
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchAll(statement) // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -295,7 +339,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An array.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
@@ -308,7 +352,7 @@ extension DatabaseValueConvertible {
|
||||
/// The result is nil if the query returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let name = try String.fetchOne(statement) // String?
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -318,7 +362,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
@@ -332,7 +376,7 @@ extension DatabaseValueConvertible {
|
||||
extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// Returns a set of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchSet(statement) // Set<String>
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -342,7 +386,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// - returns: A set.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Self>
|
||||
@@ -603,18 +647,18 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
|
||||
/// try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
// MARK: Fetching From Prepared Statement
|
||||
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
@@ -632,7 +676,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
@@ -642,7 +686,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchAll(statement) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -652,7 +696,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
@@ -664,7 +708,7 @@ extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & Hashable {
|
||||
/// Returns a set of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchSet(statement) // Set<String?>
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -674,7 +718,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & Hashable {
|
||||
/// - returns: A set of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
|
||||
@@ -315,11 +315,50 @@ extension DatabaseWriter {
|
||||
/// Rebuilds the database file, repacking it into a minimal amount of
|
||||
/// disk space.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_vacuum.html for more information.
|
||||
/// See <https://www.sqlite.org/lang_vacuum.html> for more information.
|
||||
public func vacuum() throws {
|
||||
try writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
|
||||
// VACUUM INTO was introduced in SQLite 3.27.0:
|
||||
// https://www.sqlite.org/releaselog/3_27_0.html
|
||||
//
|
||||
// Old versions of SQLCipher won't have it, but I don't know how to perform
|
||||
// availability checks that depend on the version of the SQLCipher CocoaPod
|
||||
// chosen by the application. So let's just have the method fail at runtime.
|
||||
//
|
||||
// This method is declared on DatabaseWriter instead of DatabaseReader,
|
||||
// so that it is not available on DatabaseSnaphot. VACUUM INTO is not
|
||||
// available inside the transaction that is kept open by DatabaseSnaphot.
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
/// Databases encrypted with SQLCipher are copied with the same password
|
||||
/// and configuration as the original database.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_vacuum.html#vacuuminto> for more information.
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
public func vacuum(into filePath: String) throws {
|
||||
try writeWithoutTransaction {
|
||||
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
|
||||
}
|
||||
}
|
||||
#else
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
/// See <https://www.sqlite.org/lang_vacuum.html#vacuuminto> for more information.
|
||||
///
|
||||
/// - Parameter filePath: file path for new database
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
|
||||
public func vacuum(into filePath: String) throws {
|
||||
try writeWithoutTransaction {
|
||||
try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath])
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// A write-only observation only uses the serialized writer
|
||||
|
||||
@@ -49,7 +49,7 @@ extension FetchRequest {
|
||||
/// A PreparedRequest is a request that is ready to be executed.
|
||||
public struct PreparedRequest {
|
||||
/// A prepared statement
|
||||
public var statement: SelectStatement
|
||||
public var statement: Statement
|
||||
|
||||
/// An eventual adapter for rows fetched by the select statement
|
||||
public var adapter: RowAdapter?
|
||||
@@ -58,7 +58,7 @@ public struct PreparedRequest {
|
||||
var supplementaryFetch: ((Database, [Row]) throws -> Void)?
|
||||
|
||||
init(
|
||||
statement: SelectStatement,
|
||||
statement: Statement,
|
||||
adapter: RowAdapter?,
|
||||
supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil)
|
||||
{
|
||||
|
||||
+59
-37
@@ -14,7 +14,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection,
|
||||
///
|
||||
/// let rows = try Row.fetchCursor(db, sql: "SELECT ...")
|
||||
/// let players = try Player.fetchAll(db, sql: "SELECT ...")
|
||||
@usableFromInline let statement: SelectStatement?
|
||||
@usableFromInline let statement: Statement?
|
||||
@usableFromInline let sqliteStatement: SQLiteStatement?
|
||||
|
||||
/// The number of columns in the row.
|
||||
@@ -96,7 +96,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection,
|
||||
/// The row is implemented on top of StatementRowImpl, which grants *direct*
|
||||
/// access to the SQLite statement. Iteration of the statement does modify
|
||||
/// the row.
|
||||
init(statement: SelectStatement) {
|
||||
init(statement: Statement) {
|
||||
self.statement = statement
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement)
|
||||
@@ -120,7 +120,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection,
|
||||
/// statement does not modify the row.
|
||||
convenience init(
|
||||
copiedFromSQLiteStatement sqliteStatement: SQLiteStatement,
|
||||
statement: SelectStatement)
|
||||
statement: Statement)
|
||||
{
|
||||
self.init(impl: StatementCopyRowImpl(
|
||||
sqliteStatement: sqliteStatement,
|
||||
@@ -239,7 +239,7 @@ extension Row {
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value? {
|
||||
try! decodeIfPresent(Value.self, atIndex: index)
|
||||
@@ -267,7 +267,7 @@ extension Row {
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
|
||||
try! decode(Value.self, atIndex: index)
|
||||
@@ -318,7 +318,7 @@ extension Row {
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value? {
|
||||
try! decodeIfPresent(Value.self, forKey: columnName)
|
||||
@@ -350,7 +350,7 @@ extension Row {
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
@@ -392,7 +392,7 @@ extension Row {
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inlinable
|
||||
public subscript<Value, Column>(_ column: Column)
|
||||
-> Value?
|
||||
@@ -429,7 +429,7 @@ extension Row {
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inlinable
|
||||
public subscript<Value, Column>(_ column: Column)
|
||||
-> Value
|
||||
@@ -531,7 +531,7 @@ extension Row {
|
||||
/// A fatal error is raised if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support>
|
||||
/// for more information.
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
|
||||
try! decode(Record.self, forKey: scope)
|
||||
@@ -566,7 +566,7 @@ extension Row {
|
||||
/// Nil is returned if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support>
|
||||
/// for more information.
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record? {
|
||||
try! decodeIfPresent(Record.self, forKey: scope)
|
||||
@@ -786,7 +786,7 @@ extension Row {
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inlinable
|
||||
func decodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
@@ -806,7 +806,7 @@ extension Row {
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
@@ -827,7 +827,7 @@ extension Row {
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inlinable
|
||||
func decodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
@@ -851,7 +851,7 @@ extension Row {
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see https://www.sqlite.org/datatype3.html).
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inlinable
|
||||
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
@@ -997,7 +997,7 @@ extension Row {
|
||||
/// Nil is returned if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support>
|
||||
/// for more information.
|
||||
func decodeIfPresent<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
@@ -1039,7 +1039,7 @@ extension Row {
|
||||
/// A fatal error is raised if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#joined-queries-support>
|
||||
/// for more information.
|
||||
func decode<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
@@ -1189,23 +1189,30 @@ extension Row {
|
||||
/// let rows: RowCursor = try Row.fetchCursor(db, sql: "SELECT * FROM player")
|
||||
/// }
|
||||
public final class RowCursor: Cursor {
|
||||
@usableFromInline enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
/// The statement iterated by this cursor
|
||||
public let statement: SelectStatement
|
||||
public let statement: Statement
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline let _row: Row // Reused for performance
|
||||
@usableFromInline var _done = false
|
||||
@usableFromInline var _state = _State.idle
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
self._sqliteStatement = statement.sqliteStatement
|
||||
statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? statement.database.statementDidExecute(statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? statement.reset()
|
||||
@@ -1213,30 +1220,45 @@ public final class RowCursor: Cursor {
|
||||
|
||||
@inlinable
|
||||
public func next() throws -> Row? {
|
||||
if _done {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try statement.database.statementWillExecute(statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_done = true
|
||||
_state = .done
|
||||
try statement.database.statementDidExecute(statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return _row
|
||||
case let code:
|
||||
try statement.didFail(withResultCode: code)
|
||||
_state = .failed
|
||||
try statement.database.statementDidFail(statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Row {
|
||||
|
||||
// MARK: - Fetching From SelectStatement
|
||||
// MARK: - Fetching From Prepared Statement
|
||||
|
||||
/// Returns a cursor over rows fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT ...")
|
||||
/// let rows = try Row.fetchCursor(statement) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row[0]
|
||||
@@ -1264,7 +1286,7 @@ extension Row {
|
||||
/// - returns: A cursor over fetched rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> RowCursor
|
||||
@@ -1274,7 +1296,7 @@ extension Row {
|
||||
|
||||
/// Returns an array of rows fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT ...")
|
||||
/// let rows = try Row.fetchAll(statement)
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -1284,7 +1306,7 @@ extension Row {
|
||||
/// - returns: An array of rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Row]
|
||||
@@ -1295,7 +1317,7 @@ extension Row {
|
||||
|
||||
/// Returns a set of rows fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT ...")
|
||||
/// let rows = try Row.fetchSet(statement)
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -1305,7 +1327,7 @@ extension Row {
|
||||
/// - returns: A set of rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Row>
|
||||
@@ -1316,7 +1338,7 @@ extension Row {
|
||||
|
||||
/// Returns a single row fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT ...")
|
||||
/// let row = try Row.fetchOne(statement)
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -1326,7 +1348,7 @@ extension Row {
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Row?
|
||||
@@ -2225,11 +2247,11 @@ private struct StatementCopyRowImpl: RowImpl {
|
||||
|
||||
/// See Row.init(statement:)
|
||||
private struct StatementRowImpl: RowImpl {
|
||||
let statement: SelectStatement
|
||||
let statement: Statement
|
||||
let sqliteStatement: SQLiteStatement
|
||||
let lowercaseColumnIndexes: [String: Int]
|
||||
|
||||
init(sqliteStatement: SQLiteStatement, statement: SelectStatement) {
|
||||
init(sqliteStatement: SQLiteStatement, statement: Statement) {
|
||||
self.statement = statement
|
||||
self.sqliteStatement = sqliteStatement
|
||||
// Optimize row[columnName]
|
||||
|
||||
@@ -141,7 +141,7 @@ public protocol _RowLayout {
|
||||
func _layoutIndex(ofColumn name: String) -> Int?
|
||||
}
|
||||
|
||||
extension SelectStatement: _RowLayout {
|
||||
extension Statement: _RowLayout {
|
||||
/// :nodoc:
|
||||
public var _layoutColumns: [(Int, String)] {
|
||||
Array(columnNames.enumerated())
|
||||
|
||||
@@ -92,7 +92,7 @@ enum RowDecodingError: Error {
|
||||
@usableFromInline
|
||||
static func valueMismatch(
|
||||
_ type: Any.Type,
|
||||
statement: SelectStatement,
|
||||
statement: Statement,
|
||||
index: Int)
|
||||
-> Self
|
||||
{
|
||||
@@ -149,7 +149,7 @@ struct RowDecodingContext {
|
||||
|
||||
/// Convenience initializer
|
||||
@usableFromInline
|
||||
init(statement: SelectStatement, index: Int) {
|
||||
init(statement: Statement, index: Int) {
|
||||
self.key = .columnIndex(index)
|
||||
self.row = Row(copiedFromSQLiteStatement: statement.sqliteStatement, statement: statement)
|
||||
self.sql = statement.sql
|
||||
@@ -171,7 +171,7 @@ extension RowDecodingError: CustomStringConvertible {
|
||||
let columnName = row.columnNames[rowIndex]
|
||||
chunks.append("column: \(String(reflecting: columnName))")
|
||||
chunks.append("column index: \(columnIndex)")
|
||||
|
||||
|
||||
case let .columnName(columnName):
|
||||
if let columnIndex = row.index(forColumn: columnName) {
|
||||
chunks.append("column: \(String(reflecting: columnName))")
|
||||
|
||||
@@ -155,14 +155,14 @@ extension SQLRequest: FetchRequest {
|
||||
{
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
let statement: SelectStatement
|
||||
let statement: Statement
|
||||
switch cache {
|
||||
case .none:
|
||||
statement = try db.makeSelectStatement(sql: sql)
|
||||
statement = try db.makeStatement(sql: sql)
|
||||
case .public?:
|
||||
statement = try db.cachedSelectStatement(sql: sql)
|
||||
statement = try db.cachedStatement(sql: sql)
|
||||
case .internal?:
|
||||
statement = try db.internalCachedSelectStatement(sql: sql)
|
||||
statement = try db.internalCachedStatement(sql: sql)
|
||||
}
|
||||
try statement.setArguments(context.arguments)
|
||||
return PreparedRequest(statement: statement, adapter: adapter)
|
||||
|
||||
@@ -6,7 +6,7 @@ import Dispatch
|
||||
///
|
||||
/// Generally speaking, each connection has its own dispatch queue. But it's not
|
||||
/// enough: users need to use two database connections at the same time:
|
||||
/// https://github.com/groue/GRDB.swift/issues/55. To support this use case, a
|
||||
/// <https://github.com/groue/GRDB.swift/issues/55>. To support this use case, a
|
||||
/// single dispatch queue can be temporarily shared by two or more connections.
|
||||
///
|
||||
/// - SchedulingWatchdog.makeSerializedQueue(allowingDatabase:) creates a
|
||||
|
||||
+85
-191
@@ -9,10 +9,15 @@ extension CharacterSet {
|
||||
}
|
||||
|
||||
/// A statement represents an SQL query.
|
||||
///
|
||||
/// It is the base class of UpdateStatement that executes *update statements*,
|
||||
/// and SelectStatement that fetches rows.
|
||||
public class Statement {
|
||||
public final class Statement {
|
||||
enum TransactionEffect {
|
||||
case beginTransaction
|
||||
case commitTransaction
|
||||
case rollbackTransaction
|
||||
case beginSavepoint(String)
|
||||
case releaseSavepoint(String)
|
||||
case rollbackSavepoint(String)
|
||||
}
|
||||
|
||||
/// The raw SQLite statement, suitable for the SQLite C API.
|
||||
public let sqliteStatement: SQLiteStatement
|
||||
@@ -26,20 +31,43 @@ public class Statement {
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
}
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public lazy var columnNames: [String] = {
|
||||
let sqliteStatement = self.sqliteStatement
|
||||
return (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
|
||||
// Database region is computed during statement compilation, and maybe
|
||||
// extended for select statements compiled by QueryInterfaceRequest, in
|
||||
// order to perform focused database observation. See
|
||||
// SQLQueryGenerator.makeSelectStatement(_:)
|
||||
// SQLQueryGenerator.makeStatement(_:)
|
||||
/// The database region that the statement looks into.
|
||||
public internal(set) var databaseRegion = DatabaseRegion()
|
||||
|
||||
var isReadonly: Bool {
|
||||
/// If true, the database schema cache gets invalidated after this statement
|
||||
/// is executed.
|
||||
private(set) var invalidatesDatabaseSchemaCache = false
|
||||
private(set) var transactionEffect: TransactionEffect?
|
||||
private(set) var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// Returns true if and only if the prepared statement makes no direct
|
||||
/// changes to the content of the database file.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/stmt_readonly.html>.
|
||||
public var isReadonly: Bool {
|
||||
sqlite3_stmt_readonly(sqliteStatement) != 0
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
unowned let database: Database
|
||||
|
||||
/// Cache for index(ofColumn:). Keys are lowercase.
|
||||
private lazy var columnIndexes: [String: Int] = {
|
||||
Dictionary(
|
||||
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}()
|
||||
|
||||
/// Creates a prepared statement. Returns nil if the compiled string is
|
||||
/// blank or empty.
|
||||
///
|
||||
@@ -49,7 +77,7 @@ public class Statement {
|
||||
/// - parameter statementEnd: Upon success, the pointer to the next
|
||||
/// statement in the C string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// SQLite 3.20.0, see <http://www.sqlite.org/c3ref/prepare.html>)
|
||||
/// - parameter authorizer: A StatementCompilationAuthorizer
|
||||
/// - throws: DatabaseError in case of compilation error.
|
||||
required init?(
|
||||
@@ -92,6 +120,9 @@ public class Statement {
|
||||
self.database = database
|
||||
self.sqliteStatement = statement
|
||||
self.databaseRegion = authorizer.selectedRegion
|
||||
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
|
||||
self.transactionEffect = authorizer.transactionEffect
|
||||
self.databaseEventKinds = authorizer.databaseEventKinds
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -115,7 +146,7 @@ public class Statement {
|
||||
|
||||
@usableFromInline
|
||||
var _arguments = StatementArguments()
|
||||
|
||||
|
||||
lazy var sqliteArgumentCount: Int = {
|
||||
Int(sqlite3_bind_parameter_count(self.sqliteStatement))
|
||||
}()
|
||||
@@ -264,117 +295,26 @@ public class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "Statement")
|
||||
public typealias SelectStatement = Statement
|
||||
|
||||
@available(*, deprecated, renamed: "Statement")
|
||||
public typealias UpdateStatement = Statement
|
||||
|
||||
extension Statement: CustomStringConvertible {
|
||||
public var description: String {
|
||||
"SQL: \(sql), Arguments: \(arguments)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Statement Preparation
|
||||
// MARK: - Select Statements
|
||||
|
||||
extension Statement {
|
||||
// Static method instead of an initializer because initializer can't run
|
||||
// inside `sqlCodeUnits.withUnsafeBufferPointer`.
|
||||
static func prepare(_ db: Database, sql: String, prepFlags: Int32) throws -> Self {
|
||||
let authorizer = StatementCompilationAuthorizer()
|
||||
return try db.withAuthorizer(authorizer) {
|
||||
try sql.utf8CString.withUnsafeBufferPointer { buffer in
|
||||
let statementStart = buffer.baseAddress!
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
guard let statement = try self.init(
|
||||
database: db,
|
||||
statementStart: statementStart,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: authorizer) else
|
||||
{
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_ERROR,
|
||||
message: "empty statement",
|
||||
sql: sql)
|
||||
}
|
||||
|
||||
let remainingSQL = String(cString: statementEnd!).trimmingCharacters(in: .sqlStatementSeparators)
|
||||
guard remainingSQL.isEmpty else {
|
||||
throw DatabaseError(
|
||||
resultCode: .SQLITE_MISUSE,
|
||||
message: """
|
||||
Multiple statements found. To execute multiple statements, \
|
||||
use Database.execute(sql:) instead.
|
||||
""",
|
||||
sql: sql)
|
||||
}
|
||||
|
||||
return statement
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SelectStatement
|
||||
|
||||
/// A subclass of Statement that fetches database rows.
|
||||
///
|
||||
/// You create SelectStatement with the Database.makeSelectStatement() method:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
/// }
|
||||
public final class SelectStatement: Statement {
|
||||
/// Creates a prepared statement. Returns nil if the compiled string is
|
||||
/// blank or empty.
|
||||
///
|
||||
/// - parameter database: A database connection.
|
||||
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
|
||||
/// containing SQL.
|
||||
/// - parameter statementEnd: Upon success, the pointer to the next
|
||||
/// statement in the C string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - parameter authorizer: A StatementCompilationAuthorizer
|
||||
/// - throws: DatabaseError in case of compilation error.
|
||||
required init?(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: authorizer)
|
||||
|
||||
GRDBPrecondition(
|
||||
authorizer.invalidatesDatabaseSchemaCache == false,
|
||||
"Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
GRDBPrecondition(
|
||||
authorizer.transactionEffect == nil,
|
||||
"Invalid statement type for query \(String(reflecting: sql)): use UpdateStatement instead.")
|
||||
}
|
||||
|
||||
/// The number of columns in the resulting rows.
|
||||
public var columnCount: Int {
|
||||
Int(sqlite3_column_count(self.sqliteStatement))
|
||||
}
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public lazy var columnNames: [String] = {
|
||||
let sqliteStatement = self.sqliteStatement
|
||||
return (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
|
||||
/// Cache for index(ofColumn:). Keys are lowercase.
|
||||
private lazy var columnIndexes: [String: Int] = {
|
||||
Dictionary(
|
||||
self.columnNames.enumerated().map { ($0.element.lowercased(), $0.offset) },
|
||||
uniquingKeysWith: { (left, _) in left }) // keep leftmost indexes
|
||||
}()
|
||||
|
||||
/// Returns the index of the leftmost column named `name`, in a
|
||||
/// case-insensitive way.
|
||||
public func index(ofColumn name: String) -> Int? {
|
||||
@@ -387,17 +327,6 @@ public final class SelectStatement: Statement {
|
||||
func makeCursor(arguments: StatementArguments? = nil) throws -> StatementCursor {
|
||||
try StatementCursor(statement: self, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Utility function for cursors
|
||||
@usableFromInline
|
||||
func didFail(withResultCode resultCode: Int32) throws -> Never {
|
||||
database.selectStatementDidFail(self)
|
||||
throw DatabaseError(
|
||||
resultCode: resultCode,
|
||||
message: database.lastErrorMessage,
|
||||
sql: sql,
|
||||
arguments: arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor that iterates a database statement without producing any value.
|
||||
@@ -406,26 +335,33 @@ public final class SelectStatement: Statement {
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let statement = db.makeSelectStatement(sql: "SELECT performSideEffect()")
|
||||
/// let statement = db.makeStatement(sql: "SELECT performSideEffect()")
|
||||
/// let cursor = statement.makeCursor()
|
||||
/// try cursor.next()
|
||||
/// }
|
||||
final class StatementCursor: Cursor {
|
||||
let _statement: SelectStatement
|
||||
let _sqliteStatement: SQLiteStatement
|
||||
var _done = false
|
||||
@usableFromInline enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
// Use SelectStatement.makeCursor() instead
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil) throws {
|
||||
let _statement: Statement
|
||||
let _sqliteStatement: SQLiteStatement
|
||||
var _state = _State.idle
|
||||
|
||||
// Use Statement.makeCursor() instead
|
||||
init(statement: Statement, arguments: StatementArguments? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
@@ -434,53 +370,41 @@ final class StatementCursor: Cursor {
|
||||
/// :nodoc:
|
||||
@inlinable
|
||||
func next() throws -> Void? {
|
||||
if _done {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_done = true
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return .some(())
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Update Statements
|
||||
|
||||
// MARK: - UpdateStatement
|
||||
|
||||
/// A subclass of Statement that executes SQL queries.
|
||||
///
|
||||
/// You create UpdateStatement with the Database.makeUpdateStatement() method:
|
||||
///
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// return .commit
|
||||
/// }
|
||||
public final class UpdateStatement: Statement {
|
||||
enum TransactionEffect {
|
||||
case beginTransaction
|
||||
case commitTransaction
|
||||
case rollbackTransaction
|
||||
case beginSavepoint(String)
|
||||
case releaseSavepoint(String)
|
||||
case rollbackSavepoint(String)
|
||||
}
|
||||
|
||||
/// If true, the database schema cache gets invalidated after this statement
|
||||
/// is executed.
|
||||
private(set) var invalidatesDatabaseSchemaCache: Bool = false
|
||||
|
||||
private(set) var transactionEffect: TransactionEffect?
|
||||
private(set) var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
extension Statement {
|
||||
var releasesDatabaseLock: Bool {
|
||||
guard let transactionEffect = transactionEffect else {
|
||||
return false
|
||||
@@ -500,37 +424,7 @@ public final class UpdateStatement: Statement {
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a prepared statement. Returns nil if the compiled string is
|
||||
/// blank or empty.
|
||||
///
|
||||
/// - parameter database: A database connection.
|
||||
/// - parameter statementStart: A pointer to a UTF-8 encoded C string
|
||||
/// containing SQL.
|
||||
/// - parameter statementEnd: Upon success, the pointer to the next
|
||||
/// statement in the C string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see http://www.sqlite.org/c3ref/prepare.html)
|
||||
/// - parameter authorizer: A StatementCompilationAuthorizer
|
||||
/// - throws: DatabaseError in case of compilation error.
|
||||
required init?(
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32,
|
||||
authorizer: StatementCompilationAuthorizer) throws
|
||||
{
|
||||
try super.init(
|
||||
database: database,
|
||||
statementStart: statementStart,
|
||||
statementEnd: statementEnd,
|
||||
prepFlags: prepFlags,
|
||||
authorizer: authorizer)
|
||||
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
|
||||
self.transactionEffect = authorizer.transactionEffect
|
||||
self.databaseEventKinds = authorizer.databaseEventKinds
|
||||
}
|
||||
|
||||
/// Executes the SQL query.
|
||||
/// Executes the prepared statement.
|
||||
///
|
||||
/// - parameter arguments: Optional statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
@@ -541,7 +435,7 @@ public final class UpdateStatement: Statement {
|
||||
// Statement does not know how to execute itself, because it does not
|
||||
// know how to handle its errors, or if truncate optimisation should be
|
||||
// prevented or not. Database knows.
|
||||
try database.executeUpdateStatement(self)
|
||||
try database.executeStatement(self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -561,7 +455,7 @@ public protocol StatementBinding {
|
||||
/// StatementArguments provide values to argument placeholders in raw
|
||||
/// SQL queries.
|
||||
///
|
||||
/// Placeholders can take several forms (see https://www.sqlite.org/lang_expr.html#varparam
|
||||
/// Placeholders can take several forms (see <https://www.sqlite.org/lang_expr.html#varparam>
|
||||
/// for more information):
|
||||
///
|
||||
/// - `?NNN` (e.g. `?2`): the NNN-th argument (starts at 1)
|
||||
|
||||
@@ -3,6 +3,7 @@ import Glibc
|
||||
#endif
|
||||
|
||||
/// A protocol around sqlite3_set_authorizer
|
||||
@usableFromInline
|
||||
protocol StatementAuthorizer: AnyObject {
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
@@ -28,7 +29,7 @@ final class StatementCompilationAuthorizer: StatementAuthorizer {
|
||||
|
||||
/// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or
|
||||
/// savepoint statement.
|
||||
var transactionEffect: UpdateStatement.TransactionEffect?
|
||||
var transactionEffect: Statement.TransactionEffect?
|
||||
|
||||
private var isDropStatement = false
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/// The `StatementColumnConvertible` protocol grants access to the low-level C
|
||||
/// interface that extracts values from query results:
|
||||
/// https://www.sqlite.org/c3ref/column_blob.html. It can bring performance
|
||||
/// <https://www.sqlite.org/c3ref/column_blob.html>. It can bring performance
|
||||
/// improvements.
|
||||
///
|
||||
/// To use it, have a value type adopt both `StatementColumnConvertible` and
|
||||
@@ -34,7 +34,7 @@ public protocol StatementColumnConvertible {
|
||||
/// `nil` for failed conversions: GRDB will interpret a nil result as a
|
||||
/// decoding failure.
|
||||
///
|
||||
/// See https://www.sqlite.org/c3ref/column_blob.html for more information.
|
||||
/// See <https://www.sqlite.org/c3ref/column_blob.html> for more information.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
@@ -63,7 +63,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
static func fastDecode(
|
||||
fromRow row: Row,
|
||||
@@ -79,7 +79,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecode(Self.self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
@@ -99,7 +99,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(
|
||||
fromRow row: Row,
|
||||
@@ -129,12 +129,16 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// }
|
||||
/// }
|
||||
public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & StatementColumnConvertible> : Cursor {
|
||||
@usableFromInline let _statement: SelectStatement
|
||||
@usableFromInline enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
@usableFromInline let _statement: Statement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline var _done = false
|
||||
@usableFromInline var _state = _State.idle
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
if let adapter = adapter {
|
||||
@@ -143,13 +147,16 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
}
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
@@ -157,14 +164,28 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
|
||||
|
||||
@inlinable
|
||||
public func next() throws -> Value? {
|
||||
if _done {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_done = true
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
@@ -173,7 +194,8 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -191,12 +213,16 @@ public final class FastDatabaseValueCursor<Value: DatabaseValueConvertible & Sta
|
||||
public final class FastNullableDatabaseValueCursor<Value>: Cursor
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
@usableFromInline let _statement: SelectStatement
|
||||
@usableFromInline enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
@usableFromInline let _statement: Statement
|
||||
@usableFromInline let _columnIndex: Int32
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline var _done = false
|
||||
@usableFromInline var _state = _State.idle
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
if let adapter = adapter {
|
||||
@@ -205,13 +231,16 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
} else {
|
||||
_columnIndex = 0
|
||||
}
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
@@ -219,14 +248,28 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
|
||||
@inlinable
|
||||
public func next() throws -> Value?? {
|
||||
if _done {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_done = true
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
@@ -235,7 +278,8 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
atUncheckedIndex: _columnIndex,
|
||||
context: RowDecodingContext(statement: _statement, index: Int(_columnIndex)))
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -247,11 +291,11 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
/// See DatabaseValueConvertible for more information.
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
// MARK: Fetching From Prepared Statement
|
||||
|
||||
/// Returns a cursor over values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchCursor(statement) // Cursor of String
|
||||
/// while let name = try names.next() { // String
|
||||
/// ...
|
||||
@@ -269,7 +313,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
@@ -279,7 +323,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns an array of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchAll(statement) // [String]
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -289,7 +333,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
@@ -299,7 +343,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
/// Returns a single value fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let name = try String.fetchOne(statement) // String?
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -309,7 +353,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
@@ -326,7 +370,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hashable {
|
||||
/// Returns a set of values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try String.fetchSet(statement) // Set<String>
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -336,7 +380,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Self>
|
||||
@@ -593,18 +637,18 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
// MARK: Fetching From Prepared Statement
|
||||
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
@@ -622,7 +666,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
@@ -632,7 +676,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchAll(statement) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -642,7 +686,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
@@ -654,7 +698,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable {
|
||||
/// Returns a set of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT name FROM ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchSet(statement) // Set<String?>
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -664,7 +708,7 @@ extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConv
|
||||
/// - returns: A set of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
|
||||
@@ -26,7 +26,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
return data
|
||||
case .string(let string):
|
||||
// Implicit conversion from string to blob, just as SQLite does
|
||||
// See https://www.sqlite.org/c3ref/column_blob.html
|
||||
// See <https://www.sqlite.org/c3ref/column_blob.html>
|
||||
return string.data(using: .utf8)
|
||||
default:
|
||||
return nil
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import Foundation
|
||||
|
||||
private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
|
||||
let dbValue: DatabaseValue
|
||||
let codingPath: [CodingKey]
|
||||
@@ -155,15 +157,13 @@ private struct DatabaseValueDecoder: Decoder {
|
||||
var userInfo: [CodingUserInfoKey: Any] { [:] }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
|
||||
throw DecodingError.typeMismatch(
|
||||
type,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "keyed decoding is not supported"))
|
||||
// We need to switch to JSON decoding
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
|
||||
throw DecodingError.typeMismatch(
|
||||
UnkeyedDecodingContainer.self,
|
||||
DecodingError.Context(codingPath: codingPath, debugDescription: "unkeyed decoding is not supported"))
|
||||
// We need to switch to JSON decoding
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
|
||||
func singleValueContainer() throws -> SingleValueDecodingContainer {
|
||||
@@ -173,7 +173,20 @@ private struct DatabaseValueDecoder: Decoder {
|
||||
|
||||
extension DatabaseValueConvertible where Self: Decodable {
|
||||
public static func fromDatabaseValue(_ databaseValue: DatabaseValue) -> Self? {
|
||||
try? self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
|
||||
do {
|
||||
return try self.init(from: DatabaseValueDecoder(dbValue: databaseValue, codingPath: []))
|
||||
} catch is JSONRequiredError {
|
||||
guard let data = Data.fromDatabaseValue(databaseValue) else {
|
||||
return nil
|
||||
}
|
||||
let decoder = JSONDecoder()
|
||||
decoder.dataDecodingStrategy = .base64
|
||||
decoder.dateDecodingStrategy = .millisecondsSince1970
|
||||
decoder.nonConformingFloatDecodingStrategy = .throw
|
||||
return try? decoder.decode(Self.self, from: data)
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import Foundation
|
||||
|
||||
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
|
||||
@@ -40,13 +42,18 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
|
||||
// This allows us to encode Date as String, for example.
|
||||
encode(dbValueConvertible.databaseValue)
|
||||
} else {
|
||||
try value.encode(to: DatabaseValueEncoder(encode: encode))
|
||||
try DatabaseValueEncoder(encode: encode).encode(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct DatabaseValueEncoder: Encoder {
|
||||
private class DatabaseValueEncoder: Encoder {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
var requiresJSON = false
|
||||
|
||||
init(encode: @escaping (DatabaseValue) -> Void) {
|
||||
self.encode = encode
|
||||
}
|
||||
|
||||
/// The path of coding keys taken to get to this point in encoding.
|
||||
/// A `nil` value indicates an unkeyed container.
|
||||
@@ -63,7 +70,14 @@ private struct DatabaseValueEncoder: Encoder {
|
||||
/// - precondition: May not be called after a value has been encoded through
|
||||
/// a previous `self.singleValueContainer()` call.
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> {
|
||||
fatalError("keyed encoding is not supported")
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
// Unfortunately (bis), we can't throw right from here, so let's
|
||||
// return a JSONRequiredEncoder that will throw as soon as possible.
|
||||
requiresJSON = true
|
||||
let container = JSONRequiredEncoder.KeyedContainer<Key>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding multiple unkeyed values.
|
||||
@@ -73,7 +87,13 @@ private struct DatabaseValueEncoder: Encoder {
|
||||
/// - precondition: May not be called after a value has been encoded through
|
||||
/// a previous `self.singleValueContainer()` call.
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
fatalError("unkeyed encoding is not supported")
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
// Unfortunately (bis), we can't throw right from here, so let's
|
||||
// return a JSONRequiredEncoder that will throw as soon as possible.
|
||||
requiresJSON = true
|
||||
return JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
/// Returns an encoding container appropriate for holding a single primitive value.
|
||||
@@ -86,13 +106,41 @@ private struct DatabaseValueEncoder: Encoder {
|
||||
func singleValueContainer() -> SingleValueEncodingContainer {
|
||||
DatabaseValueEncodingContainer(encode: encode)
|
||||
}
|
||||
|
||||
func encode<T: Encodable>(_ value: T) throws {
|
||||
do {
|
||||
try value.encode(to: self)
|
||||
if requiresJSON {
|
||||
// Here we handle empty arrays and dictionaries.
|
||||
throw JSONRequiredError()
|
||||
}
|
||||
} catch is JSONRequiredError {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.dataEncodingStrategy = .base64
|
||||
encoder.dateEncodingStrategy = .millisecondsSince1970
|
||||
encoder.nonConformingFloatEncodingStrategy = .throw
|
||||
if #available(watchOS 4.0, OSX 10.13, iOS 11.0, tvOS 11.0, *) {
|
||||
// guarantee some stability in order to ease value comparison
|
||||
encoder.outputFormatting = .sortedKeys
|
||||
}
|
||||
let jsonData = try encoder.encode(value)
|
||||
|
||||
// Store JSON String in the database for easier debugging and
|
||||
// database inspection. Thanks to SQLite weak typing, we won't
|
||||
// have any trouble decoding this string into data when we
|
||||
// eventually perform JSON decoding.
|
||||
// TODO: possible optimization: avoid this conversion to string,
|
||||
// and store raw data bytes as an SQLite string
|
||||
let jsonString = String(data: jsonData, encoding: .utf8)!
|
||||
try jsonString.encode(to: self)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible where Self: Encodable {
|
||||
public var databaseValue: DatabaseValue {
|
||||
var dbValue: DatabaseValue! = nil
|
||||
let encoder = DatabaseValueEncoder(encode: { dbValue = $0 })
|
||||
try! self.encode(to: encoder)
|
||||
try! DatabaseValueEncoder(encode: { dbValue = $0 }).encode(self)
|
||||
return dbValue
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
struct JSONRequiredError: Error { }
|
||||
|
||||
/// The encoder that always ends up with a JSONRequiredError
|
||||
struct JSONRequiredEncoder: Encoder {
|
||||
var codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
|
||||
let container = KeyedContainer<Key>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer { self }
|
||||
|
||||
struct KeyedContainer<KeyType: CodingKey>: KeyedEncodingContainerProtocol {
|
||||
var codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
|
||||
|
||||
// swiftlint:disable comma
|
||||
func encodeNil(forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Bool, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int8, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int16, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int32, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int64, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt8, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt16, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt32, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt64, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode<T>(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() }
|
||||
// swiftlint:enable comma
|
||||
|
||||
func nestedContainer<NestedKey>(
|
||||
keyedBy keyType: NestedKey.Type,
|
||||
forKey key: KeyType)
|
||||
-> KeyedEncodingContainer<NestedKey>
|
||||
where NestedKey: CodingKey
|
||||
{
|
||||
let container = KeyedContainer<NestedKey>(codingPath: codingPath + [key])
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder() -> Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder(forKey key: KeyType) -> Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension JSONRequiredEncoder: SingleValueEncodingContainer {
|
||||
func encodeNil() throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Bool ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int8 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int16 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int32 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int64 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt8 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt16) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt32) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt64) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Float ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Double) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: String) throws { throw JSONRequiredError() }
|
||||
func encode<T>(_ value: T) throws where T: Encodable { throw JSONRequiredError() }
|
||||
}
|
||||
|
||||
extension JSONRequiredEncoder: UnkeyedEncodingContainer {
|
||||
var count: Int { 0 }
|
||||
|
||||
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type)
|
||||
-> KeyedEncodingContainer<NestedKey>
|
||||
where NestedKey: CodingKey
|
||||
{
|
||||
let container = KeyedContainer<NestedKey>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
|
||||
mutating func superEncoder() -> Encoder { self }
|
||||
}
|
||||
@@ -518,7 +518,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data):
|
||||
// Implicit conversion from blob to string, just as SQLite does
|
||||
// See https://www.sqlite.org/c3ref/column_blob.html
|
||||
// See <https://www.sqlite.org/c3ref/column_blob.html>
|
||||
return String(data: data, encoding: .utf8)
|
||||
case .string(let string):
|
||||
return string
|
||||
|
||||
@@ -164,7 +164,7 @@ class DatabaseObservationBroker {
|
||||
private var statementObservations: [StatementObservation] = [] {
|
||||
didSet { observesDatabaseChanges = !statementObservations.isEmpty }
|
||||
}
|
||||
private var observesDatabaseChanges: Bool = false {
|
||||
private var observesDatabaseChanges = false {
|
||||
didSet {
|
||||
if observesDatabaseChanges == oldValue { return }
|
||||
if observesDatabaseChanges {
|
||||
@@ -200,8 +200,9 @@ class DatabaseObservationBroker {
|
||||
|
||||
/// Setups observation of changes that are about to be performed by the
|
||||
/// statement, and returns the authorizer that should be used during
|
||||
/// statement execution.
|
||||
func updateStatementWillExecute(_ statement: UpdateStatement) -> StatementAuthorizer? {
|
||||
/// statement execution (this allows preventing the truncate optimization
|
||||
/// when there exists a transaction observer for row deletion).
|
||||
func statementWillExecute(_ statement: Statement) -> StatementAuthorizer? {
|
||||
// If any observer observes row deletions, we'll have to disable
|
||||
// [truncate optimization](https://www.sqlite.org/lang_delete.html#truncateopt)
|
||||
// so that observers are notified.
|
||||
@@ -285,16 +286,7 @@ 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
|
||||
}
|
||||
transactionState = .none
|
||||
|
||||
if observesRowDeletion {
|
||||
return TruncateOptimizationBlocker()
|
||||
@@ -303,8 +295,10 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
func updateStatementDidFail(_ statement: UpdateStatement) throws {
|
||||
// Undo updateStatementWillExecute
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
/// a transaction.
|
||||
func statementDidFail(_ statement: Statement) throws {
|
||||
// Undo statementWillExecute
|
||||
statementObservations = []
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
|
||||
@@ -327,8 +321,10 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
func updateStatementDidExecute(_ statement: UpdateStatement) throws {
|
||||
// Undo updateStatementWillExecute
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
/// an empty transaction.
|
||||
func statementDidExecute(_ statement: Statement) throws {
|
||||
// Undo statementWillExecute
|
||||
if transactionObservations.isEmpty == false {
|
||||
statementObservations = []
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
@@ -443,7 +439,7 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
// Called from updateStatementDidExecute
|
||||
// Called from statementDidExecute
|
||||
private func databaseDidCommit() {
|
||||
savepointStack.clear()
|
||||
|
||||
@@ -453,7 +449,9 @@ class DatabaseObservationBroker {
|
||||
databaseDidEndTransaction()
|
||||
}
|
||||
|
||||
// Called from updateStatementDidExecute
|
||||
// Called from statementDidExecute
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
/// the empty transaction.
|
||||
private func databaseDidCommitEmptyDeferredTransaction() throws {
|
||||
// A statement that ends a transaction has been executed. But for
|
||||
// SQLite, no transaction at all has started, and sqlite3_commit_hook
|
||||
@@ -496,7 +494,7 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
// Called from updateStatementDidExecute or updateStatementDidFails
|
||||
// Called from statementDidExecute or statementDidFail
|
||||
private func databaseDidRollback(notifyTransactionObservers: Bool) {
|
||||
savepointStack.clear()
|
||||
|
||||
@@ -531,7 +529,7 @@ class DatabaseObservationBroker {
|
||||
//
|
||||
// Normally, notifyBufferedEvents() is called as part of statement
|
||||
// execution, and the current broker has been set in
|
||||
// updateStatementWillExecute(). An assertion should be enough:
|
||||
// statementWillExecute(). An assertion should be enough:
|
||||
//
|
||||
// assert(SchedulingWatchdog.current?.databaseObservationBroker != nil)
|
||||
//
|
||||
@@ -539,10 +537,8 @@ class DatabaseObservationBroker {
|
||||
//
|
||||
// let journalMode = String.fetchOne(db, sql: "PRAGMA journal_mode = wal")
|
||||
//
|
||||
// It runs a SelectStatement, not an UpdateStatement. But this not why
|
||||
// this case is particular. What is unexpected is that it triggers
|
||||
// the commit hook when the "PRAGMA journal_mode = wal" statement is
|
||||
// finalized, long after it has executed:
|
||||
// It triggers the commit hook when the "PRAGMA journal_mode = wal"
|
||||
// statement is finalized, long after it has executed:
|
||||
//
|
||||
// 1. Statement.deinit()
|
||||
// 2. sqlite3_finalize()
|
||||
@@ -555,7 +551,7 @@ class DatabaseObservationBroker {
|
||||
// journal mode would trigger the commit hook in sqlite3_step(),
|
||||
// not in sqlite3_finalize().
|
||||
//
|
||||
// Anyway: in this scenario, updateStatementWillExecute() has not been
|
||||
// Anyway: in this scenario, statementWillExecute() has not been
|
||||
// called, and the current broker is nil.
|
||||
//
|
||||
// Let's not try to outsmart SQLite, and build a complex state machine.
|
||||
@@ -590,7 +586,7 @@ class DatabaseObservationBroker {
|
||||
do {
|
||||
try broker.databaseWillCommit()
|
||||
broker.transactionState = .commit
|
||||
// Next step: updateStatementDidExecute()
|
||||
// Next step: statementDidExecute()
|
||||
return 0
|
||||
} catch {
|
||||
broker.transactionState = .cancelledCommit(error)
|
||||
@@ -603,11 +599,11 @@ class DatabaseObservationBroker {
|
||||
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
|
||||
switch broker.transactionState {
|
||||
case .cancelledCommit:
|
||||
// Next step: updateStatementDidFail()
|
||||
// Next step: statementDidFail()
|
||||
break
|
||||
default:
|
||||
broker.transactionState = .rollback
|
||||
// Next step: updateStatementDidExecute()
|
||||
// Next step: statementDidExecute()
|
||||
}
|
||||
}, brokerPointer)
|
||||
}
|
||||
@@ -741,7 +737,7 @@ public protocol TransactionObserver: AnyObject {
|
||||
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
|
||||
/// does not have this enabled, so you'll need to compile your own
|
||||
/// version of SQLite:
|
||||
/// See https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/CustomSQLiteBuilds.md>
|
||||
///
|
||||
/// The databaseDidChangeWithEvent callback is always available,
|
||||
/// and may provide most/all of what you need.
|
||||
@@ -800,7 +796,7 @@ final class TransactionObservation {
|
||||
|
||||
// A disabled observation is not interested in individual database changes.
|
||||
// It is still interested in transactions commits & rollbacks.
|
||||
var isDisabled: Bool = false
|
||||
var isDisabled = false
|
||||
|
||||
private weak var weakObserver: TransactionObserver?
|
||||
private var strongObserver: TransactionObserver?
|
||||
@@ -1350,7 +1346,7 @@ enum DatabaseEventPredicate {
|
||||
// MARK: - SavepointStack
|
||||
|
||||
/// The SQLite savepoint stack is described at
|
||||
/// https://www.sqlite.org/lang_savepoint.html
|
||||
/// <https://www.sqlite.org/lang_savepoint.html>
|
||||
///
|
||||
/// This class reimplements the SQLite stack, so that we can:
|
||||
///
|
||||
|
||||
+10
-2
@@ -8,7 +8,7 @@ public struct FTS3: VirtualTableModule {
|
||||
/// Options for Latin script characters. Matches the raw "remove_diacritics"
|
||||
/// tokenizer argument.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html
|
||||
/// See <https://www.sqlite.org/fts3.html>
|
||||
public enum Diacritics {
|
||||
/// Do not remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=0" tokenizer argument.
|
||||
@@ -45,10 +45,18 @@ public struct FTS3: VirtualTableModule {
|
||||
/// The virtual table module name
|
||||
public let moduleName = "fts3"
|
||||
|
||||
// TODO: remove when `makeTableDefinition()` is no longer a requirement
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition() -> FTS3TableDefinition {
|
||||
preconditionFailure()
|
||||
}
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS3TableDefinition {
|
||||
FTS3TableDefinition()
|
||||
}
|
||||
|
||||
@@ -93,7 +101,7 @@ public final class FTS3TableDefinition {
|
||||
/// try db.create(virtualTable: "document", using: FTS3()) { t in
|
||||
/// t.tokenizer = .porter
|
||||
/// }
|
||||
/// See https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables
|
||||
/// See <https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables>
|
||||
public var tokenizer: FTS3TokenizerDescriptor?
|
||||
|
||||
/// Appends a table column.
|
||||
|
||||
@@ -7,7 +7,7 @@ public struct FTS3Pattern {
|
||||
/// Creates a pattern from a raw pattern string; throws DatabaseError on
|
||||
/// invalid syntax.
|
||||
///
|
||||
/// The pattern syntax is documented at https://www.sqlite.org/fts3.html#full_text_index_queries
|
||||
/// The pattern syntax is documented at <https://www.sqlite.org/fts3.html#full_text_index_queries>
|
||||
///
|
||||
/// try FTS3Pattern(rawPattern: "and") // OK
|
||||
/// try FTS3Pattern(rawPattern: "AND") // malformed MATCH expression: [AND]
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
/// t.tokenizer = .simple // FTS3TokenizerDescriptor
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#tokenizer
|
||||
/// See <https://www.sqlite.org/fts3.html#tokenizer>
|
||||
public struct FTS3TokenizerDescriptor {
|
||||
let name: String
|
||||
let arguments: [String]
|
||||
@@ -20,7 +20,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
/// t.tokenizer = .simple
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#tokenizer
|
||||
/// See <https://www.sqlite.org/fts3.html#tokenizer>
|
||||
public static let simple = FTS3TokenizerDescriptor("simple")
|
||||
|
||||
/// The "porter" tokenizer.
|
||||
@@ -29,7 +29,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
/// t.tokenizer = .porter
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#tokenizer
|
||||
/// See <https://www.sqlite.org/fts3.html#tokenizer>
|
||||
public static let porter = FTS3TokenizerDescriptor("porter")
|
||||
|
||||
/// The "unicode61" tokenizer.
|
||||
@@ -46,7 +46,7 @@ public struct FTS3TokenizerDescriptor {
|
||||
/// - tokenCharacters: Unless empty (the default), SQLite will consider
|
||||
/// these characters as token characters.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#tokenizer
|
||||
/// See <https://www.sqlite.org/fts3.html#tokenizer>
|
||||
public static func unicode61(
|
||||
diacritics: FTS3.Diacritics = .removeLegacy,
|
||||
separators: Set<Character> = [],
|
||||
|
||||
+37
-18
@@ -5,7 +5,7 @@
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html
|
||||
/// See <https://www.sqlite.org/fts3.html>
|
||||
public struct FTS4: VirtualTableModule {
|
||||
|
||||
/// Creates a FTS4 module suitable for the Database
|
||||
@@ -16,7 +16,7 @@ public struct FTS4: VirtualTableModule {
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html
|
||||
/// See <https://www.sqlite.org/fts3.html>
|
||||
public init() {
|
||||
}
|
||||
|
||||
@@ -25,11 +25,19 @@ public struct FTS4: VirtualTableModule {
|
||||
/// The virtual table module name
|
||||
public let moduleName = "fts4"
|
||||
|
||||
// TODO: remove when `makeTableDefinition()` is no longer a requirement
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition() -> FTS4TableDefinition {
|
||||
FTS4TableDefinition()
|
||||
preconditionFailure()
|
||||
}
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS4TableDefinition {
|
||||
FTS4TableDefinition(configuration: configuration)
|
||||
}
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
@@ -113,20 +121,26 @@ public struct FTS4: VirtualTableModule {
|
||||
|
||||
let oldRowID = "old.\(rowIDColumn.quotedDatabaseIdentifier)"
|
||||
|
||||
let ifNotExists = definition.configuration.ifNotExists
|
||||
? "IF NOT EXISTS "
|
||||
: ""
|
||||
|
||||
// swiftlint:disable line_length
|
||||
try db.execute(sql: """
|
||||
CREATE TRIGGER \("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
|
||||
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_bu".quotedDatabaseIdentifier) BEFORE UPDATE ON \(content) BEGIN
|
||||
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
|
||||
END;
|
||||
CREATE TRIGGER \("__\(tableName)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN
|
||||
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_bd".quotedDatabaseIdentifier) BEFORE DELETE ON \(content) BEGIN
|
||||
DELETE FROM \(ftsTable) WHERE docid=\(oldRowID);
|
||||
END;
|
||||
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
|
||||
END;
|
||||
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES(\(newContentColumns));
|
||||
END;
|
||||
""")
|
||||
// swiftlint:enable line_length
|
||||
|
||||
// https://www.sqlite.org/fts3.html#*fts4rebuidcmd
|
||||
|
||||
@@ -144,13 +158,14 @@ public struct FTS4: VirtualTableModule {
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html
|
||||
/// See <https://www.sqlite.org/fts3.html>
|
||||
public final class FTS4TableDefinition {
|
||||
enum ContentMode {
|
||||
case raw(content: String?)
|
||||
case synchronized(contentTable: String)
|
||||
}
|
||||
|
||||
fileprivate let configuration: VirtualTableConfiguration
|
||||
fileprivate var columns: [FTS4ColumnDefinition] = []
|
||||
fileprivate var contentMode: ContentMode = .raw(content: nil)
|
||||
|
||||
@@ -160,7 +175,7 @@ public final class FTS4TableDefinition {
|
||||
/// t.tokenizer = .porter
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables
|
||||
/// See <https://www.sqlite.org/fts3.html#creating_and_destroying_fts_tables>
|
||||
public var tokenizer: FTS3TokenizerDescriptor?
|
||||
|
||||
/// The FTS4 `content` option
|
||||
@@ -172,7 +187,7 @@ public final class FTS4TableDefinition {
|
||||
/// Setting this property invalidates any synchronization previously
|
||||
/// established with the `synchronize(withTable:)` method.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_content_option_
|
||||
/// See <https://www.sqlite.org/fts3.html#the_content_option_>
|
||||
public var content: String? {
|
||||
get {
|
||||
switch contentMode {
|
||||
@@ -189,17 +204,17 @@ public final class FTS4TableDefinition {
|
||||
|
||||
/// The FTS4 `compress` option
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options
|
||||
/// See <https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options>
|
||||
public var compress: String?
|
||||
|
||||
/// The FTS4 `uncompress` option
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options
|
||||
/// See <https://www.sqlite.org/fts3.html#the_compress_and_uncompress_options>
|
||||
public var uncompress: String?
|
||||
|
||||
/// The FTS4 `matchinfo` option
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_matchinfo_option
|
||||
/// See <https://www.sqlite.org/fts3.html#the_matchinfo_option>
|
||||
public var matchinfo: String?
|
||||
|
||||
/// Support for the FTS5 `prefix` option
|
||||
@@ -210,9 +225,13 @@ public final class FTS4TableDefinition {
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_prefix_option
|
||||
/// See <https://www.sqlite.org/fts3.html#the_prefix_option>
|
||||
public var prefixes: Set<Int>?
|
||||
|
||||
init(configuration: VirtualTableConfiguration) {
|
||||
self.configuration = configuration
|
||||
}
|
||||
|
||||
/// Appends a table column.
|
||||
///
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
@@ -234,7 +253,7 @@ public final class FTS4TableDefinition {
|
||||
/// content in the external table. SQL triggers make sure that the
|
||||
/// full-text table is kept up to date with the external table.
|
||||
///
|
||||
/// See https://sqlite.org/fts5.html#external_content_tables
|
||||
/// See <https://sqlite.org/fts5.html#external_content_tables>
|
||||
public func synchronize(withTable tableName: String) {
|
||||
contentMode = .synchronized(contentTable: tableName)
|
||||
}
|
||||
@@ -249,7 +268,7 @@ public final class FTS4TableDefinition {
|
||||
/// t.column("content") // FTS4ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html
|
||||
/// See <https://www.sqlite.org/fts3.html>
|
||||
public final class FTS4ColumnDefinition {
|
||||
fileprivate let name: String
|
||||
fileprivate var isIndexed: Bool
|
||||
@@ -268,7 +287,7 @@ public final class FTS4ColumnDefinition {
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_notindexed_option
|
||||
/// See <https://www.sqlite.org/fts3.html#the_notindexed_option>
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
@@ -284,7 +303,7 @@ public final class FTS4ColumnDefinition {
|
||||
/// t.column("lid").asLanguageId()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts3.html#the_languageid_option
|
||||
/// See <https://www.sqlite.org/fts3.html#the_languageid_option>
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
|
||||
+39
-18
@@ -8,12 +8,12 @@ import Foundation
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html
|
||||
/// See <https://www.sqlite.org/fts5.html>
|
||||
public struct FTS5: VirtualTableModule {
|
||||
/// Options for Latin script characters. Matches the raw "remove_diacritics"
|
||||
/// tokenizer argument.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html
|
||||
/// See <https://www.sqlite.org/fts5.html>
|
||||
public enum Diacritics {
|
||||
/// Do not remove diacritics from Latin script characters. This
|
||||
/// option matches the raw "remove_diacritics=0" tokenizer argument.
|
||||
@@ -43,7 +43,7 @@ public struct FTS5: VirtualTableModule {
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html
|
||||
/// See <https://www.sqlite.org/fts5.html>
|
||||
public init() {
|
||||
}
|
||||
|
||||
@@ -52,9 +52,19 @@ public struct FTS5: VirtualTableModule {
|
||||
/// The virtual table module name
|
||||
public let moduleName = "fts5"
|
||||
|
||||
/// Don't use this method.
|
||||
// TODO: remove when `makeTableDefinition()` is no longer a requirement
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition() -> FTS5TableDefinition {
|
||||
FTS5TableDefinition()
|
||||
preconditionFailure()
|
||||
}
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS5TableDefinition {
|
||||
FTS5TableDefinition(configuration: configuration)
|
||||
}
|
||||
|
||||
/// Don't use this method.
|
||||
@@ -150,18 +160,24 @@ public struct FTS5: VirtualTableModule {
|
||||
.map { "old.\($0.quotedDatabaseIdentifier)" }
|
||||
.joined(separator: ", ")
|
||||
|
||||
let ifNotExists = definition.configuration.ifNotExists
|
||||
? "IF NOT EXISTS "
|
||||
: ""
|
||||
|
||||
// swiftlint:disable line_length
|
||||
try db.execute(sql: """
|
||||
CREATE TRIGGER \("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ai".quotedDatabaseIdentifier) AFTER INSERT ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
|
||||
END;
|
||||
CREATE TRIGGER \("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
|
||||
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_ad".quotedDatabaseIdentifier) AFTER DELETE ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
|
||||
END;
|
||||
CREATE TRIGGER \("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
CREATE TRIGGER \(ifNotExists)\("__\(tableName)_au".quotedDatabaseIdentifier) AFTER UPDATE ON \(content) BEGIN
|
||||
INSERT INTO \(ftsTable)(\(ftsTable), \(ftsColumns)) VALUES('delete', \(oldContentColumns));
|
||||
INSERT INTO \(ftsTable)(\(ftsColumns)) VALUES (\(newContentColumns));
|
||||
END;
|
||||
""")
|
||||
// swiftlint:enable line_length
|
||||
|
||||
// https://sqlite.org/fts5.html#the_rebuild_command
|
||||
|
||||
@@ -243,13 +259,14 @@ public struct FTS5: VirtualTableModule {
|
||||
/// t.column("content")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html
|
||||
/// See <https://www.sqlite.org/fts5.html>
|
||||
public final class FTS5TableDefinition {
|
||||
enum ContentMode {
|
||||
case raw(content: String?, contentRowID: String?)
|
||||
case synchronized(contentTable: String)
|
||||
}
|
||||
|
||||
fileprivate let configuration: VirtualTableConfiguration
|
||||
fileprivate var columns: [FTS5ColumnDefinition] = []
|
||||
fileprivate var contentMode: ContentMode = .raw(content: nil, contentRowID: nil)
|
||||
|
||||
@@ -259,7 +276,7 @@ public final class FTS5TableDefinition {
|
||||
/// t.tokenizer = .porter()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization
|
||||
/// See <https://www.sqlite.org/fts5.html#fts5_table_creation_and_initialization>
|
||||
public var tokenizer: FTS5TokenizerDescriptor?
|
||||
|
||||
/// The FTS5 `content` option
|
||||
@@ -271,7 +288,7 @@ public final class FTS5TableDefinition {
|
||||
/// Setting this property invalidates any synchronization previously
|
||||
/// established with the `synchronize(withTable:)` method.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html#external_content_and_contentless_tables
|
||||
/// See <https://www.sqlite.org/fts5.html#external_content_and_contentless_tables>
|
||||
public var content: String? {
|
||||
get {
|
||||
switch contentMode {
|
||||
@@ -300,7 +317,7 @@ public final class FTS5TableDefinition {
|
||||
/// Setting this property invalidates any synchronization previously
|
||||
/// established with the `synchronize(withTable:)` method.
|
||||
///
|
||||
/// See https://sqlite.org/fts5.html#external_content_tables
|
||||
/// See <https://sqlite.org/fts5.html#external_content_tables>
|
||||
public var contentRowID: String? {
|
||||
get {
|
||||
switch contentMode {
|
||||
@@ -322,19 +339,23 @@ public final class FTS5TableDefinition {
|
||||
|
||||
/// Support for the FTS5 `prefix` option
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html#prefix_indexes
|
||||
/// See <https://www.sqlite.org/fts5.html#prefix_indexes>
|
||||
public var prefixes: Set<Int>?
|
||||
|
||||
/// Support for the FTS5 `columnsize` option
|
||||
///
|
||||
/// https://www.sqlite.org/fts5.html#the_columnsize_option
|
||||
/// <https://www.sqlite.org/fts5.html#the_columnsize_option>
|
||||
public var columnSize: Int?
|
||||
|
||||
/// Support for the FTS5 `detail` option
|
||||
///
|
||||
/// https://www.sqlite.org/fts5.html#the_detail_option
|
||||
/// <https://www.sqlite.org/fts5.html#the_detail_option>
|
||||
public var detail: String?
|
||||
|
||||
init(configuration: VirtualTableConfiguration) {
|
||||
self.configuration = configuration
|
||||
}
|
||||
|
||||
/// Appends a table column.
|
||||
///
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in
|
||||
@@ -356,7 +377,7 @@ public final class FTS5TableDefinition {
|
||||
/// content in the external table. SQL triggers make sure that the
|
||||
/// full-text table is kept up to date with the external table.
|
||||
///
|
||||
/// See https://sqlite.org/fts5.html#external_content_tables
|
||||
/// See <https://sqlite.org/fts5.html#external_content_tables>
|
||||
public func synchronize(withTable tableName: String) {
|
||||
contentMode = .synchronized(contentTable: tableName)
|
||||
}
|
||||
@@ -371,7 +392,7 @@ public final class FTS5TableDefinition {
|
||||
/// t.column("content") // FTS5ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html
|
||||
/// See <https://www.sqlite.org/fts5.html>
|
||||
public final class FTS5ColumnDefinition {
|
||||
fileprivate let name: String
|
||||
fileprivate var isIndexed: Bool
|
||||
@@ -388,7 +409,7 @@ public final class FTS5ColumnDefinition {
|
||||
/// t.column("b").notIndexed()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html#the_unindexed_column_option
|
||||
/// See <https://www.sqlite.org/fts5.html#the_unindexed_column_option>
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
|
||||
@@ -93,7 +93,7 @@ public struct FTS5Pattern {
|
||||
}
|
||||
}
|
||||
}
|
||||
try db.makeSelectStatement(sql: "SELECT * FROM document WHERE document MATCH ?")
|
||||
try db.makeStatement(sql: "SELECT * FROM document WHERE document MATCH ?")
|
||||
.makeCursor(arguments: [rawPattern])
|
||||
.next() // error on next() for invalid patterns
|
||||
}
|
||||
@@ -114,7 +114,7 @@ extension Database {
|
||||
/// Creates a pattern from a raw pattern string; throws DatabaseError on
|
||||
/// invalid syntax.
|
||||
///
|
||||
/// The pattern syntax is documented at https://www.sqlite.org/fts5.html#full_text_query_syntax
|
||||
/// The pattern syntax is documented at <https://www.sqlite.org/fts5.html#full_text_query_syntax>
|
||||
///
|
||||
/// try db.makeFTS5Pattern(rawPattern: "and", forTable: "document") // OK
|
||||
/// try db.makeFTS5Pattern(rawPattern: "AND", forTable: "document") // malformed MATCH expression: [AND]
|
||||
|
||||
@@ -15,7 +15,7 @@ public typealias FTS5TokenCallback = @convention(c) (
|
||||
|
||||
/// The reason why FTS5 is requesting tokenization.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html#custom_tokenizers
|
||||
/// See <https://www.sqlite.org/fts5.html#custom_tokenizers>
|
||||
public struct FTS5Tokenization: OptionSet {
|
||||
public let rawValue: Int32
|
||||
|
||||
@@ -41,7 +41,7 @@ public protocol FTS5Tokenizer: AnyObject {
|
||||
/// Tokenizes the text described by `pText` and `nText`, and
|
||||
/// notifies found tokens to the `tokenCallback` function.
|
||||
///
|
||||
/// It matches the `xTokenize` function documented at https://www.sqlite.org/fts5.html#custom_tokenizers
|
||||
/// It matches the `xTokenize` function documented at <https://www.sqlite.org/fts5.html#custom_tokenizers>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - context: An opaque pointer that is the first argument to
|
||||
@@ -51,7 +51,7 @@ public protocol FTS5Tokenizer: AnyObject {
|
||||
/// nul-terminated.
|
||||
/// - nText: The number of bytes in the tokenized text.
|
||||
/// - tokenCallback: The function to call for each found token.
|
||||
/// It matches the `xToken` callback at https://www.sqlite.org/fts5.html#custom_tokenizers
|
||||
/// It matches the `xToken` callback at <https://www.sqlite.org/fts5.html#custom_tokenizers>
|
||||
func tokenize(
|
||||
context: UnsafeMutableRawPointer?,
|
||||
tokenization: FTS5Tokenization,
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
/// t.tokenizer = .unicode61() // FTS5TokenizerDescriptor
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html#tokenizers
|
||||
/// See <https://www.sqlite.org/fts5.html#tokenizers>
|
||||
public struct FTS5TokenizerDescriptor {
|
||||
/// The tokenizer components
|
||||
///
|
||||
@@ -55,7 +55,7 @@ public struct FTS5TokenizerDescriptor {
|
||||
/// - tokenCharacters: Unless empty (the default), SQLite will
|
||||
/// consider these characters as token characters.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html#ascii_tokenizer
|
||||
/// See <https://www.sqlite.org/fts5.html#ascii_tokenizer>
|
||||
public static func ascii(
|
||||
separators: Set<Character> = [],
|
||||
tokenCharacters: Set<Character> = [])
|
||||
@@ -108,7 +108,7 @@ public struct FTS5TokenizerDescriptor {
|
||||
/// - base: An eventual wrapping tokenizer which replaces the
|
||||
// default unicode61() base tokenizer.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html#porter_tokenizer
|
||||
/// See <https://www.sqlite.org/fts5.html#porter_tokenizer>
|
||||
public static func porter(wrapping base: FTS5TokenizerDescriptor? = nil) -> FTS5TokenizerDescriptor {
|
||||
if let base = base {
|
||||
return FTS5TokenizerDescriptor(components: ["porter"] + base.components)
|
||||
@@ -131,7 +131,7 @@ public struct FTS5TokenizerDescriptor {
|
||||
/// - tokenCharacters: Unless empty (the default), SQLite will
|
||||
/// consider these characters as token characters.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html#unicode61_tokenizer
|
||||
/// See <https://www.sqlite.org/fts5.html#unicode61_tokenizer>
|
||||
public static func unicode61(
|
||||
diacritics: FTS5.Diacritics = .removeLegacy,
|
||||
separators: Set<Character> = [],
|
||||
|
||||
@@ -3,7 +3,7 @@ import Foundation
|
||||
|
||||
/// Flags that tell SQLite how to register a token.
|
||||
///
|
||||
/// See https://www.sqlite.org/fts5.html#custom_tokenizers
|
||||
/// See <https://www.sqlite.org/fts5.html#custom_tokenizers>
|
||||
public struct FTS5TokenFlags: OptionSet {
|
||||
public let rawValue: Int32
|
||||
|
||||
@@ -76,7 +76,7 @@ public protocol FTS5WrapperTokenizer: FTS5CustomTokenizer {
|
||||
/// 2. The input `flags` should be given unmodified to the tokenCallback
|
||||
/// function, unless you union it with the .colocated flag when the
|
||||
/// tokenizer produces synonyms (see
|
||||
/// https://www.sqlite.org/fts5.html#synonym_support).
|
||||
/// <https://www.sqlite.org/fts5.html#synonym_support>).
|
||||
///
|
||||
/// - parameters:
|
||||
/// - token: A token produced by the wrapped tokenizer
|
||||
|
||||
@@ -15,7 +15,7 @@ extension AnyFetchRequest {
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Define your own FetchRequest type instead.")
|
||||
public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?))
|
||||
public init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (Statement, RowAdapter?))
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ extension DatabaseReader {
|
||||
|
||||
extension FetchRequest {
|
||||
@available(*, unavailable, message: "Use makePreparedRequest(_:forSingleResult:) instead.")
|
||||
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
|
||||
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (Statement, RowAdapter?)
|
||||
{ preconditionFailure() }
|
||||
|
||||
@available(*, unavailable, message: "Use ValueObservation.tracking(request.fetchCount) instead")
|
||||
|
||||
@@ -39,7 +39,7 @@ struct Migration {
|
||||
// > schema change did not break any foreign
|
||||
// > key constraints.
|
||||
if try db
|
||||
.makeSelectStatement(sql: "PRAGMA foreign_key_check")
|
||||
.makeStatement(sql: "PRAGMA foreign_key_check")
|
||||
.makeCursor()
|
||||
.isEmpty() == false
|
||||
{
|
||||
|
||||
@@ -4,8 +4,7 @@ import Foundation
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _Association {
|
||||
init(sqlAssociation: _SQLAssociation)
|
||||
var _sqlAssociation: _SQLAssociation { get }
|
||||
var _sqlAssociation: _SQLAssociation { get set }
|
||||
}
|
||||
|
||||
/// The base protocol for all associations that define a connection between two
|
||||
@@ -45,35 +44,57 @@ public protocol Association: _Association, DerivableRequest {
|
||||
}
|
||||
|
||||
extension Association {
|
||||
/// :nodoc:
|
||||
public func _including(all association: _SQLAssociation) -> Self {
|
||||
mapDestinationRelation { $0._including(all: association) }
|
||||
/// Returns self modified with the *update* function.
|
||||
@inline(__always)
|
||||
func with(_ update: (inout Self) throws -> Void) rethrows -> Self {
|
||||
var result = self
|
||||
try update(&result)
|
||||
return result
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _including(optional association: _SQLAssociation) -> Self {
|
||||
mapDestinationRelation { $0._including(optional: association) }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _including(required association: _SQLAssociation) -> Self {
|
||||
mapDestinationRelation { $0._including(required: association) }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _joining(optional association: _SQLAssociation) -> Self {
|
||||
mapDestinationRelation { $0._joining(optional: association) }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _joining(required association: _SQLAssociation) -> Self {
|
||||
mapDestinationRelation { $0._joining(required: association) }
|
||||
/// Returns self with destination relation modified with the *update* function.
|
||||
@inline(__always)
|
||||
fileprivate func withDestinationRelation(_ update: (inout SQLRelation) throws -> Void) rethrows -> Self {
|
||||
var result = self
|
||||
try update(&result._sqlAssociation.destination.relation)
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
extension Association {
|
||||
fileprivate func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self {
|
||||
.init(sqlAssociation: _sqlAssociation.map(\.destination.relation, transform))
|
||||
/// :nodoc:
|
||||
public func _including(all association: _SQLAssociation) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation._including(all: association)
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _including(optional association: _SQLAssociation) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation._including(optional: association)
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _including(required association: _SQLAssociation) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation._including(required: association)
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _joining(optional association: _SQLAssociation) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation._joining(optional: association)
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _joining(required association: _SQLAssociation) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation._joining(required: association)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,11 +180,14 @@ extension Association {
|
||||
/// .including(required: Player.team.aliased(teamAlias))
|
||||
/// .filter(sql: "custom.color = ?", arguments: ["red"])
|
||||
public func aliased(_ alias: TableAlias) -> Self {
|
||||
mapDestinationRelation { $0.aliased(alias) }
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.aliased(alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Association where Self: SelectionRequest {
|
||||
// SelectionRequest conformance
|
||||
extension Association {
|
||||
|
||||
/// Creates an association which selects *selection*.
|
||||
///
|
||||
@@ -187,7 +211,11 @@ extension Association where Self: SelectionRequest {
|
||||
/// .select { db in [Column("color") }
|
||||
/// var request = Player.including(required: association)
|
||||
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
mapDestinationRelation { $0.select { try selection($0).map(\.sqlSelection) } }
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.select { db in
|
||||
try selection(db).map(\.sqlSelection)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an association which appends *selection*.
|
||||
@@ -204,11 +232,16 @@ extension Association where Self: SelectionRequest {
|
||||
/// .annotated(with: { db in [Column("name")] })
|
||||
/// var request = Player.including(required: association)
|
||||
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
|
||||
mapDestinationRelation { $0.annotated { try selection($0).map(\.sqlSelection) } }
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.annotated { db in
|
||||
try selection(db).map(\.sqlSelection)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Association where Self: FilteredRequest {
|
||||
// FilteredRequest conformance
|
||||
extension Association {
|
||||
/// Creates an association with the provided *predicate promise* added to
|
||||
/// the eventual set of already applied predicates.
|
||||
///
|
||||
@@ -222,11 +255,16 @@ extension Association where Self: FilteredRequest {
|
||||
/// let association = Player.team.filter { db in true }
|
||||
/// var request = Player.including(required: association)
|
||||
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
|
||||
mapDestinationRelation { $0.filter { try predicate($0).sqlExpression } }
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.filter { db in
|
||||
try predicate(db).sqlExpression
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Association where Self: OrderedRequest {
|
||||
// OrderedRequest conformance
|
||||
extension Association {
|
||||
/// Creates an association with the provided *orderings promise*.
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
@@ -252,7 +290,11 @@ extension Association where Self: OrderedRequest {
|
||||
/// .order{ _ in [Column("name")] }
|
||||
/// var request = Player.including(required: association)
|
||||
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> Self {
|
||||
mapDestinationRelation { $0.order { try orderings($0).map(\.sqlOrdering) } }
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.order { db in
|
||||
try orderings(db).map(\.sqlOrdering)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an association that reverses applied orderings.
|
||||
@@ -276,7 +318,9 @@ extension Association where Self: OrderedRequest {
|
||||
/// let association = Player.team.reversed()
|
||||
/// var request = Player.including(required: association)
|
||||
public func reversed() -> Self {
|
||||
mapDestinationRelation { $0.reversed() }
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.reversed()
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an association without any ordering.
|
||||
@@ -291,33 +335,48 @@ extension Association where Self: OrderedRequest {
|
||||
/// let association = Player.team.order(Column("name")).unordered()
|
||||
/// var request = Player.including(required: association)
|
||||
public func unordered() -> Self {
|
||||
mapDestinationRelation { $0.unordered() }
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.unordered()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Association where Self: TableRequest {
|
||||
// TableRequest conformance
|
||||
extension Association {
|
||||
public var databaseTableName: String {
|
||||
_sqlAssociation.destination.relation.source.tableName
|
||||
}
|
||||
}
|
||||
|
||||
extension Association where Self: AggregatingRequest {
|
||||
// AggregatingRequest conformance
|
||||
extension Association {
|
||||
/// Creates an association grouped according to *expressions promise*.
|
||||
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self {
|
||||
mapDestinationRelation { $0.group { try expressions($0).map(\.sqlExpression) } }
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.group { db in
|
||||
try expressions(db).map(\.sqlExpression)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an association with the provided *predicate promise* added to
|
||||
/// the eventual set of already applied predicates.
|
||||
public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
|
||||
mapDestinationRelation { $0.having { try predicate($0).sqlExpression } }
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.having { db in
|
||||
try predicate(db).sqlExpression
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Association where Self: DerivableRequest {
|
||||
// DerivableRequest conformance
|
||||
extension Association {
|
||||
/// Creates an association for returns distinct rows.
|
||||
public func distinct() -> Self {
|
||||
mapDestinationRelation { $0.with(\.isDistinct, true) }
|
||||
withDestinationRelation { relation in
|
||||
relation.isDistinct = true
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an association that fetches *limit* rows, starting at *offset*.
|
||||
@@ -329,14 +388,18 @@ extension Association where Self: DerivableRequest {
|
||||
///
|
||||
/// :nodoc:
|
||||
public func limit(_ limit: Int, offset: Int? = nil) -> Self {
|
||||
mapDestinationRelation { $0.with(\.limit, SQLLimit(limit: limit, offset: offset)) }
|
||||
withDestinationRelation { relation in
|
||||
relation.limit = SQLLimit(limit: limit, offset: offset)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an association that embeds the common table expression.
|
||||
///
|
||||
/// See `QueryInterfaceRequest.with(_:)` for more information.
|
||||
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
|
||||
mapDestinationRelation { $0.with(\.ctes[cte.tableName], cte.cte) }
|
||||
withDestinationRelation { relation in
|
||||
relation.ctes[cte.tableName] = cte.cte
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,7 +411,9 @@ public protocol AssociationToOne: Association { }
|
||||
extension AssociationToOne {
|
||||
public func forKey(_ key: String) -> Self {
|
||||
let associationKey = SQLAssociationKey.fixedSingular(key)
|
||||
return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey))
|
||||
return with {
|
||||
$0._sqlAssociation = $0._sqlAssociation.forDestinationKey(associationKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -360,6 +425,8 @@ public protocol AssociationToMany: Association { }
|
||||
extension AssociationToMany {
|
||||
public func forKey(_ key: String) -> Self {
|
||||
let associationKey = SQLAssociationKey.fixedPlural(key)
|
||||
return .init(sqlAssociation: _sqlAssociation.forDestinationKey(associationKey))
|
||||
return with {
|
||||
$0._sqlAssociation = $0._sqlAssociation.forDestinationKey(associationKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,7 @@ extension AssociationToMany {
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db)
|
||||
@available(*, deprecated, message: "Did you mean average(Column(...))? If not, prefer average(value.databaseValue) instead.") // swiftlint:disable:this line_length
|
||||
public func average(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
@@ -72,6 +73,33 @@ extension AssociationToMany {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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: SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression]))
|
||||
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.
|
||||
///
|
||||
@@ -89,6 +117,7 @@ extension AssociationToMany {
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db)
|
||||
@available(*, deprecated, message: "Did you mean max(Column(...))? If not, prefer max(value.databaseValue) instead.") // swiftlint:disable:this line_length
|
||||
public func max(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
@@ -99,6 +128,33 @@ extension AssociationToMany {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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: SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression]))
|
||||
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.
|
||||
///
|
||||
@@ -116,6 +172,7 @@ extension AssociationToMany {
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db)
|
||||
@available(*, deprecated, message: "Did you mean min(Column(...))? If not, prefer min(value.databaseValue) instead.") // swiftlint:disable:this line_length
|
||||
public func min(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
@@ -126,6 +183,33 @@ extension AssociationToMany {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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: SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression]))
|
||||
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.
|
||||
///
|
||||
@@ -143,6 +227,7 @@ extension AssociationToMany {
|
||||
/// let infos: [TeamInfo] = try TeamInfo.fetchAll(db, request)
|
||||
///
|
||||
/// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db)
|
||||
@available(*, deprecated, message: "Did you mean sum(Column(...))? If not, prefer sum(value.databaseValue) instead.") // swiftlint:disable:this line_length
|
||||
public func sum(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
@@ -152,6 +237,33 @@ extension AssociationToMany {
|
||||
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: SQLSpecificExpressible) -> AssociationAggregate<OriginRowDecoder> {
|
||||
let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression]))
|
||||
if let column = expression as? ColumnExpression {
|
||||
let name = key.singularizedName
|
||||
return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum")
|
||||
} else {
|
||||
return aggregate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An AssociationAggregate is able to compute aggregated values from a
|
||||
@@ -232,7 +344,9 @@ extension AssociationAggregate: Refinable {
|
||||
/// let numberOfBooks: Int = row["numberOfBooks"]
|
||||
/// }
|
||||
public func forKey(_ key: String) -> Self {
|
||||
with(\.key, key)
|
||||
with {
|
||||
$0.key = key
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an aggregate that is selected in a column named like the given
|
||||
@@ -976,8 +1090,9 @@ public func ?? <RowDecoder>(
|
||||
rhs: SQLExpressible)
|
||||
-> AssociationAggregate<RowDecoder>
|
||||
{
|
||||
// Preserve key
|
||||
lhs.map { $0 ?? rhs }.with(\.key, lhs.key)
|
||||
lhs
|
||||
.map { $0 ?? rhs }
|
||||
.with { $0.key = lhs.key } // Preserve key
|
||||
}
|
||||
|
||||
// TODO: add support for ABS(aggregate)
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
/// SQLite guarantees that no book refers to a missing author. The
|
||||
/// `onDelete: .cascade` option has SQLite automatically delete all of an
|
||||
/// author's books when that author is deleted.
|
||||
/// See https://sqlite.org/foreignkeys.html#fk_actions for more information.
|
||||
/// See <https://sqlite.org/foreignkeys.html#fk_actions> for more information.
|
||||
///
|
||||
/// The example above uses auto-incremented primary keys. But generally
|
||||
/// speaking, all primary keys are supported.
|
||||
@@ -68,11 +68,6 @@ public struct BelongsToAssociation<Origin, Destination>: AssociationToOne {
|
||||
/// :nodoc:
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
/// :nodoc:
|
||||
public init(sqlAssociation: _SQLAssociation) {
|
||||
self._sqlAssociation = sqlAssociation
|
||||
}
|
||||
|
||||
init(
|
||||
to destinationRelation: SQLRelation,
|
||||
key: String?,
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
/// SQLite guarantees that no book refers to a missing author. The
|
||||
/// `onDelete: .cascade` option has SQLite automatically delete all of an
|
||||
/// author's books when that author is deleted.
|
||||
/// See https://sqlite.org/foreignkeys.html#fk_actions for more information.
|
||||
/// See <https://sqlite.org/foreignkeys.html#fk_actions> for more information.
|
||||
///
|
||||
/// The example above uses auto-incremented primary keys. But generally
|
||||
/// speaking, all primary keys are supported.
|
||||
@@ -68,11 +68,6 @@ public struct HasManyAssociation<Origin, Destination>: AssociationToMany {
|
||||
/// :nodoc:
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
/// :nodoc:
|
||||
public init(sqlAssociation: _SQLAssociation) {
|
||||
self._sqlAssociation = sqlAssociation
|
||||
}
|
||||
|
||||
init(
|
||||
to destinationRelation: SQLRelation,
|
||||
key: String?,
|
||||
|
||||
@@ -50,9 +50,4 @@ public struct HasManyThroughAssociation<Origin, Destination>: AssociationToMany
|
||||
|
||||
/// :nodoc:
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
/// :nodoc:
|
||||
public init(sqlAssociation: _SQLAssociation) {
|
||||
self._sqlAssociation = sqlAssociation
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@
|
||||
/// country.code, so that SQLite guarantees that no profile refers to a
|
||||
/// missing country. The `onDelete: .cascade` option has SQLite automatically
|
||||
/// delete a profile when its country is deleted.
|
||||
/// See https://sqlite.org/foreignkeys.html#fk_actions for more information.
|
||||
/// See <https://sqlite.org/foreignkeys.html#fk_actions> for more information.
|
||||
///
|
||||
/// The example above uses a string primary for the country table. But generally
|
||||
/// speaking, all primary keys are supported.
|
||||
@@ -70,11 +70,6 @@ public struct HasOneAssociation<Origin, Destination>: AssociationToOne {
|
||||
/// :nodoc:
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
/// :nodoc:
|
||||
public init(sqlAssociation: _SQLAssociation) {
|
||||
self._sqlAssociation = sqlAssociation
|
||||
}
|
||||
|
||||
init(
|
||||
to destinationRelation: SQLRelation,
|
||||
key: String?,
|
||||
|
||||
@@ -30,9 +30,4 @@ public struct HasOneThroughAssociation<Origin, Destination>: AssociationToOne {
|
||||
|
||||
/// :nodoc:
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
/// :nodoc:
|
||||
public init(sqlAssociation: _SQLAssociation) {
|
||||
self._sqlAssociation = sqlAssociation
|
||||
}
|
||||
}
|
||||
@@ -10,11 +10,6 @@ public struct JoinAssociation<Origin, Destination>: AssociationToOne {
|
||||
/// :nodoc:
|
||||
public var _sqlAssociation: _SQLAssociation
|
||||
|
||||
/// :nodoc:
|
||||
public init(sqlAssociation: _SQLAssociation) {
|
||||
self._sqlAssociation = sqlAssociation
|
||||
}
|
||||
|
||||
/// Creates a `JoinAssociation` whose key is the table name of the relation.
|
||||
init(
|
||||
to relation: SQLRelation,
|
||||
|
||||
@@ -378,7 +378,8 @@ extension CommonTableExpression {
|
||||
///
|
||||
/// The key of the returned association is the table name of `Destination`.
|
||||
///
|
||||
/// - parameter cte: A common table expression.
|
||||
/// - parameter destination: The record type at the other side of
|
||||
/// the association.
|
||||
/// - parameter condition: A function that returns the joining clause.
|
||||
/// - parameter left: A `TableAlias` for the left table.
|
||||
/// - parameter right: A `TableAlias` for the right table.
|
||||
@@ -399,7 +400,8 @@ extension CommonTableExpression {
|
||||
///
|
||||
/// The key of the returned association is the table name of `Destination`.
|
||||
///
|
||||
/// - parameter cte: A common table expression.
|
||||
/// - parameter destination: The record type at the other side of
|
||||
/// the association.
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to destination: Destination.Type)
|
||||
@@ -408,4 +410,38 @@ extension CommonTableExpression {
|
||||
{
|
||||
JoinAssociation(to: Destination.relationForAll, condition: .none)
|
||||
}
|
||||
|
||||
/// Creates an association to a table that you can join
|
||||
/// or include in another request.
|
||||
///
|
||||
/// The key of the returned association is the table name of `Destination`.
|
||||
///
|
||||
/// - parameter destination: The table at the other side of the association.
|
||||
/// - parameter condition: A function that returns the joining clause.
|
||||
/// - parameter left: A `TableAlias` for the left table.
|
||||
/// - parameter right: A `TableAlias` for the right table.
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to destination: Table<Destination>,
|
||||
on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> SQLExpressible)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
{
|
||||
JoinAssociation(
|
||||
to: destination.relationForAll,
|
||||
condition: .expression { condition($0, $1).sqlExpression })
|
||||
}
|
||||
|
||||
/// Creates an association to a table that you can join
|
||||
/// or include in another request.
|
||||
///
|
||||
/// The key of the returned association is the table name of `Destination`.
|
||||
///
|
||||
/// - parameter destination: The table at the other side of the association.
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to destination: Table<Destination>)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
{
|
||||
JoinAssociation(to: destination.relationForAll, condition: .none)
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@
|
||||
/// let players = try request.fetchAll(db) // [Player]
|
||||
/// }
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
/// See <https://github.com/groue/GRDB.swift#the-query-interface>
|
||||
public struct QueryInterfaceRequest<RowDecoder> {
|
||||
var relation: SQLRelation
|
||||
}
|
||||
@@ -77,7 +77,11 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
/// .select { db in [Column("id")] }
|
||||
/// .select { db in [Column("email")] }
|
||||
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0.select { try selection($0).map(\.sqlSelection) } }
|
||||
with {
|
||||
$0.relation = $0.relation.select { db in
|
||||
try selection(db).map(\.sqlSelection)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a request which selects *selection*, and fetches values of
|
||||
@@ -153,7 +157,52 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
/// .select([Column("id"), Column("email")])
|
||||
/// .annotated(with: { db in [Column("name")] })
|
||||
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0.annotated { try selection($0).map(\.sqlSelection) } }
|
||||
with {
|
||||
$0.relation = $0.relation.annotated { db in
|
||||
try selection(db).map(\.sqlSelection)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
|
||||
extension QueryInterfaceRequest
|
||||
where RowDecoder: Identifiable,
|
||||
RowDecoder.ID: DatabaseValueConvertible
|
||||
{
|
||||
/// Creates a request which selects the primary key.
|
||||
///
|
||||
/// // SELECT id FROM player WHERE ...
|
||||
/// let request = try Player.filter(...).selectID()
|
||||
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID> {
|
||||
select { db in
|
||||
let primaryKey = try db.primaryKey(self.databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
|
||||
return [Column(primaryKey.columns[0])]
|
||||
}.asRequest(of: RowDecoder.ID.self)
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
|
||||
extension QueryInterfaceRequest
|
||||
where RowDecoder: Identifiable,
|
||||
RowDecoder.ID: _OptionalProtocol,
|
||||
RowDecoder.ID.Wrapped: DatabaseValueConvertible
|
||||
{
|
||||
/// Creates a request which selects the primary key.
|
||||
///
|
||||
/// // SELECT id FROM player WHERE ...
|
||||
/// let request = try Player.filter(...).selectID()
|
||||
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID.Wrapped> {
|
||||
select { db in
|
||||
let primaryKey = try db.primaryKey(self.databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
|
||||
return [Column(primaryKey.columns[0])]
|
||||
}.asRequest(of: RowDecoder.ID.Wrapped.self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,7 +214,11 @@ extension QueryInterfaceRequest: FilteredRequest {
|
||||
/// var request = Player.all()
|
||||
/// request = request.filter { db in true }
|
||||
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0.filter { try predicate($0).sqlExpression } }
|
||||
with {
|
||||
$0.relation = $0.relation.filter { db in
|
||||
try predicate(db).sqlExpression
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +237,11 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
/// .reversed()
|
||||
/// .order{ _ in [Column("name")] }
|
||||
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0.order { try orderings($0).map(\.sqlOrdering) } }
|
||||
with {
|
||||
$0.relation = $0.relation.order { db in
|
||||
try orderings(db).map(\.sqlOrdering)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a request that reverses applied orderings.
|
||||
@@ -199,7 +256,9 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
/// var request = Player.all()
|
||||
/// request = request.reversed()
|
||||
public func reversed() -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0.reversed() }
|
||||
with {
|
||||
$0.relation = $0.relation.reversed()
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a request without any ordering.
|
||||
@@ -208,20 +267,30 @@ extension QueryInterfaceRequest: OrderedRequest {
|
||||
/// var request = Player.all().order(Column("name"))
|
||||
/// request = request.unordered()
|
||||
public func unordered() -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0.unordered() }
|
||||
with {
|
||||
$0.relation = $0.relation.unordered()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: AggregatingRequest {
|
||||
/// Creates a request grouped according to *expressions promise*.
|
||||
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0.group { try expressions($0).map(\.sqlExpression) } }
|
||||
with {
|
||||
$0.relation = $0.relation.group { db in
|
||||
try expressions(db).map(\.sqlExpression)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a request with the provided *predicate promise* added to the
|
||||
/// eventual set of already applied predicates.
|
||||
public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0.having { try predicate($0).sqlExpression } }
|
||||
with {
|
||||
$0.relation = $0.relation.having { db in
|
||||
try predicate(db).sqlExpression
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,27 +298,37 @@ extension QueryInterfaceRequest: AggregatingRequest {
|
||||
extension QueryInterfaceRequest: _JoinableRequest {
|
||||
/// :nodoc:
|
||||
public func _including(all association: _SQLAssociation) -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0._including(all: association) }
|
||||
with {
|
||||
$0.relation = $0.relation._including(all: association)
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _including(optional association: _SQLAssociation) -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0._including(optional: association) }
|
||||
with {
|
||||
$0.relation = $0.relation._including(optional: association)
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _including(required association: _SQLAssociation) -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0._including(required: association) }
|
||||
with {
|
||||
$0.relation = $0.relation._including(required: association)
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _joining(optional association: _SQLAssociation) -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0._joining(optional: association) }
|
||||
with {
|
||||
$0.relation = $0.relation._joining(optional: association)
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _joining(required association: _SQLAssociation) -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0._joining(required: association) }
|
||||
with {
|
||||
$0.relation = $0.relation._joining(required: association)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -279,13 +358,17 @@ extension QueryInterfaceRequest: TableRequest {
|
||||
/// .aliased(playerAlias)
|
||||
/// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
|
||||
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest {
|
||||
map(\.relation) { $0.aliased(alias) }
|
||||
with {
|
||||
$0.relation = $0.relation.aliased(alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest: DerivableRequest {
|
||||
public func distinct() -> QueryInterfaceRequest {
|
||||
with(\.relation.isDistinct, true)
|
||||
with {
|
||||
$0.relation.isDistinct = true
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a request which fetches *limit* rows, starting at *offset*.
|
||||
@@ -296,11 +379,15 @@ extension QueryInterfaceRequest: DerivableRequest {
|
||||
///
|
||||
/// Any previous limit is replaced.
|
||||
public func limit(_ limit: Int, offset: Int?) -> QueryInterfaceRequest {
|
||||
with(\.relation.limit, SQLLimit(limit: limit, offset: offset))
|
||||
with {
|
||||
$0.relation.limit = SQLLimit(limit: limit, offset: offset)
|
||||
}
|
||||
}
|
||||
|
||||
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
|
||||
with(\.relation.ctes[cte.tableName], cte.cte)
|
||||
with {
|
||||
$0.relation.ctes[cte.tableName] = cte.cte
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -325,7 +412,7 @@ extension QueryInterfaceRequest {
|
||||
|
||||
// MARK: - Batch Delete
|
||||
|
||||
extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
extension QueryInterfaceRequest {
|
||||
/// Deletes matching rows; returns the number of deleted rows.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -340,7 +427,20 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
|
||||
// MARK: - Batch Update
|
||||
|
||||
extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
extension QueryInterfaceRequest {
|
||||
/// The conflict resolution to use for batch updates
|
||||
private var defaultConflictResolutionForUpdate: Database.ConflictResolution {
|
||||
// In order to look for the default conflict resolution, we perform a
|
||||
// runtime check for MutablePersistableRecord, and look for a
|
||||
// user-defined default. Such dynamic dispatch is unusual in GRDB, but
|
||||
// static dispatch is likely to create bad surprises in generic contexts.
|
||||
if let recordType = RowDecoder.self as? MutablePersistableRecord.Type {
|
||||
return recordType.persistenceConflictPolicy.conflictResolutionForUpdate
|
||||
} else {
|
||||
return .abort
|
||||
}
|
||||
}
|
||||
|
||||
/// Updates matching rows; returns the number of updated rows.
|
||||
///
|
||||
/// For example:
|
||||
@@ -351,8 +451,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
/// }
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution,
|
||||
/// defaulting to the record's persistenceConflictPolicy.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignments: An array of column assignments.
|
||||
/// - returns: The number of updated rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@@ -362,7 +461,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
_ assignments: [ColumnAssignment]) throws -> Int
|
||||
{
|
||||
let conflictResolution = conflictResolution ?? RowDecoder.persistenceConflictPolicy.conflictResolutionForUpdate
|
||||
let conflictResolution = conflictResolution ?? defaultConflictResolutionForUpdate
|
||||
guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement(
|
||||
db,
|
||||
conflictResolution: conflictResolution,
|
||||
@@ -385,8 +484,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
|
||||
/// }
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution,
|
||||
/// defaulting to the record's persistenceConflictPolicy.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution.
|
||||
/// - parameter assignment: A column assignment.
|
||||
/// - parameter otherAssignments: Eventual other column assignments.
|
||||
/// - returns: The number of updated rows.
|
||||
@@ -659,7 +757,11 @@ func makePrefetchRequest(
|
||||
let pivotAlias = TableAlias()
|
||||
|
||||
let prefetchRelation = association
|
||||
.map(\.pivot.relation, { $0.aliased(pivotAlias).filter(pivotFilter) })
|
||||
.with {
|
||||
$0.pivot.relation = $0.pivot.relation
|
||||
.aliased(pivotAlias)
|
||||
.filter(pivotFilter)
|
||||
}
|
||||
.destinationRelation()
|
||||
.annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") })
|
||||
|
||||
@@ -704,11 +806,13 @@ throws -> DatabaseRegion
|
||||
let pivotFilter = pivotMapping.joinExpression(leftRows: [DummyRow()])
|
||||
|
||||
let prefetchRelation = association
|
||||
.map(\.pivot.relation) { $0.filter(pivotFilter) }
|
||||
.with {
|
||||
$0.pivot.relation = $0.pivot.relation.filter(pivotFilter)
|
||||
}
|
||||
.destinationRelation()
|
||||
|
||||
return try SQLQueryGenerator(relation: prefetchRelation)
|
||||
.makeSelectStatement(db)
|
||||
.makeStatement(db)
|
||||
.databaseRegion // contains region of nested associations
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
/// let nameColumn = MyColumn(name: "name", sqlType: "VARCHAR")
|
||||
/// let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
/// See <https://github.com/groue/GRDB.swift#the-query-interface>
|
||||
public protocol ColumnExpression: SQLSpecificExpressible {
|
||||
/// The unqualified name of a database column.
|
||||
///
|
||||
@@ -35,7 +35,7 @@ extension ColumnExpression {
|
||||
/// When you need to introduce your own column type, don't wrap a Column.
|
||||
/// Instead, adopt the ColumnExpression protocol.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift#the-query-interface
|
||||
/// See <https://github.com/groue/GRDB.swift#the-query-interface>
|
||||
public struct Column: ColumnExpression, Equatable {
|
||||
/// The hidden rowID column
|
||||
public static let rowID = Column("rowid")
|
||||
|
||||
@@ -87,7 +87,9 @@ public struct _SQLAssociation {
|
||||
|
||||
/// Changes the destination key
|
||||
func forDestinationKey(_ key: SQLAssociationKey) -> Self {
|
||||
with(\.destination.key, key)
|
||||
with {
|
||||
$0.destination.key = key
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a new association
|
||||
@@ -126,7 +128,9 @@ public struct _SQLAssociation {
|
||||
.removingChildrenForPrefetchedAssociations()
|
||||
|
||||
// Don't interfere with user-defined keys that could be added later
|
||||
let key = step.key.map(\.baseName) { "grdb_\($0)" }
|
||||
let key = step.key.with {
|
||||
$0.baseName = "grdb_\($0.baseName)"
|
||||
}
|
||||
|
||||
return SQLAssociationStep(
|
||||
key: key,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/// The right-hand side of the `IN` or `NOT IN` SQL operators
|
||||
///
|
||||
/// See https://sqlite.org/lang_expr.html#the_in_and_not_in_operators
|
||||
/// See <https://sqlite.org/lang_expr.html#the_in_and_not_in_operators>
|
||||
struct SQLCollection {
|
||||
private var impl: Impl
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/// SQLExpression is the type that represents an SQL expression, as
|
||||
/// described at https://www.sqlite.org/lang_expr.html
|
||||
/// described at <https://www.sqlite.org/lang_expr.html>
|
||||
public struct SQLExpression {
|
||||
private var impl: Impl
|
||||
|
||||
@@ -370,7 +370,7 @@ public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryO
|
||||
extension SQLExpression {
|
||||
|
||||
/// SQLite row values were shipped in SQLite 3.15:
|
||||
/// https://www.sqlite.org/releaselog/3_15_0.html
|
||||
/// <https://www.sqlite.org/releaselog/3_15_0.html>
|
||||
static let rowValuesAreAvailable = (sqlite3_libversion_number() >= 3015000)
|
||||
|
||||
// MARK: Basic Expressions
|
||||
@@ -1204,7 +1204,7 @@ extension SQLExpression {
|
||||
///
|
||||
/// The `= 1` and `= 0` tests allow the SQLite query planner to
|
||||
/// optimize queries with indices on boolean columns and expressions.
|
||||
/// See https://github.com/groue/GRDB.swift/issues/816
|
||||
/// See <https://github.com/groue/GRDB.swift/issues/816>
|
||||
///
|
||||
/// Some specific expressions can produce idiomatic SQL.
|
||||
///
|
||||
@@ -1559,7 +1559,7 @@ extension SQLExpression {
|
||||
/// It is adopted by protocols like `DatabaseValueConvertible`, and types
|
||||
/// like `Column`.
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
/// See <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
public protocol SQLExpressible {
|
||||
/// Returns an SQL expression.
|
||||
var sqlExpression: SQLExpression { get }
|
||||
@@ -1665,14 +1665,14 @@ extension SQLSpecificExpressible {
|
||||
|
||||
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
/// See <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
public var asc: SQLOrdering {
|
||||
.asc(sqlExpression)
|
||||
}
|
||||
|
||||
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
/// See <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
public var desc: SQLOrdering {
|
||||
.desc(sqlExpression)
|
||||
}
|
||||
@@ -1680,21 +1680,21 @@ extension SQLSpecificExpressible {
|
||||
#if GRDBCUSTOMSQLITE
|
||||
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
/// See <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
public var ascNullsLast: SQLOrdering {
|
||||
.ascNullsLast(sqlExpression)
|
||||
}
|
||||
|
||||
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
/// See <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
public var descNullsFirst: SQLOrdering {
|
||||
.descNullsFirst(sqlExpression)
|
||||
}
|
||||
#elseif !GRDBCIPHER
|
||||
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
/// See <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
|
||||
public var ascNullsLast: SQLOrdering {
|
||||
.ascNullsLast(sqlExpression)
|
||||
@@ -1702,7 +1702,7 @@ extension SQLSpecificExpressible {
|
||||
|
||||
/// Returns a value that can be used as an argument to QueryInterfaceRequest.order()
|
||||
///
|
||||
/// See https://github.com/groue/GRDB.swift/#the-query-interface
|
||||
/// See <https://github.com/groue/GRDB.swift/#the-query-interface>
|
||||
@available(OSX 10.16, iOS 14, tvOS 14, watchOS 7, *)
|
||||
public var descNullsFirst: SQLOrdering {
|
||||
.descNullsFirst(sqlExpression)
|
||||
|
||||
@@ -174,7 +174,7 @@ extension SQLSpecificExpressible {
|
||||
/// A date modifier for SQLite date functions such as `julianDay(_:_:)` and
|
||||
/// `dateTime(_:_:)`.
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/lang_datefunc.html
|
||||
/// For more information, see <https://www.sqlite.org/lang_datefunc.html>
|
||||
public enum SQLDateModifier: SQLSpecificExpressible {
|
||||
/// Adds the specified amount of seconds
|
||||
case second(Double)
|
||||
@@ -203,16 +203,16 @@ public enum SQLDateModifier: SQLSpecificExpressible {
|
||||
/// Shifts the date backwards to the beginning of the current year
|
||||
case startOfYear
|
||||
|
||||
/// See https://www.sqlite.org/lang_datefunc.html
|
||||
/// See <https://www.sqlite.org/lang_datefunc.html>
|
||||
case weekday(Int)
|
||||
|
||||
/// See https://www.sqlite.org/lang_datefunc.html
|
||||
/// See <https://www.sqlite.org/lang_datefunc.html>
|
||||
case unixEpoch
|
||||
|
||||
/// See https://www.sqlite.org/lang_datefunc.html
|
||||
/// See <https://www.sqlite.org/lang_datefunc.html>
|
||||
case localTime
|
||||
|
||||
/// See https://www.sqlite.org/lang_datefunc.html
|
||||
/// See <https://www.sqlite.org/lang_datefunc.html>
|
||||
case utc
|
||||
|
||||
public var sqlExpression: SQLExpression {
|
||||
@@ -261,7 +261,7 @@ public enum SQLDateModifier: SQLSpecificExpressible {
|
||||
/// // JULIANDAY(date, '1 days')
|
||||
/// julianDay(Column("date"), .day(1))
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/lang_datefunc.html
|
||||
/// For more information, see <https://www.sqlite.org/lang_datefunc.html>
|
||||
public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression {
|
||||
.function("JULIANDAY", [value.sqlExpression] + modifiers.map(\.sqlExpression))
|
||||
}
|
||||
@@ -276,7 +276,7 @@ public func julianDay(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModif
|
||||
/// // DATETIME(date, '1 days')
|
||||
/// dateTime(Column("date"), .day(1))
|
||||
///
|
||||
/// For more information, see https://www.sqlite.org/lang_datefunc.html
|
||||
/// For more information, see <https://www.sqlite.org/lang_datefunc.html>
|
||||
public func dateTime(_ value: SQLSpecificExpressible, _ modifiers: SQLDateModifier...) -> SQLExpression {
|
||||
.function("DATETIME", [value.sqlExpression] + modifiers.map(\.sqlExpression))
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/// The type that can be used as an SQL ordering term, as described at
|
||||
/// https://www.sqlite.org/syntax/ordering-term.html
|
||||
/// <https://www.sqlite.org/syntax/ordering-term.html>
|
||||
public struct SQLOrdering {
|
||||
private var impl: Impl
|
||||
|
||||
@@ -117,7 +117,7 @@ extension SQLOrdering {
|
||||
// MARK: - SQLOrderingTerm
|
||||
|
||||
/// The protocol for all types that can be used as an SQL ordering term, as
|
||||
/// described at https://www.sqlite.org/syntax/ordering-term.html
|
||||
/// described at <https://www.sqlite.org/syntax/ordering-term.html>
|
||||
public protocol SQLOrderingTerm {
|
||||
/// Returns an SQL ordering.
|
||||
var sqlOrdering: SQLOrdering { get }
|
||||
|
||||
@@ -190,7 +190,9 @@ extension SQLRelation {
|
||||
|
||||
extension SQLRelation: Refinable {
|
||||
func select(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
|
||||
with(\.selectionPromise, DatabasePromise(selection))
|
||||
with {
|
||||
$0.selectionPromise = DatabasePromise(selection)
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience
|
||||
@@ -208,18 +210,21 @@ extension SQLRelation: Refinable {
|
||||
func selectOnly(_ selection: [SQLSelection]) -> Self {
|
||||
self
|
||||
.select(selection)
|
||||
.with(\.isDistinct, false)
|
||||
.map(\.children) { children in
|
||||
children.mapValues { child in
|
||||
child.map(\.relation) { $0.selectOnly([]) }
|
||||
.with {
|
||||
$0.isDistinct = false
|
||||
$0.children = children.mapValues { child in
|
||||
child.with {
|
||||
$0.relation = $0.relation.selectOnly([])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func annotated(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
|
||||
map(\.selectionPromise) { selectionPromise in
|
||||
DatabasePromise { db in
|
||||
try selectionPromise.resolve(db) + selection(db)
|
||||
with {
|
||||
let old = $0.selectionPromise
|
||||
$0.selectionPromise = DatabasePromise { db in
|
||||
try old.resolve(db) + selection(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -230,13 +235,13 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
|
||||
func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
|
||||
map(\.filterPromise) { promise in
|
||||
DatabasePromise { db in
|
||||
if let filter = try promise?.resolve(db) {
|
||||
return try filter && predicate(db)
|
||||
} else {
|
||||
return try predicate(db)
|
||||
with {
|
||||
if let old = $0.filterPromise {
|
||||
$0.filterPromise = DatabasePromise { db in
|
||||
try old.resolve(db) && predicate(db)
|
||||
}
|
||||
} else {
|
||||
$0.filterPromise = DatabasePromise(predicate)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -247,41 +252,50 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
|
||||
func order(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
|
||||
with(\.ordering, SQLRelation.Ordering(orderings: orderings))
|
||||
with {
|
||||
$0.ordering = SQLRelation.Ordering(orderings: orderings)
|
||||
}
|
||||
}
|
||||
|
||||
func reversed() -> Self {
|
||||
map(\.ordering, \.reversed)
|
||||
with {
|
||||
$0.ordering = $0.ordering.reversed
|
||||
}
|
||||
}
|
||||
|
||||
func unordered() -> Self {
|
||||
self
|
||||
.with(\.ordering, SQLRelation.Ordering())
|
||||
.map(\.children) { children in
|
||||
children.mapValues { child in
|
||||
child.map(\.relation) { $0.unordered() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
|
||||
with(\.groupPromise, DatabasePromise(expressions))
|
||||
}
|
||||
|
||||
func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
|
||||
map(\.havingExpressionPromise) { promise in
|
||||
DatabasePromise { db in
|
||||
if let filter = try promise?.resolve(db) {
|
||||
return try filter && predicate(db)
|
||||
} else {
|
||||
return try predicate(db)
|
||||
with {
|
||||
$0.ordering = SQLRelation.Ordering()
|
||||
$0.children = children.mapValues { child in
|
||||
child.with {
|
||||
$0.relation = $0.relation.unordered()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
|
||||
with {
|
||||
$0.groupPromise = DatabasePromise(expressions)
|
||||
}
|
||||
}
|
||||
|
||||
func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
|
||||
with {
|
||||
if let old = $0.havingExpressionPromise {
|
||||
$0.havingExpressionPromise = DatabasePromise { db in
|
||||
try old.resolve(db) && predicate(db)
|
||||
}
|
||||
} else {
|
||||
$0.havingExpressionPromise = DatabasePromise(predicate)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func aliased(_ alias: TableAlias) -> Self {
|
||||
map(\.source) { $0.aliased(alias) }
|
||||
with {
|
||||
$0.source = $0.source.aliased(alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,9 +310,9 @@ extension SQLRelation {
|
||||
return child.relation.prefetchedAssociations.map { association in
|
||||
// Remove redundant pivot child
|
||||
let pivotKey = association.pivot.keyName
|
||||
let child = child.map(\.relation) { relation in
|
||||
assert(relation.children[pivotKey] != nil)
|
||||
return relation.removingChild(forKey: pivotKey)
|
||||
let child = child.with {
|
||||
assert($0.relation.children[pivotKey] != nil)
|
||||
$0.relation = $0.relation.removingChild(forKey: pivotKey)
|
||||
}
|
||||
return association.through(child.makeAssociationForKey(key))
|
||||
}
|
||||
@@ -488,11 +502,15 @@ extension SQLRelation {
|
||||
}
|
||||
|
||||
func removingChild(forKey key: String) -> Self {
|
||||
mapInto(\.children) { $0.removeValue(forKey: key) }
|
||||
with {
|
||||
$0.children.removeValue(forKey: key)
|
||||
}
|
||||
}
|
||||
|
||||
func filteringChildren(_ included: (Child) throws -> Bool) rethrows -> Self {
|
||||
try map(\.children) { try $0.filter { try included($1) } }
|
||||
try with {
|
||||
$0.children = try $0.children.filter { (_, child) in try included(child) }
|
||||
}
|
||||
}
|
||||
|
||||
func removingChildrenForPrefetchedAssociations() -> Self {
|
||||
@@ -519,11 +537,19 @@ extension SQLRelation {
|
||||
}
|
||||
|
||||
func _joining(optional association: _SQLAssociation) -> Self {
|
||||
appendingChild(for: association.map(\.destination.relation, { $0.select([]) }), kind: .oneOptional)
|
||||
// Remove association selection
|
||||
let associationWithEmptySelection = association.with {
|
||||
$0.destination.relation = $0.destination.relation.select([])
|
||||
}
|
||||
return appendingChild(for: associationWithEmptySelection, kind: .oneOptional)
|
||||
}
|
||||
|
||||
func _joining(required association: _SQLAssociation) -> Self {
|
||||
appendingChild(for: association.map(\.destination.relation, { $0.select([]) }), kind: .oneRequired)
|
||||
// Remove association selection
|
||||
let associationWithEmptySelection = association.with {
|
||||
$0.destination.relation = $0.destination.relation.select([])
|
||||
}
|
||||
return appendingChild(for: associationWithEmptySelection, kind: .oneRequired)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -869,33 +895,46 @@ extension JoinMapping {
|
||||
return true.sqlExpression
|
||||
}
|
||||
|
||||
// SQLite doesn't match foreign keys on NULL: https://www.sqlite.org/foreignkeys.html
|
||||
// > The foreign key constraint is satisfied if for each row in the
|
||||
// > child table either one or more of the child key columns are NULL,
|
||||
// > or there exists a row in the parent table for which each parent key
|
||||
// > column contains a value equal to the value in its associated child
|
||||
// > key column.
|
||||
//
|
||||
// Since a single NULL value satisfies the foreign key constraint
|
||||
// without requiring a matching matching parent row, below we'll ignore
|
||||
// left rows (children) that attempt at matching on NULL.
|
||||
if mappings.count == 1 {
|
||||
// Join on a single right column.
|
||||
// table.a IN (1, 2, 3, ...)
|
||||
|
||||
// Unique database values and filter out NULL:
|
||||
// Unique database values and filter out NULL because SQLite doesn't
|
||||
// match foreign keys on NULL
|
||||
let leftIndex = mapping.leftIndex
|
||||
var dbValues = Set(leftRows.map { $0.databaseValue(at: leftIndex) })
|
||||
dbValues.remove(.null) // SQLite doesn't match foreign keys on NULL
|
||||
// table.a IN (1, 2, 3, ...)
|
||||
dbValues.remove(.null)
|
||||
|
||||
// Sort database values for nicer output.
|
||||
return dbValues.sorted(by: <).contains(mapping.rightColumn)
|
||||
} else {
|
||||
// Join on a multiple columns.
|
||||
// ((table.a = 1) AND (table.b = 2)) OR ((table.a = 3) AND (table.b = 4)) ...
|
||||
return leftRows
|
||||
.map({ leftRow in
|
||||
.compactMap { leftRow -> SQLExpression? in
|
||||
// (table.a = 1) AND (table.b = 2)
|
||||
mappings
|
||||
.map({ mapping -> SQLExpression in
|
||||
let leftValue = leftRow.databaseValue(at: mapping.leftIndex)
|
||||
// Force `=` operator, because SQLite doesn't match foreign keys on NULL
|
||||
return SQLExpression.compare(
|
||||
.equal,
|
||||
mapping.rightColumn.sqlExpression,
|
||||
leftValue.sqlExpression)
|
||||
})
|
||||
.joined(operator: .and)
|
||||
})
|
||||
var conditions: [SQLExpression] = []
|
||||
for mapping in mappings {
|
||||
let dbValue = leftRow.databaseValue(at: mapping.leftIndex)
|
||||
if dbValue.isNull {
|
||||
// SQLite doesn't match foreign keys on NULL:
|
||||
// give up this left row.
|
||||
return nil
|
||||
}
|
||||
conditions.append(mapping.rightColumn == dbValue)
|
||||
}
|
||||
return conditions.joined(operator: .and)
|
||||
}
|
||||
.joined(operator: .or)
|
||||
}
|
||||
}
|
||||
@@ -941,10 +980,7 @@ 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
|
||||
self[caseInsensitive: column]?.databaseValue ?? .null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/// The type that can be selected, as described at
|
||||
/// https://www.sqlite.org/syntax/result-column.html
|
||||
/// <https://www.sqlite.org/syntax/result-column.html>
|
||||
public struct SQLSelection {
|
||||
private var impl: Impl
|
||||
|
||||
@@ -175,7 +175,7 @@ extension SQLSelection {
|
||||
/// COUNT(*)
|
||||
/// (score + bonus) AS total
|
||||
///
|
||||
/// See https://sqlite.org/syntax/result-column.html
|
||||
/// See <https://sqlite.org/syntax/result-column.html>
|
||||
///
|
||||
/// - parameter context: An SQL generation context which accepts
|
||||
/// statement arguments.
|
||||
@@ -285,7 +285,7 @@ enum SQLCount {
|
||||
// MARK: - SQLSelectable
|
||||
|
||||
/// SQLSelectable is the protocol for types that can be selected, as
|
||||
/// described at https://www.sqlite.org/syntax/result-column.html
|
||||
/// described at <https://www.sqlite.org/syntax/result-column.html>
|
||||
public protocol SQLSelectable {
|
||||
/// Returns an SQL selection.
|
||||
var sqlSelection: SQLSelection { get }
|
||||
|
||||
@@ -45,7 +45,7 @@ extension SQLSubquery {
|
||||
// do not execute the statement or modify its arguments.
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
let statement = try db.cachedSelectStatement(sql: sql)
|
||||
let statement = try db.cachedStatement(sql: sql)
|
||||
return statement.columnCount
|
||||
|
||||
case let .relation(relation):
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -93,7 +93,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
|
||||
func makePreparedRequest(_ db: Database) throws -> PreparedRequest {
|
||||
try PreparedRequest(
|
||||
statement: makeSelectStatement(db),
|
||||
statement: makeStatement(db),
|
||||
adapter: rowAdapter(SQLGenerationContext(db, ctes: relation.ctes)))
|
||||
}
|
||||
|
||||
@@ -105,14 +105,14 @@ struct SQLQueryGenerator: Refinable {
|
||||
.columnCount(SQLGenerationContext(db, ctes: relation.ctes))
|
||||
}
|
||||
|
||||
/// Returns a select statement
|
||||
func makeSelectStatement(_ db: Database) throws -> SelectStatement {
|
||||
/// Returns a prepared statement
|
||||
func makeStatement(_ db: Database) throws -> Statement {
|
||||
// Build
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try requestSQL(context)
|
||||
|
||||
// Compile & set arguments
|
||||
let statement = try db.makeSelectStatement(sql: sql)
|
||||
let statement = try db.makeStatement(sql: sql)
|
||||
statement.arguments = context.arguments
|
||||
|
||||
// Optimize statement region. This allows us to track individual rowids,
|
||||
@@ -197,7 +197,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
return false
|
||||
}
|
||||
|
||||
func makeDeleteStatement(_ db: Database) throws -> UpdateStatement {
|
||||
func makeDeleteStatement(_ db: Database) throws -> Statement {
|
||||
switch try grouping(db) {
|
||||
case .none:
|
||||
guard relation.joins.isEmpty else {
|
||||
@@ -225,7 +225,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql: sql)
|
||||
let statement = try db.makeStatement(sql: sql)
|
||||
statement.arguments = context.arguments
|
||||
return statement
|
||||
|
||||
@@ -239,20 +239,23 @@ struct SQLQueryGenerator: Refinable {
|
||||
}
|
||||
|
||||
/// DELETE FROM table WHERE id IN (SELECT id FROM table ...)
|
||||
private func makeTrivialDeleteStatement(_ db: Database) throws -> UpdateStatement {
|
||||
private func makeTrivialDeleteStatement(_ db: Database) throws -> Statement {
|
||||
let tableName = relation.source.tableName
|
||||
let alias = TableAlias(tableName: tableName)
|
||||
let context = SQLGenerationContext(db, aliases: [alias])
|
||||
let subqueryContext = context.subqueryContext(aliases: relation.allAliases, ctes: relation.ctes)
|
||||
let primaryKey = SQLExpression.fastPrimaryKey
|
||||
let selectPrimaryKey = self.with {
|
||||
$0.relation = $0.relation.selectOnly([.expression(primaryKey)])
|
||||
}
|
||||
|
||||
var sql = "DELETE FROM \(tableName.quotedDatabaseIdentifier) WHERE "
|
||||
sql += try alias[primaryKey].sql(context)
|
||||
sql += " IN ("
|
||||
sql += try map(\.relation, { $0.selectOnly([.expression(primaryKey)]) }).requestSQL(subqueryContext)
|
||||
sql += try selectPrimaryKey.requestSQL(subqueryContext)
|
||||
sql += ")"
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql: sql)
|
||||
let statement = try db.makeStatement(sql: sql)
|
||||
statement.arguments = context.arguments
|
||||
return statement
|
||||
}
|
||||
@@ -262,7 +265,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
_ db: Database,
|
||||
conflictResolution: Database.ConflictResolution,
|
||||
assignments: [ColumnAssignment])
|
||||
throws -> UpdateStatement?
|
||||
throws -> Statement?
|
||||
{
|
||||
switch try grouping(db) {
|
||||
case .none:
|
||||
@@ -311,7 +314,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql: sql)
|
||||
let statement = try db.makeStatement(sql: sql)
|
||||
statement.arguments = context.arguments
|
||||
return statement
|
||||
|
||||
@@ -330,7 +333,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
_ db: Database,
|
||||
conflictResolution: Database.ConflictResolution,
|
||||
assignments: [ColumnAssignment])
|
||||
throws -> UpdateStatement?
|
||||
throws -> Statement?
|
||||
{
|
||||
// Check for empty assignments after all programmer errors have
|
||||
// been checked.
|
||||
@@ -343,6 +346,9 @@ struct SQLQueryGenerator: Refinable {
|
||||
let context = SQLGenerationContext(db, aliases: [alias])
|
||||
let subqueryContext = context.subqueryContext(aliases: relation.allAliases, ctes: relation.ctes)
|
||||
let primaryKey = SQLExpression.fastPrimaryKey
|
||||
let selectPrimaryKey = self.with {
|
||||
$0.relation = $0.relation.selectOnly([.expression(primaryKey)])
|
||||
}
|
||||
|
||||
// UPDATE table...
|
||||
var sql = "UPDATE "
|
||||
@@ -361,10 +367,10 @@ struct SQLQueryGenerator: Refinable {
|
||||
sql += " WHERE "
|
||||
sql += try alias[primaryKey].sql(context)
|
||||
sql += " IN ("
|
||||
sql += try map(\.relation, { $0.selectOnly([.expression(primaryKey)]) }).requestSQL(subqueryContext)
|
||||
sql += try selectPrimaryKey.requestSQL(subqueryContext)
|
||||
sql += ")"
|
||||
|
||||
let statement = try db.makeUpdateStatement(sql: sql)
|
||||
let statement = try db.makeStatement(sql: sql)
|
||||
statement.arguments = context.arguments
|
||||
return statement
|
||||
}
|
||||
@@ -654,17 +660,18 @@ private struct SQLQualifiedRelation {
|
||||
/// Sets the selection, removes all selections from joins, and clears the
|
||||
/// `isDistinct` flag.
|
||||
func selectOnly(_ selection: [SQLSelection]) -> Self {
|
||||
let sourceSelectionPromise = DatabasePromise(value: selection.map {
|
||||
let qualifiedSelection = selection.map {
|
||||
$0.qualified(with: source.alias)
|
||||
})
|
||||
return self
|
||||
.with(\.sourceSelectionPromise, sourceSelectionPromise)
|
||||
.with(\.isDistinct, false)
|
||||
.map(\.joins, { joins in
|
||||
joins.mapValues { join in
|
||||
join.map(\.relation) { $0.selectOnly([]) }
|
||||
}
|
||||
return with {
|
||||
$0.sourceSelectionPromise = DatabasePromise(value: qualifiedSelection)
|
||||
$0.isDistinct = false
|
||||
$0.joins = $0.joins.mapValues { join in
|
||||
join.with {
|
||||
$0.relation = $0.relation.selectOnly([])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ extension Database {
|
||||
/// t.column("latitude", .double).notNull()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html and
|
||||
/// https://www.sqlite.org/withoutrowid.html
|
||||
/// See <https://www.sqlite.org/lang_createtable.html> and
|
||||
/// <https://www.sqlite.org/withoutrowid.html>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
@@ -44,7 +44,7 @@ extension Database {
|
||||
|
||||
/// Renames a database table.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_altertable.html
|
||||
/// See <https://www.sqlite.org/lang_altertable.html>
|
||||
///
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func rename(table name: String, to newName: String) throws {
|
||||
@@ -57,7 +57,7 @@ extension Database {
|
||||
/// t.add(column: "url", .text)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_altertable.html
|
||||
/// See <https://www.sqlite.org/lang_altertable.html>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
@@ -72,7 +72,7 @@ extension Database {
|
||||
|
||||
/// Deletes a database table.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_droptable.html
|
||||
/// See <https://www.sqlite.org/lang_droptable.html>
|
||||
///
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func drop(table name: String) throws {
|
||||
@@ -89,7 +89,7 @@ extension Database {
|
||||
///
|
||||
/// try db.execute(sql: "CREATE INDEX ...")
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createindex.html
|
||||
/// See <https://www.sqlite.org/lang_createindex.html>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The index name.
|
||||
@@ -98,7 +98,7 @@ extension Database {
|
||||
/// - unique: If true, creates a unique index.
|
||||
/// - ifNotExists: If false, no error is thrown if index already exists.
|
||||
/// - condition: If not nil, creates a partial index
|
||||
/// (see https://www.sqlite.org/partialindex.html).
|
||||
/// (see <https://www.sqlite.org/partialindex.html>).
|
||||
public func create(
|
||||
index name: String,
|
||||
on table: String,
|
||||
@@ -121,7 +121,7 @@ extension Database {
|
||||
|
||||
/// Deletes a database index.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_dropindex.html
|
||||
/// See <https://www.sqlite.org/lang_dropindex.html>
|
||||
///
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func drop(index name: String) throws {
|
||||
@@ -133,7 +133,7 @@ extension Database {
|
||||
/// This method is useful when the definition of a collation sequence
|
||||
/// has changed.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_reindex.html
|
||||
/// See <https://www.sqlite.org/lang_reindex.html>
|
||||
///
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func reindex(collation: Database.CollationName) throws {
|
||||
@@ -145,7 +145,7 @@ extension Database {
|
||||
/// This method is useful when the definition of a collation sequence
|
||||
/// has changed.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_reindex.html
|
||||
/// See <https://www.sqlite.org/lang_reindex.html>
|
||||
///
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func reindex(collation: DatabaseCollation) throws {
|
||||
@@ -162,7 +162,7 @@ extension Database {
|
||||
/// t.column(...)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html
|
||||
/// See <https://www.sqlite.org/lang_createtable.html>
|
||||
public final class TableDefinition {
|
||||
private typealias KeyConstraint = (
|
||||
columns: [String],
|
||||
@@ -238,11 +238,11 @@ public final class TableDefinition {
|
||||
/// asynchronous process, even if this row gets deleted and a new one is
|
||||
/// inserted in between.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#primkeyconst and
|
||||
/// https://www.sqlite.org/lang_createtable.html#rowid
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#primkeyconst> and
|
||||
/// <https://www.sqlite.org/lang_createtable.html#rowid>
|
||||
///
|
||||
/// - parameter conflictResolution: An optional conflict resolution
|
||||
/// (see https://www.sqlite.org/lang_conflict.html).
|
||||
/// (see <https://www.sqlite.org/lang_conflict.html>).
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
public func autoIncrementedPrimaryKey(
|
||||
@@ -259,7 +259,7 @@ public final class TableDefinition {
|
||||
/// t.column("name", .text)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#tablecoldef
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#tablecoldef>
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
/// - parameter type: the eventual column type.
|
||||
@@ -305,12 +305,12 @@ public final class TableDefinition {
|
||||
/// t.primaryKey(["citizenID", "countryCode"])
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#primkeyconst and
|
||||
/// https://www.sqlite.org/lang_createtable.html#rowid
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#primkeyconst> and
|
||||
/// <https://www.sqlite.org/lang_createtable.html#rowid>
|
||||
///
|
||||
/// - parameter columns: The primary key columns.
|
||||
/// - parameter conflictResolution: An optional conflict resolution
|
||||
/// (see https://www.sqlite.org/lang_conflict.html).
|
||||
/// (see <https://www.sqlite.org/lang_conflict.html>).
|
||||
public func primaryKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil) {
|
||||
guard primaryKeyConstraint == nil else {
|
||||
// Programmer error
|
||||
@@ -327,11 +327,11 @@ public final class TableDefinition {
|
||||
/// t.uniqueKey(["latitude", "longitude"])
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#uniqueconst
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#uniqueconst>
|
||||
///
|
||||
/// - parameter columns: The unique key columns.
|
||||
/// - parameter conflictResolution: An optional conflict resolution
|
||||
/// (see https://www.sqlite.org/lang_conflict.html).
|
||||
/// (see <https://www.sqlite.org/lang_conflict.html>).
|
||||
public func uniqueKey(_ columns: [String], onConflict conflictResolution: Database.ConflictResolution? = nil) {
|
||||
uniqueKeyConstraints.append((columns: columns, conflictResolution: conflictResolution))
|
||||
}
|
||||
@@ -345,7 +345,7 @@ public final class TableDefinition {
|
||||
/// t.foreignKey(["citizenID", "countryCode"], references: "citizenship", onDelete: .cascade)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/foreignkeys.html
|
||||
/// See <https://www.sqlite.org/foreignkeys.html>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - columns: The foreign key columns.
|
||||
@@ -356,7 +356,7 @@ public final class TableDefinition {
|
||||
/// - deleteAction: Optional action when the referenced row is deleted.
|
||||
/// - updateAction: Optional action when the referenced row is updated.
|
||||
/// - deferred: If true, defines a deferred foreign key constraint.
|
||||
/// See https://www.sqlite.org/foreignkeys.html#fk_deferred.
|
||||
/// See <https://www.sqlite.org/foreignkeys.html#fk_deferred>.
|
||||
public func foreignKey(
|
||||
_ columns: [String],
|
||||
references table: String,
|
||||
@@ -384,7 +384,7 @@ public final class TableDefinition {
|
||||
/// t.check(personalPhone != nil || workPhone != nil)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#ckconst
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#ckconst>
|
||||
///
|
||||
/// - parameter condition: The checked condition
|
||||
public func check(_ condition: SQLExpressible) {
|
||||
@@ -399,7 +399,7 @@ public final class TableDefinition {
|
||||
/// t.check(sql: "personalPhone IS NOT NULL OR workPhone IS NOT NULL")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#ckconst
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#ckconst>
|
||||
///
|
||||
/// - parameter sql: An SQL snippet
|
||||
public func check(sql: String) {
|
||||
@@ -572,7 +572,7 @@ public final class TableDefinition {
|
||||
/// t.add(column: ...)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_altertable.html
|
||||
/// See <https://www.sqlite.org/lang_altertable.html>
|
||||
public final class TableAlteration {
|
||||
private let name: String
|
||||
|
||||
@@ -594,7 +594,7 @@ public final class TableAlteration {
|
||||
/// t.add(column: "url", .text)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_altertable.html
|
||||
/// See <https://www.sqlite.org/lang_altertable.html>
|
||||
///
|
||||
/// - parameter name: the column name.
|
||||
/// - parameter type: the column type.
|
||||
@@ -638,7 +638,7 @@ public final class TableAlteration {
|
||||
/// t.rename(column: "url", to: "homeURL")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_altertable.html
|
||||
/// See <https://www.sqlite.org/lang_altertable.html>
|
||||
///
|
||||
/// - parameter name: the column name to rename.
|
||||
/// - parameter newName: the new name of the column.
|
||||
@@ -652,7 +652,7 @@ public final class TableAlteration {
|
||||
/// t.rename(column: "url", to: "homeURL")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_altertable.html
|
||||
/// See <https://www.sqlite.org/lang_altertable.html>
|
||||
///
|
||||
/// - parameter name: the column name to rename.
|
||||
/// - parameter newName: the new name of the column.
|
||||
@@ -723,8 +723,8 @@ public final class TableAlteration {
|
||||
/// t.add(column: ...) // ColumnDefinition
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html and
|
||||
/// https://www.sqlite.org/lang_altertable.html
|
||||
/// See <https://www.sqlite.org/lang_createtable.html> and
|
||||
/// <https://www.sqlite.org/lang_altertable.html>
|
||||
public final class ColumnDefinition {
|
||||
enum Index {
|
||||
case none
|
||||
@@ -743,7 +743,7 @@ public final class ColumnDefinition {
|
||||
/// The `GeneratedColumnQualification` enum defines whether a generated
|
||||
/// column sis virtual or stored.
|
||||
///
|
||||
/// See https://sqlite.org/gencol.html#virtual_versus_stored_columns
|
||||
/// See <https://sqlite.org/gencol.html#virtual_versus_stored_columns>
|
||||
public enum GeneratedColumnQualification {
|
||||
case virtual
|
||||
case stored
|
||||
@@ -776,12 +776,12 @@ public final class ColumnDefinition {
|
||||
/// t.column("id", .integer).primaryKey()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#primkeyconst and
|
||||
/// https://www.sqlite.org/lang_createtable.html#rowid
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#primkeyconst> and
|
||||
/// <https://www.sqlite.org/lang_createtable.html#rowid>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - conflictResolution: An optional conflict resolution
|
||||
/// (see https://www.sqlite.org/lang_conflict.html).
|
||||
/// (see <https://www.sqlite.org/lang_conflict.html>).
|
||||
/// - autoincrement: If true, the primary key is autoincremented.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
@@ -800,10 +800,10 @@ public final class ColumnDefinition {
|
||||
/// t.column("name", .text).notNull()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#notnullconst
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#notnullconst>
|
||||
///
|
||||
/// - parameter conflictResolution: An optional conflict resolution
|
||||
/// (see https://www.sqlite.org/lang_conflict.html).
|
||||
/// (see <https://www.sqlite.org/lang_conflict.html>).
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
public func notNull(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
|
||||
@@ -817,10 +817,10 @@ public final class ColumnDefinition {
|
||||
/// t.column("email", .text).unique()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#uniqueconst
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#uniqueconst>
|
||||
///
|
||||
/// - parameter conflictResolution: An optional conflict resolution
|
||||
/// (see https://www.sqlite.org/lang_conflict.html).
|
||||
/// (see <https://www.sqlite.org/lang_conflict.html>).
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
public func unique(onConflict conflictResolution: Database.ConflictResolution? = nil) -> Self {
|
||||
@@ -834,7 +834,7 @@ public final class ColumnDefinition {
|
||||
/// t.column("email", .text).indexed()
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#uniqueconst
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#uniqueconst>
|
||||
///
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
@@ -851,7 +851,7 @@ public final class ColumnDefinition {
|
||||
/// t.column("name", .text).check { length($0) > 0 }
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#ckconst
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#ckconst>
|
||||
///
|
||||
/// - parameter condition: A closure whose argument is an Column that
|
||||
/// represents the defined column, and returns the expression to check.
|
||||
@@ -868,7 +868,7 @@ public final class ColumnDefinition {
|
||||
/// t.column("name", .text).check(sql: "LENGTH(name) > 0")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#ckconst
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#ckconst>
|
||||
///
|
||||
/// - parameter sql: An SQL snippet.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@@ -884,7 +884,7 @@ public final class ColumnDefinition {
|
||||
/// t.column("name", .text).defaults(to: "Anonymous")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#dfltval
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#dfltval>
|
||||
///
|
||||
/// - parameter value: A DatabaseValueConvertible value.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@@ -900,7 +900,7 @@ public final class ColumnDefinition {
|
||||
/// t.column("creationDate", .DateTime).defaults(sql: "CURRENT_TIMESTAMP")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html#dfltval
|
||||
/// See <https://www.sqlite.org/lang_createtable.html#dfltval>
|
||||
///
|
||||
/// - parameter sql: An SQL snippet.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@@ -916,7 +916,7 @@ public final class ColumnDefinition {
|
||||
/// t.column("email", .text).collate(.nocase)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html#collation
|
||||
/// See <https://www.sqlite.org/datatype3.html#collation>
|
||||
///
|
||||
/// - parameter collation: An Database.CollationName.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@@ -932,7 +932,7 @@ public final class ColumnDefinition {
|
||||
/// t.column("name", .text).collate(.localizedCaseInsensitiveCompare)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/datatype3.html#collation
|
||||
/// See <https://www.sqlite.org/datatype3.html#collation>
|
||||
///
|
||||
/// - parameter collation: A custom DatabaseCollation.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@@ -952,7 +952,7 @@ public final class ColumnDefinition {
|
||||
/// t.column("totalScore", .integer).generatedAs(sql: "score + bonus", .stored)
|
||||
/// }
|
||||
///
|
||||
/// See https://sqlite.org/gencol.html. Note particularly the limitations of
|
||||
/// See <https://sqlite.org/gencol.html>. Note particularly the limitations of
|
||||
/// generated columns, e.g. they may not have a default value.
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -982,7 +982,7 @@ public final class ColumnDefinition {
|
||||
/// t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"), .stored)
|
||||
/// }
|
||||
///
|
||||
/// See https://sqlite.org/gencol.html. Note particularly the limitations of
|
||||
/// See <https://sqlite.org/gencol.html>. Note particularly the limitations of
|
||||
/// generated columns, e.g. they may not have a default value.
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -1009,7 +1009,7 @@ public final class ColumnDefinition {
|
||||
/// t.column("authorId", .integer).references("author", onDelete: .cascade)
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/foreignkeys.html
|
||||
/// See <https://www.sqlite.org/foreignkeys.html>
|
||||
///
|
||||
/// - parameters
|
||||
/// - table: The referenced table.
|
||||
@@ -1018,7 +1018,7 @@ public final class ColumnDefinition {
|
||||
/// - deleteAction: Optional action when the referenced row is deleted.
|
||||
/// - updateAction: Optional action when the referenced row is updated.
|
||||
/// - deferred: If true, defines a deferred foreign key constraint.
|
||||
/// See https://www.sqlite.org/foreignkeys.html#fk_deferred.
|
||||
/// See <https://www.sqlite.org/foreignkeys.html#fk_deferred>.
|
||||
/// - returns: Self so that you can further refine the column definition.
|
||||
@discardableResult
|
||||
public func references(
|
||||
|
||||
@@ -21,14 +21,26 @@ public protocol VirtualTableModule {
|
||||
/// The name of the module.
|
||||
var moduleName: String { get }
|
||||
|
||||
// TODO: remove this requirement
|
||||
/// Returns a table definition that is passed as the closure argument in the
|
||||
/// `Database.create(virtualTable:using:)` method:
|
||||
///
|
||||
/// try db.create(virtualTable: "item", using: module) { t in
|
||||
/// // t is the result of makeTableDefinition()
|
||||
/// }
|
||||
///
|
||||
/// - warning: This method is DEPRECATED. Define
|
||||
/// `makeTableDefinition(configuration:)` instead.
|
||||
func makeTableDefinition() -> TableDefinition
|
||||
|
||||
/// Returns a table definition that is passed as the closure argument in the
|
||||
/// `Database.create(virtualTable:using:)` method:
|
||||
///
|
||||
/// try db.create(virtualTable: "item", using: module) { t in
|
||||
/// // t is the result of makeTableDefinition(configuration:)
|
||||
/// }
|
||||
func makeTableDefinition(configuration: VirtualTableConfiguration) -> TableDefinition
|
||||
|
||||
/// Returns the module arguments for the `CREATE VIRTUAL TABLE` query.
|
||||
func moduleArguments(for definition: TableDefinition, in db: Database) throws -> [String]
|
||||
|
||||
@@ -37,6 +49,20 @@ public protocol VirtualTableModule {
|
||||
func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
|
||||
}
|
||||
|
||||
extension VirtualTableModule {
|
||||
// Support for VirtualTableModule types defined by users
|
||||
// TODO: remove when `makeTableDefinition()` is no longer a requirement
|
||||
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> TableDefinition {
|
||||
makeTableDefinition()
|
||||
}
|
||||
}
|
||||
|
||||
public struct VirtualTableConfiguration {
|
||||
/// If true, existing objects must not be replaced, or generate any error
|
||||
/// (even if they do not match the objects that would be created otherwise.)
|
||||
var ifNotExists: Bool
|
||||
}
|
||||
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Schema
|
||||
@@ -45,7 +71,7 @@ extension Database {
|
||||
///
|
||||
/// try db.create(virtualTable: "vocabulary", using: "spellfix1")
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html
|
||||
/// See <https://www.sqlite.org/lang_createtable.html>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
@@ -86,7 +112,7 @@ extension Database {
|
||||
/// t.column("body")
|
||||
/// }
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_createtable.html
|
||||
/// See <https://www.sqlite.org/lang_createtable.html>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
@@ -104,7 +130,8 @@ extension Database {
|
||||
throws
|
||||
{
|
||||
// Define virtual table
|
||||
let definition = module.makeTableDefinition()
|
||||
let configuration = VirtualTableConfiguration(ifNotExists: ifNotExists)
|
||||
let definition = module.makeTableDefinition(configuration: configuration)
|
||||
if let body = body {
|
||||
body(definition)
|
||||
}
|
||||
|
||||
@@ -209,6 +209,91 @@ extension TableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Associations to Table
|
||||
|
||||
extension TableRecord {
|
||||
/// Creates a "Belongs To" association between Self and the destination
|
||||
/// table, based on a database foreign key.
|
||||
///
|
||||
/// For more information, see `TableRecord.belongsTo(_:key:using:)` where
|
||||
/// the first argument is `TableRecord`.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - destination: The table at the other side of the association.
|
||||
/// - key: An eventual decoding key for the association. By default, it
|
||||
/// is `destination.tableName`.
|
||||
/// - foreignKey: An eventual foreign key. You need to provide an
|
||||
/// explicit foreign key when GRDB can't infer one from the database
|
||||
/// schema. This happens when the schema does not define any foreign
|
||||
/// key to the destination table, or when the schema defines several
|
||||
/// foreign keys to the destination table.
|
||||
public static func belongsTo<Destination>(
|
||||
_ destination: Table<Destination>,
|
||||
key: String? = nil,
|
||||
using foreignKey: ForeignKey? = nil)
|
||||
-> BelongsToAssociation<Self, Destination>
|
||||
{
|
||||
BelongsToAssociation(
|
||||
to: destination.relationForAll,
|
||||
key: key,
|
||||
using: foreignKey)
|
||||
}
|
||||
|
||||
/// Creates a "Has many" association between Self and the destination table,
|
||||
/// based on a database foreign key.
|
||||
///
|
||||
/// For more information, see `TableRecord.hasMany(_:key:using:)` where
|
||||
/// the first argument is `TableRecord`.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - destination: The table at the other side of the association.
|
||||
/// - key: An eventual decoding key for the association. By default, it
|
||||
/// is `destination.tableName`.
|
||||
/// - foreignKey: An eventual foreign key. You need to provide an
|
||||
/// explicit foreign key when GRDB can't infer one from the database
|
||||
/// schema. This happens when the schema does not define any foreign
|
||||
/// key from the destination table, or when the schema defines several
|
||||
/// foreign keys from the destination table.
|
||||
public static func hasMany<Destination>(
|
||||
_ destination: Table<Destination>,
|
||||
key: String? = nil,
|
||||
using foreignKey: ForeignKey? = nil)
|
||||
-> HasManyAssociation<Self, Destination>
|
||||
{
|
||||
HasManyAssociation(
|
||||
to: destination.relationForAll,
|
||||
key: key,
|
||||
using: foreignKey)
|
||||
}
|
||||
|
||||
/// Creates a "Has one" association between Self and the destination table,
|
||||
/// based on a database foreign key.
|
||||
///
|
||||
/// For more information, see `TableRecord.hasOne(_:key:using:)` where
|
||||
/// the first argument is `TableRecord`.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - destination: The table at the other side of the association.
|
||||
/// - key: An eventual decoding key for the association. By default, it
|
||||
/// is `destination.databaseTableName`.
|
||||
/// - foreignKey: An eventual foreign key. You need to provide an
|
||||
/// explicit foreign key when GRDB can't infer one from the database
|
||||
/// schema. This happens when the schema does not define any foreign
|
||||
/// key from the destination table, or when the schema defines several
|
||||
/// foreign keys from the destination table.
|
||||
public static func hasOne<Destination>(
|
||||
_ destination: Table<Destination>,
|
||||
key: String? = nil,
|
||||
using foreignKey: ForeignKey? = nil)
|
||||
-> HasOneAssociation<Self, Destination>
|
||||
{
|
||||
HasOneAssociation(
|
||||
to: destination.relationForAll,
|
||||
key: key,
|
||||
using: foreignKey)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Associations to CommonTableExpression
|
||||
|
||||
extension TableRecord {
|
||||
@@ -351,7 +436,7 @@ extension TableRecord {
|
||||
Pivot.RowDecoder == Target.OriginRowDecoder
|
||||
{
|
||||
let association = HasManyThroughAssociation<Self, Target.RowDecoder>(
|
||||
sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation))
|
||||
_sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation))
|
||||
|
||||
if let key = key {
|
||||
return association.forKey(key)
|
||||
@@ -433,7 +518,7 @@ extension TableRecord {
|
||||
Pivot.RowDecoder == Target.OriginRowDecoder
|
||||
{
|
||||
let association = HasOneThroughAssociation<Self, Target.RowDecoder>(
|
||||
sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation))
|
||||
_sqlAssociation: target._sqlAssociation.through(pivot._sqlAssociation))
|
||||
|
||||
if let key = key {
|
||||
return association.forKey(key)
|
||||
@@ -471,14 +556,14 @@ extension TableRecord where Self: EncodableRecord {
|
||||
case let .foreignKey(foreignKey):
|
||||
let destinationRelation = association
|
||||
._sqlAssociation
|
||||
.map(\.pivot.relation, { pivotRelation in
|
||||
pivotRelation.filter { db in
|
||||
.with {
|
||||
$0.pivot.relation = $0.pivot.relation.filter { db in
|
||||
// Filter the pivot on self
|
||||
try foreignKey
|
||||
.joinMapping(db, from: Self.databaseTableName)
|
||||
.joinExpression(leftRows: [PersistenceContainer(db, self)])
|
||||
}
|
||||
})
|
||||
}
|
||||
.destinationRelation()
|
||||
return QueryInterfaceRequest(relation: destinationRelation)
|
||||
}
|
||||
@@ -544,7 +629,7 @@ extension TableRecord {
|
||||
///
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
|
||||
/// // FROM player LEFT JOIN book ...
|
||||
/// var request = Player.annotated(with: Player.books.count)
|
||||
/// let request = Player.annotated(with: Player.books.count)
|
||||
public static func annotated(with aggregates: AssociationAggregate<Self>...) -> QueryInterfaceRequest<Self> {
|
||||
all().annotated(with: aggregates)
|
||||
}
|
||||
@@ -553,7 +638,7 @@ extension TableRecord {
|
||||
///
|
||||
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
|
||||
/// // FROM player LEFT JOIN book ...
|
||||
/// var request = Player.annotated(with: [Player.books.count])
|
||||
/// let request = Player.annotated(with: [Player.books.count])
|
||||
public static func annotated(with aggregates: [AssociationAggregate<Self>]) -> QueryInterfaceRequest<Self> {
|
||||
all().annotated(with: aggregates)
|
||||
}
|
||||
|
||||
@@ -133,7 +133,7 @@ extension TableRecord {
|
||||
/// Creates a request which appends *selection*.
|
||||
///
|
||||
/// // SELECT id, email, name FROM player
|
||||
/// le request = Player
|
||||
/// let request = Player
|
||||
/// .select([Column("id"), Column("email")])
|
||||
/// .annotated(with: [Column("name")])
|
||||
public static func annotated(with selection: [SQLSelectable]) -> QueryInterfaceRequest<Self> {
|
||||
@@ -143,7 +143,7 @@ extension TableRecord {
|
||||
/// Creates a request which appends *selection*.
|
||||
///
|
||||
/// // SELECT id, email, name FROM player
|
||||
/// le request = Player
|
||||
/// let request = Player
|
||||
/// .select([Column("id"), Column("email")])
|
||||
/// .annotated(with: Column("name"))
|
||||
public static func annotated(with selection: SQLSelectable...) -> QueryInterfaceRequest<Self> {
|
||||
@@ -380,6 +380,14 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
|
||||
{
|
||||
all().filter(ids: ids)
|
||||
}
|
||||
|
||||
/// Creates a request which selects the primary key.
|
||||
///
|
||||
/// // SELECT id FROM player
|
||||
/// let request = try Player.selectID()
|
||||
public static func selectID() -> QueryInterfaceRequest<ID> {
|
||||
all().selectID()
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
|
||||
@@ -406,4 +414,12 @@ extension TableRecord where Self: Identifiable, ID: _OptionalProtocol, ID.Wrappe
|
||||
{
|
||||
all().filter(ids: ids)
|
||||
}
|
||||
|
||||
/// Creates a request which selects the primary key.
|
||||
///
|
||||
/// // SELECT id FROM player
|
||||
/// let request = try Player.selectID()
|
||||
public static func selectID() -> QueryInterfaceRequest<ID.Wrapped> {
|
||||
all().selectID()
|
||||
}
|
||||
}
|
||||
@@ -88,7 +88,7 @@ private class RecordEncoder<Record: EncodableRecord>: Encoder {
|
||||
func encodeIfPresent(_ value: Float?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
|
||||
func encodeIfPresent(_ value: Double?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
|
||||
func encodeIfPresent(_ value: String?, forKey key: Key) throws { recordEncoder.persist(value, forKey: key) }
|
||||
// swiftlint:disable comma
|
||||
// swiftlint:enable comma
|
||||
|
||||
func encodeIfPresent<T>(_ value: T?, forKey key: Key) throws where T: Encodable {
|
||||
if let value = value {
|
||||
@@ -182,20 +182,24 @@ private class ColumnEncoder<Record: EncodableRecord>: Encoder {
|
||||
}
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
|
||||
// Keyed values require JSON encoding: we need to throw
|
||||
// JSONRequiredError. Since we can't throw right from here, let's
|
||||
// delegate the job to a dedicated container.
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
// Unfortunately (bis), we can't throw right from here, so let's
|
||||
// return a JSONRequiredEncoder that will throw as soon as possible.
|
||||
requiresJSON = true
|
||||
let container = JSONRequiredEncoder<Record>.KeyedContainer<Key>(codingPath: codingPath)
|
||||
let container = JSONRequiredEncoder.KeyedContainer<Key>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer {
|
||||
// Keyed values require JSON encoding: we need to throw
|
||||
// JSONRequiredError. Since we can't throw right from here, let's
|
||||
// delegate the job to a dedicated container.
|
||||
// We need to perform JSON encoding. Unfortunately we can't access the
|
||||
// inner container of Foundation's JSONEncoder. At this point we must
|
||||
// throw an error so that the caller can retry encoding from scratch.
|
||||
// Unfortunately (bis), we can't throw right from here, so let's
|
||||
// return a JSONRequiredEncoder that will throw as soon as possible.
|
||||
requiresJSON = true
|
||||
return JSONRequiredEncoder<Record>(codingPath: codingPath)
|
||||
return JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer { self }
|
||||
@@ -224,105 +228,6 @@ extension ColumnEncoder: SingleValueEncodingContainer {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - JSONRequiredEncoder
|
||||
|
||||
/// The error that triggers JSON encoding
|
||||
private struct JSONRequiredError: Error { }
|
||||
|
||||
/// The encoder that always ends up with a JSONRequiredError
|
||||
private struct JSONRequiredEncoder<Record: EncodableRecord>: Encoder {
|
||||
var codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
|
||||
let container = KeyedContainer<Key>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func unkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
|
||||
func singleValueContainer() -> SingleValueEncodingContainer { self }
|
||||
|
||||
struct KeyedContainer<KeyType: CodingKey>: KeyedEncodingContainerProtocol {
|
||||
var codingPath: [CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
|
||||
|
||||
func encodeNil(forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Bool, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int8, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int16, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int32, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int64, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt8, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt16, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt32, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt64, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Float, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Double, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: String, forKey key: KeyType) throws { throw JSONRequiredError() }
|
||||
func encode<T>(_ value: T, forKey key: KeyType) throws where T: Encodable { throw JSONRequiredError() }
|
||||
|
||||
func nestedContainer<NestedKey>(
|
||||
keyedBy keyType: NestedKey.Type,
|
||||
forKey key: KeyType)
|
||||
-> KeyedEncodingContainer<NestedKey>
|
||||
where NestedKey: CodingKey
|
||||
{
|
||||
let container = KeyedContainer<NestedKey>(codingPath: codingPath + [key])
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
func nestedUnkeyedContainer(forKey key: KeyType) -> UnkeyedEncodingContainer {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder() -> Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
|
||||
func superEncoder(forKey key: KeyType) -> Encoder {
|
||||
JSONRequiredEncoder(codingPath: codingPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension JSONRequiredEncoder: SingleValueEncodingContainer {
|
||||
func encodeNil() throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Bool ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int8 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int16 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int32 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Int64 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt8 ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt16) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt32) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: UInt64) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Float ) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: Double) throws { throw JSONRequiredError() }
|
||||
func encode(_ value: String) throws { throw JSONRequiredError() }
|
||||
func encode<T>(_ value: T) throws where T: Encodable { throw JSONRequiredError() }
|
||||
}
|
||||
|
||||
extension JSONRequiredEncoder: UnkeyedEncodingContainer {
|
||||
var count: Int { 0 }
|
||||
|
||||
mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type)
|
||||
-> KeyedEncodingContainer<NestedKey>
|
||||
where NestedKey: CodingKey
|
||||
{
|
||||
let container = KeyedContainer<NestedKey>(codingPath: codingPath)
|
||||
return KeyedEncodingContainer(container)
|
||||
}
|
||||
|
||||
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { self }
|
||||
|
||||
mutating func superEncoder() -> Encoder { self }
|
||||
}
|
||||
|
||||
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
|
||||
private var iso8601Formatter: ISO8601DateFormatter = {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
|
||||
@@ -396,9 +396,6 @@ extension ColumnDecoder: SingleValueDecodingContainer {
|
||||
}
|
||||
}
|
||||
|
||||
/// The error that triggers JSON decoding
|
||||
private struct JSONRequiredError: Error { }
|
||||
|
||||
@available(macOS 10.12, watchOS 3.0, tvOS 10.0, *)
|
||||
private var iso8601Formatter: ISO8601DateFormatter = {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
|
||||
@@ -45,7 +45,7 @@ extension FetchableRecord where Self: TableRecord {
|
||||
|
||||
/// The first found record.
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// // SELECT * FROM player LIMIT 1
|
||||
/// let player = try Player.fetchOne(db) // Player?
|
||||
///
|
||||
/// The selection defaults to all columns. This default can be changed for
|
||||
|
||||
@@ -12,7 +12,7 @@ import Foundation
|
||||
/// try Player.fetchAll(db, sql: "SELECT ...", arguments:...) // [Player]
|
||||
/// try Player.fetchOne(db, sql: "SELECT ...", arguments:...) // Player?
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT ...")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT ...")
|
||||
/// try Player.fetchCursor(statement, arguments:...) // Cursor of Player
|
||||
/// try Player.fetchAll(statement, arguments:...) // [Player]
|
||||
/// try Player.fetchOne(statement, arguments:...) // Player?
|
||||
@@ -131,11 +131,11 @@ extension FetchableRecord {
|
||||
|
||||
extension FetchableRecord {
|
||||
|
||||
// MARK: Fetching From SelectStatement
|
||||
// MARK: Fetching From Prepared Statement
|
||||
|
||||
/// A cursor over records fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player")
|
||||
/// let players = try Player.fetchCursor(statement) // Cursor of Player
|
||||
/// while let player = try players.next() { // Player
|
||||
/// ...
|
||||
@@ -153,7 +153,7 @@ extension FetchableRecord {
|
||||
/// - returns: A cursor over fetched records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> RecordCursor<Self>
|
||||
@@ -163,7 +163,7 @@ extension FetchableRecord {
|
||||
|
||||
/// Returns an array of records fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player")
|
||||
/// let players = try Player.fetchAll(statement) // [Player]
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -173,7 +173,7 @@ extension FetchableRecord {
|
||||
/// - returns: An array of records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Self]
|
||||
@@ -183,7 +183,7 @@ extension FetchableRecord {
|
||||
|
||||
/// Returns a single record fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player")
|
||||
/// let player = try Player.fetchOne(statement) // Player?
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -193,7 +193,7 @@ extension FetchableRecord {
|
||||
/// - returns: An optional record.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Self?
|
||||
@@ -205,7 +205,7 @@ extension FetchableRecord {
|
||||
extension FetchableRecord where Self: Hashable {
|
||||
/// Returns a set of records fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player")
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player")
|
||||
/// let players = try Player.fetchSet(statement) // Set<Player>
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -215,7 +215,7 @@ extension FetchableRecord where Self: Hashable {
|
||||
/// - returns: A set of records.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: SelectStatement,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Self>
|
||||
@@ -494,22 +494,29 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable {
|
||||
/// let players: RecordCursor<Player> = try Player.fetchCursor(db, sql: "SELECT * FROM player")
|
||||
/// }
|
||||
public final class RecordCursor<Record: FetchableRecord>: Cursor {
|
||||
@usableFromInline let _statement: SelectStatement
|
||||
@usableFromInline enum _State {
|
||||
case idle, busy, done, failed
|
||||
}
|
||||
|
||||
@usableFromInline let _statement: Statement
|
||||
@usableFromInline let _row: Row // Reused for performance
|
||||
@usableFromInline let _sqliteStatement: SQLiteStatement
|
||||
@usableFromInline var _done = false
|
||||
@usableFromInline var _state = _State.idle
|
||||
|
||||
init(statement: SelectStatement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
_statement = statement
|
||||
_row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
_sqliteStatement = statement.sqliteStatement
|
||||
_statement.reset(withArguments: arguments)
|
||||
|
||||
// Assume cursor is created for iteration
|
||||
try statement.database.selectStatementWillExecute(statement)
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
if _state == .busy {
|
||||
try? _statement.database.statementDidExecute(_statement)
|
||||
}
|
||||
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? _statement.reset()
|
||||
@@ -517,19 +524,34 @@ public final class RecordCursor<Record: FetchableRecord>: Cursor {
|
||||
|
||||
@inlinable
|
||||
public func next() throws -> Record? {
|
||||
if _done {
|
||||
switch _state {
|
||||
case .done:
|
||||
// make sure this instance never yields a value again, even if the
|
||||
// statement is reset by another cursor.
|
||||
return nil
|
||||
case .idle:
|
||||
guard try _statement.database.statementWillExecute(_statement) == nil else {
|
||||
throw DatabaseError(
|
||||
resultCode: SQLITE_MISUSE,
|
||||
message: "Can't run statement that requires a customized authorizer from a cursor",
|
||||
sql: _statement.sql,
|
||||
arguments: _statement.arguments)
|
||||
}
|
||||
_state = .busy
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
switch sqlite3_step(_sqliteStatement) {
|
||||
case SQLITE_DONE:
|
||||
_done = true
|
||||
_state = .done
|
||||
try _statement.database.statementDidExecute(_statement)
|
||||
return nil
|
||||
case SQLITE_ROW:
|
||||
return Record(row: _row)
|
||||
case let code:
|
||||
try _statement.didFail(withResultCode: code)
|
||||
_state = .failed
|
||||
try _statement.database.statementDidFail(_statement, withResultCode: code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ extension PersistenceError {
|
||||
///
|
||||
/// See `MutablePersistableRecord.persistenceConflictPolicy`.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_conflict.html
|
||||
/// See <https://www.sqlite.org/lang_conflict.html>
|
||||
public struct PersistenceConflictPolicy {
|
||||
/// The conflict resolution algorithm for insertions
|
||||
public let conflictResolutionForInsert: Database.ConflictResolution
|
||||
@@ -67,7 +67,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord {
|
||||
/// `didInsert(with:for:)` method is not called upon successful insertion,
|
||||
/// even if a row was actually inserted without any conflict.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_conflict.html
|
||||
/// See <https://www.sqlite.org/lang_conflict.html>
|
||||
static var persistenceConflictPolicy: PersistenceConflictPolicy { get }
|
||||
|
||||
/// Notifies the record that it was successfully inserted.
|
||||
@@ -504,305 +504,6 @@ extension MutablePersistableRecord where Self: AnyObject {
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistableRecord {
|
||||
|
||||
// MARK: Batch Delete
|
||||
|
||||
/// Deletes all records; returns the number of deleted rows.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: The number of deleted rows
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database) throws -> Int {
|
||||
try all().deleteAll(db)
|
||||
}
|
||||
|
||||
// MARK: Batch Update
|
||||
|
||||
/// Updates all records; returns the number of updated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = 0
|
||||
/// try Player.updateAll(db, [Column("score").set(to: 0)])
|
||||
/// }
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution,
|
||||
/// defaulting to the record's persistenceConflictPolicy.
|
||||
/// - parameter assignments: An array of column assignments.
|
||||
/// - returns: The number of updated rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public static func updateAll(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
_ assignments: [ColumnAssignment])
|
||||
throws -> Int
|
||||
{
|
||||
try all().updateAll(db, onConflict: conflictResolution, assignments)
|
||||
}
|
||||
|
||||
/// Updates all records; returns the number of updated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = 0
|
||||
/// try Player.updateAll(db, Column("score").set(to: 0))
|
||||
/// }
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution,
|
||||
/// defaulting to the record's persistenceConflictPolicy.
|
||||
/// - parameter assignment: A column assignment.
|
||||
/// - parameter otherAssignments: Eventual other column assignments.
|
||||
/// - returns: The number of updated rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public static func updateAll(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
_ assignment: ColumnAssignment,
|
||||
_ otherAssignments: ColumnAssignment...)
|
||||
throws -> Int
|
||||
{
|
||||
try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments)
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistableRecord {
|
||||
|
||||
// MARK: - Deleting by Single-Column Primary Key
|
||||
|
||||
/// Delete records identified by their primary keys; returns the number of
|
||||
/// deleted rows.
|
||||
///
|
||||
/// // DELETE FROM player WHERE id IN (1, 2, 3)
|
||||
/// try Player.deleteAll(db, keys: [1, 2, 3])
|
||||
///
|
||||
/// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE')
|
||||
/// try Country.deleteAll(db, keys: ["FR", "US", "DE"])
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM document WHERE rowid IN (1, 2, 3)
|
||||
/// try Document.deleteAll(db, keys: [1, 2, 3])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll<Sequence>(_ db: Database, keys: Sequence)
|
||||
throws -> Int
|
||||
where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible
|
||||
{
|
||||
let keys = Array(keys)
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by its primary key; returns whether a
|
||||
/// database row was deleted.
|
||||
///
|
||||
/// // DELETE FROM player WHERE id = 123
|
||||
/// try Player.deleteOne(db, key: 123)
|
||||
///
|
||||
/// // DELETE FROM country WHERE code = 'FR'
|
||||
/// try Country.deleteOne(db, key: "FR")
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM document WHERE rowid = 1
|
||||
/// try Document.deleteOne(db, key: 1)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A primary key value.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne<PrimaryKeyType>(_ db: Database, key: PrimaryKeyType?)
|
||||
throws -> Bool
|
||||
where PrimaryKeyType: DatabaseValueConvertible
|
||||
{
|
||||
guard let key = key else {
|
||||
// Avoid hitting the database
|
||||
return false
|
||||
}
|
||||
return try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
|
||||
extension MutablePersistableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
|
||||
|
||||
// MARK: - Deleting by Single-Column Primary Key
|
||||
|
||||
/// Delete records identified by their primary keys; returns the number of
|
||||
/// deleted rows.
|
||||
///
|
||||
/// // DELETE FROM player WHERE id IN (1, 2, 3)
|
||||
/// try Player.deleteAll(db, ids: [1, 2, 3])
|
||||
///
|
||||
/// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE')
|
||||
/// try Country.deleteAll(db, ids: ["FR", "US", "DE"])
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM document WHERE rowid IN (1, 2, 3)
|
||||
/// try Document.deleteAll(db, ids: [1, 2, 3])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - ids: A collection of primary keys.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll<Collection>(_ db: Database, ids: Collection)
|
||||
throws -> Int
|
||||
where Collection: Swift.Collection, Collection.Element == ID
|
||||
{
|
||||
if ids.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(ids: ids).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by its primary key; returns whether a
|
||||
/// database row was deleted.
|
||||
///
|
||||
/// // DELETE FROM player WHERE id = 123
|
||||
/// try Player.deleteOne(db, key: 123)
|
||||
///
|
||||
/// // DELETE FROM country WHERE code = 'FR'
|
||||
/// try Country.deleteOne(db, key: "FR")
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM document WHERE rowid = 1
|
||||
/// try Document.deleteOne(db, key: 1)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - id: A primary key value.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne(_ db: Database, id: ID) throws -> Bool {
|
||||
try deleteAll(db, ids: [id]) > 0
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
|
||||
extension MutablePersistableRecord
|
||||
where Self: Identifiable,
|
||||
ID: _OptionalProtocol,
|
||||
ID.Wrapped: DatabaseValueConvertible
|
||||
{
|
||||
// MARK: - Deleting by Single-Column Primary Key
|
||||
|
||||
/// Delete records identified by their primary keys; returns the number of
|
||||
/// deleted rows.
|
||||
///
|
||||
/// // DELETE FROM player WHERE id IN (1, 2, 3)
|
||||
/// try Player.deleteAll(db, ids: [1, 2, 3])
|
||||
///
|
||||
/// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE')
|
||||
/// try Country.deleteAll(db, ids: ["FR", "US", "DE"])
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM document WHERE rowid IN (1, 2, 3)
|
||||
/// try Document.deleteAll(db, ids: [1, 2, 3])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - ids: A collection of primary keys.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll<Collection>(_ db: Database, ids: Collection)
|
||||
throws -> Int
|
||||
where Collection: Swift.Collection, Collection.Element == ID.Wrapped
|
||||
{
|
||||
if ids.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(ids: ids).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by its primary key; returns whether a
|
||||
/// database row was deleted.
|
||||
///
|
||||
/// // DELETE FROM player WHERE id = 123
|
||||
/// try Player.deleteOne(db, key: 123)
|
||||
///
|
||||
/// // DELETE FROM country WHERE code = 'FR'
|
||||
/// try Country.deleteOne(db, key: "FR")
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM document WHERE rowid = 1
|
||||
/// try Document.deleteOne(db, key: 1)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - id: A primary key value.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne(_ db: Database, id: ID.Wrapped) throws -> Bool {
|
||||
try deleteAll(db, ids: [id]) > 0
|
||||
}
|
||||
}
|
||||
|
||||
extension MutablePersistableRecord {
|
||||
|
||||
// MARK: - Deleting by Key
|
||||
|
||||
/// Delete records identified by the provided unique keys (primary key or
|
||||
/// any key with a unique index on it); returns the number of deleted rows.
|
||||
///
|
||||
/// try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - keys: An array of key dictionaries.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int {
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by a unique key (the primary key or any key
|
||||
/// with a unique index on it); returns whether a database row was deleted.
|
||||
///
|
||||
/// Player.deleteOne(db, key: ["name": Arthur"])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A dictionary of values.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool {
|
||||
try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - PersistableRecord
|
||||
|
||||
/// Types that adopt `PersistableRecord` can be inserted, updated, and deleted.
|
||||
@@ -976,19 +677,19 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
func insertStatement(onConflict: Database.ConflictResolution) throws -> UpdateStatement {
|
||||
func insertStatement(onConflict: Database.ConflictResolution) throws -> Statement {
|
||||
let query = InsertQuery(
|
||||
onConflict: onConflict,
|
||||
tableName: databaseTableName,
|
||||
insertedColumns: persistenceContainer.columns)
|
||||
let statement = try db.internalCachedUpdateStatement(sql: query.sql)
|
||||
let statement = try db.internalCachedStatement(sql: query.sql)
|
||||
statement.setUncheckedArguments(StatementArguments(persistenceContainer.values))
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns nil if and only if primary key is nil
|
||||
@usableFromInline
|
||||
func updateStatement(columns: Set<String>, onConflict: Database.ConflictResolution) throws -> UpdateStatement? {
|
||||
func updateStatement(columns: Set<String>, onConflict: Database.ConflictResolution) throws -> Statement? {
|
||||
// Fail early if primary key does not resolve to a database row.
|
||||
let primaryKeyColumns = primaryKey.columns
|
||||
let primaryKeyValues = primaryKeyColumns.map {
|
||||
@@ -1031,14 +732,14 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
tableName: databaseTableName,
|
||||
updatedColumns: updatedColumns,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
let statement = try db.internalCachedUpdateStatement(sql: query.sql)
|
||||
let statement = try db.internalCachedStatement(sql: query.sql)
|
||||
statement.setUncheckedArguments(StatementArguments(updatedValues + primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns nil if and only if primary key is nil
|
||||
@usableFromInline
|
||||
func deleteStatement() throws -> UpdateStatement? {
|
||||
func deleteStatement() throws -> Statement? {
|
||||
// Fail early if primary key does not resolve to a database row.
|
||||
let primaryKeyColumns = primaryKey.columns
|
||||
let primaryKeyValues = primaryKeyColumns.map {
|
||||
@@ -1051,14 +752,14 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
let query = DeleteQuery(
|
||||
tableName: databaseTableName,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
let statement = try db.internalCachedUpdateStatement(sql: query.sql)
|
||||
let statement = try db.internalCachedStatement(sql: query.sql)
|
||||
statement.setUncheckedArguments(StatementArguments(primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns nil if and only if primary key is nil
|
||||
@usableFromInline
|
||||
func existsStatement() throws -> SelectStatement? {
|
||||
func existsStatement() throws -> Statement? {
|
||||
// Fail early if primary key does not resolve to a database row.
|
||||
let primaryKeyColumns = primaryKey.columns
|
||||
let primaryKeyValues = primaryKeyColumns.map {
|
||||
@@ -1071,7 +772,7 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
let query = ExistsQuery(
|
||||
tableName: databaseTableName,
|
||||
conditionColumns: primaryKeyColumns)
|
||||
let statement = try db.internalCachedSelectStatement(sql: query.sql)
|
||||
let statement = try db.internalCachedStatement(sql: query.sql)
|
||||
statement.setUncheckedArguments(StatementArguments(primaryKeyValues))
|
||||
return statement
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord {
|
||||
/// `didInsert(with:for:)` method is not called upon successful insertion,
|
||||
/// even if a row was actually inserted without any conflict.
|
||||
///
|
||||
/// See https://www.sqlite.org/lang_conflict.html
|
||||
/// See <https://www.sqlite.org/lang_conflict.html>
|
||||
open class var persistenceConflictPolicy: PersistenceConflictPolicy {
|
||||
PersistenceConflictPolicy(insert: .abort, update: .abort)
|
||||
}
|
||||
|
||||
@@ -140,6 +140,302 @@ extension TableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Batch Delete
|
||||
|
||||
extension TableRecord {
|
||||
|
||||
/// Deletes all records; returns the number of deleted rows.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: The number of deleted rows
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database) throws -> Int {
|
||||
try all().deleteAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Deleting by Single-Column Primary Key
|
||||
|
||||
extension TableRecord {
|
||||
|
||||
/// Delete records identified by their primary keys; returns the number of
|
||||
/// deleted rows.
|
||||
///
|
||||
/// // DELETE FROM player WHERE id IN (1, 2, 3)
|
||||
/// try Player.deleteAll(db, keys: [1, 2, 3])
|
||||
///
|
||||
/// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE')
|
||||
/// try Country.deleteAll(db, keys: ["FR", "US", "DE"])
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM document WHERE rowid IN (1, 2, 3)
|
||||
/// try Document.deleteAll(db, keys: [1, 2, 3])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - keys: A sequence of primary keys.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll<Sequence>(_ db: Database, keys: Sequence)
|
||||
throws -> Int
|
||||
where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible
|
||||
{
|
||||
let keys = Array(keys)
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by its primary key; returns whether a
|
||||
/// database row was deleted.
|
||||
///
|
||||
/// // DELETE FROM player WHERE id = 123
|
||||
/// try Player.deleteOne(db, key: 123)
|
||||
///
|
||||
/// // DELETE FROM country WHERE code = 'FR'
|
||||
/// try Country.deleteOne(db, key: "FR")
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM document WHERE rowid = 1
|
||||
/// try Document.deleteOne(db, key: 1)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A primary key value.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne<PrimaryKeyType>(_ db: Database, key: PrimaryKeyType?)
|
||||
throws -> Bool
|
||||
where PrimaryKeyType: DatabaseValueConvertible
|
||||
{
|
||||
guard let key = key else {
|
||||
// Avoid hitting the database
|
||||
return false
|
||||
}
|
||||
return try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
|
||||
extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible {
|
||||
/// Delete records identified by their primary keys; returns the number of
|
||||
/// deleted rows.
|
||||
///
|
||||
/// // DELETE FROM player WHERE id IN (1, 2, 3)
|
||||
/// try Player.deleteAll(db, ids: [1, 2, 3])
|
||||
///
|
||||
/// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE')
|
||||
/// try Country.deleteAll(db, ids: ["FR", "US", "DE"])
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM document WHERE rowid IN (1, 2, 3)
|
||||
/// try Document.deleteAll(db, ids: [1, 2, 3])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - ids: A collection of primary keys.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll<Collection>(_ db: Database, ids: Collection)
|
||||
throws -> Int
|
||||
where Collection: Swift.Collection, Collection.Element == ID
|
||||
{
|
||||
if ids.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(ids: ids).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by its primary key; returns whether a
|
||||
/// database row was deleted.
|
||||
///
|
||||
/// // DELETE FROM player WHERE id = 123
|
||||
/// try Player.deleteOne(db, id: 123)
|
||||
///
|
||||
/// // DELETE FROM country WHERE code = 'FR'
|
||||
/// try Country.deleteOne(db, id: "FR")
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM document WHERE rowid = 1
|
||||
/// try Document.deleteOne(db, id: 1)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - id: A primary key value.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne(_ db: Database, id: ID) throws -> Bool {
|
||||
try deleteAll(db, ids: [id]) > 0
|
||||
}
|
||||
}
|
||||
|
||||
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
|
||||
extension TableRecord
|
||||
where Self: Identifiable,
|
||||
ID: _OptionalProtocol,
|
||||
ID.Wrapped: DatabaseValueConvertible
|
||||
{
|
||||
/// Delete records identified by their primary keys; returns the number of
|
||||
/// deleted rows.
|
||||
///
|
||||
/// // DELETE FROM player WHERE id IN (1, 2, 3)
|
||||
/// try Player.deleteAll(db, ids: [1, 2, 3])
|
||||
///
|
||||
/// // DELETE FROM country WHERE code IN ('FR', 'US', 'DE')
|
||||
/// try Country.deleteAll(db, ids: ["FR", "US", "DE"])
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM document WHERE rowid IN (1, 2, 3)
|
||||
/// try Document.deleteAll(db, ids: [1, 2, 3])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - ids: A collection of primary keys.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll<Collection>(_ db: Database, ids: Collection)
|
||||
throws -> Int
|
||||
where Collection: Swift.Collection, Collection.Element == ID.Wrapped
|
||||
{
|
||||
if ids.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(ids: ids).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by its primary key; returns whether a
|
||||
/// database row was deleted.
|
||||
///
|
||||
/// // DELETE FROM player WHERE id = 123
|
||||
/// try Player.deleteOne(db, id: 123)
|
||||
///
|
||||
/// // DELETE FROM country WHERE code = 'FR'
|
||||
/// try Country.deleteOne(db, id: "FR")
|
||||
///
|
||||
/// When the table has no explicit primary key, GRDB uses the hidden
|
||||
/// "rowid" column:
|
||||
///
|
||||
/// // DELETE FROM document WHERE rowid = 1
|
||||
/// try Document.deleteOne(db, id: 1)
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - id: A primary key value.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne(_ db: Database, id: ID.Wrapped) throws -> Bool {
|
||||
try deleteAll(db, ids: [id]) > 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Deleting by Key
|
||||
|
||||
extension TableRecord {
|
||||
/// Delete records identified by the provided unique keys (primary key or
|
||||
/// any key with a unique index on it); returns the number of deleted rows.
|
||||
///
|
||||
/// try Player.deleteAll(db, keys: [["email": "a@example.com"], ["email": "b@example.com"]])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - keys: An array of key dictionaries.
|
||||
/// - returns: The number of deleted rows
|
||||
@discardableResult
|
||||
public static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int {
|
||||
if keys.isEmpty {
|
||||
// Avoid hitting the database
|
||||
return 0
|
||||
}
|
||||
return try filter(keys: keys).deleteAll(db)
|
||||
}
|
||||
|
||||
/// Delete a record, identified by a unique key (the primary key or any key
|
||||
/// with a unique index on it); returns whether a database row was deleted.
|
||||
///
|
||||
/// Player.deleteOne(db, key: ["name": Arthur"])
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - key: A dictionary of values.
|
||||
/// - returns: Whether a database row was deleted.
|
||||
@discardableResult
|
||||
public static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool {
|
||||
try deleteAll(db, keys: [key]) > 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Batch Update
|
||||
|
||||
extension TableRecord {
|
||||
|
||||
/// Updates all records; returns the number of updated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = 0
|
||||
/// try Player.updateAll(db, [Column("score").set(to: 0)])
|
||||
/// }
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution,
|
||||
/// defaulting to the record's persistenceConflictPolicy.
|
||||
/// - parameter assignments: An array of column assignments.
|
||||
/// - returns: The number of updated rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public static func updateAll(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
_ assignments: [ColumnAssignment])
|
||||
throws -> Int
|
||||
{
|
||||
try all().updateAll(db, onConflict: conflictResolution, assignments)
|
||||
}
|
||||
|
||||
/// Updates all records; returns the number of updated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = 0
|
||||
/// try Player.updateAll(db, Column("score").set(to: 0))
|
||||
/// }
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution,
|
||||
/// defaulting to the record's persistenceConflictPolicy.
|
||||
/// - parameter assignment: A column assignment.
|
||||
/// - parameter otherAssignments: Eventual other column assignments.
|
||||
/// - returns: The number of updated rows.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public static func updateAll(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
_ assignment: ColumnAssignment,
|
||||
_ otherAssignments: ColumnAssignment...)
|
||||
throws -> Int
|
||||
{
|
||||
try updateAll(db, onConflict: conflictResolution, [assignment] + otherAssignments)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -1,44 +1,19 @@
|
||||
/// A case-preserving, case-insensitive identifier
|
||||
/// that matches the ASCII version of sqlite3_stricmp
|
||||
struct CaseInsensitiveIdentifier: Hashable {
|
||||
var rawValue: String
|
||||
private let lowercased: String
|
||||
let rawValue: String
|
||||
|
||||
init(rawValue: String) {
|
||||
self.lowercased = rawValue.lowercased()
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
static func == (lhs: CaseInsensitiveIdentifier, rhs: CaseInsensitiveIdentifier) -> Bool {
|
||||
guard lhs.rawValue.utf8.count == rhs.rawValue.utf8.count else { return false }
|
||||
for (l, r) in zip(lhs.rawValue.utf8, rhs.rawValue.utf8)
|
||||
where upperToLower[Int(l)] != upperToLower[Int(r)] {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
lhs.lowercased == rhs.lowercased
|
||||
}
|
||||
|
||||
func hash(into hasher: inout Hasher) {
|
||||
for c in rawValue.utf8 {
|
||||
hasher.combine(upperToLower[Int(c)])
|
||||
}
|
||||
hasher.combine(lowercased)
|
||||
}
|
||||
}
|
||||
|
||||
// swiftlint:disable comma
|
||||
/// The same table as SQLite
|
||||
private let upperToLower: [UTF8.CodeUnit] = [
|
||||
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
|
||||
18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
|
||||
36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
|
||||
54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
|
||||
104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
|
||||
122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
|
||||
108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
|
||||
126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
|
||||
144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
|
||||
162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
|
||||
180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
|
||||
198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
|
||||
216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
|
||||
234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
|
||||
252,253,254,255
|
||||
]
|
||||
@@ -10,7 +10,7 @@ import Foundation
|
||||
///
|
||||
/// This scheduling guarantee is used by GRDB in order to be able
|
||||
/// to make promises on the scheduling of database values without surprising
|
||||
/// the users as in https://forums.swift.org/t/28631.
|
||||
/// the users as in <https://forums.swift.org/t/28631>.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
struct ReceiveValuesOn<Upstream: Publisher, Context: Scheduler>: Publisher {
|
||||
typealias Output = Upstream.Output
|
||||
|
||||
@@ -10,13 +10,14 @@
|
||||
/// extension Player: Refinable { }
|
||||
///
|
||||
/// let player = Player(name: "Arthur", score: 1000)
|
||||
/// player.with { $0.score = 100 } // Player(name: "Arthur", score: 100)
|
||||
/// player.with(\.score, 100) // Player(name: "Arthur", score: 100)
|
||||
/// player.map(\.score) { $0 + 100 } // Player(name: "Arthur", score: 1100)
|
||||
///
|
||||
/// // Player(name: "Arthur", score: 100)
|
||||
/// let newPlayer = player.with {
|
||||
/// $0.score = 100
|
||||
/// }
|
||||
protocol Refinable { }
|
||||
|
||||
extension Refinable {
|
||||
|
||||
/// Returns self modified with the *update* function.
|
||||
///
|
||||
/// For example:
|
||||
@@ -33,49 +34,4 @@ extension Refinable {
|
||||
try update(&result)
|
||||
return result
|
||||
}
|
||||
|
||||
/// Returns self with the given value set on the given key path.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let player = Player(name: "Arthur", score: 1000)
|
||||
/// let newPlayer = player.with(\.score, 1100)
|
||||
/// newPlayer.name // "Arthur"
|
||||
/// newPlayer.score // 1100
|
||||
@inline(__always)
|
||||
func with<T>(_ keyPath: WritableKeyPath<Self, T>, _ value: T) -> Self {
|
||||
with { $0[keyPath: keyPath] = value }
|
||||
}
|
||||
|
||||
/// Returns self with the given transform function applied to the given key path.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let player = Player(name: "Arthur", score: 1000)
|
||||
/// let newPlayer = player.map(\.score) { $0 + 100 }
|
||||
/// newPlayer.name // "Arthur"
|
||||
/// newPlayer.score // 1100
|
||||
@inline(__always)
|
||||
func map<T>(_ keyPath: WritableKeyPath<Self, T>, _ transform: (T) throws -> T) rethrows -> Self {
|
||||
try with {
|
||||
$0[keyPath: keyPath] = try transform($0[keyPath: keyPath])
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns self with the given update function applied to the given key path.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let player = Player(name: "Arthur", scores: [100, 10])
|
||||
/// let newPlayer = player.mapInto(\.scores) { $0.append(1000) }
|
||||
/// newPlayer.name // "Arthur"
|
||||
/// newPlayer.scores // [100, 10, 1000]
|
||||
@inline(__always)
|
||||
func mapInto<T>(_ keyPath: WritableKeyPath<Self, T>, _ update: (inout T) throws -> Void) rethrows -> Self {
|
||||
try with {
|
||||
try update(&$0[keyPath: keyPath])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Array: Refinable where Element: Refinable { }
|
||||
@@ -8,7 +8,7 @@ extension String {
|
||||
///
|
||||
/// db.execute(sql: "SELECT * FROM \(tableName.quotedDatabaseIdentifier)")
|
||||
@inlinable public var quotedDatabaseIdentifier: String {
|
||||
// See https://www.sqlite.org/lang_keywords.html
|
||||
// See <https://www.sqlite.org/lang_keywords.html>
|
||||
return "\"\(self)\""
|
||||
}
|
||||
}
|
||||
@@ -45,8 +45,8 @@ func GRDBPrecondition(
|
||||
line: UInt = #line)
|
||||
{
|
||||
/// Custom precondition function which aims at solving
|
||||
/// https://bugs.swift.org/browse/SR-905 and
|
||||
/// https://github.com/groue/GRDB.swift/issues/37
|
||||
/// <https://bugs.swift.org/browse/SR-905> and
|
||||
/// <https://github.com/groue/GRDB.swift/issues/37>
|
||||
if !condition() {
|
||||
fatalError(message(), file: file, line: line)
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ public struct ValueObservation<Reducer: ValueReducer> {
|
||||
///
|
||||
/// Don't set this flag to true unless you really need it. A read/write
|
||||
/// observation is less efficient than a read-only observation.
|
||||
public var requiresWriteAccess: Bool = false
|
||||
public var requiresWriteAccess = false
|
||||
|
||||
/// Returns a ValueObservation with a transformed reducer.
|
||||
func mapReducer<R>(_ transform: @escaping (Reducer) -> R) -> ValueObservation<R> {
|
||||
@@ -103,8 +103,8 @@ extension ValueObservation: Refinable {
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Reducer.Value) -> Void) -> DatabaseCancellable
|
||||
{
|
||||
let observation = map(\.events) { events in
|
||||
events.map(\.didFail) { concat($0, onError) }
|
||||
let observation = self.with {
|
||||
$0.events.didFail = concat($0.events.didFail, onError)
|
||||
}
|
||||
observation.events.willStart?()
|
||||
return reader._add(
|
||||
@@ -157,14 +157,13 @@ extension ValueObservation: Refinable {
|
||||
// the type of the value may change with the `map` operator.
|
||||
didReceiveValue: didReceiveValue ?? { _ in })
|
||||
})
|
||||
.map(\.events, { events in
|
||||
events
|
||||
.map(\.willStart) { concat($0, willStart) }
|
||||
.map(\.willTrackRegion) { concat($0, willTrackRegion) }
|
||||
.map(\.databaseDidChange) { concat($0, databaseDidChange) }
|
||||
.map(\.didFail) { concat($0, didFail) }
|
||||
.map(\.didCancel) { concat($0, didCancel) }
|
||||
})
|
||||
.with {
|
||||
$0.events.willStart = concat($0.events.willStart, willStart)
|
||||
$0.events.willTrackRegion = concat($0.events.willTrackRegion, willTrackRegion)
|
||||
$0.events.databaseDidChange = concat($0.events.databaseDidChange, databaseDidChange)
|
||||
$0.events.didFail = concat($0.events.didFail, didFail)
|
||||
$0.events.didCancel = concat($0.events.didCancel, didCancel)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints log messages for all ValueObservation events.
|
||||
@@ -173,16 +172,31 @@ extension ValueObservation: Refinable {
|
||||
to stream: TextOutputStream? = nil)
|
||||
-> ValueObservation<ValueReducers.Trace<Reducer>>
|
||||
{
|
||||
let lock = NSLock()
|
||||
let prefix = prefix.isEmpty ? "" : "\(prefix): "
|
||||
var stream = stream ?? PrintOutputStream()
|
||||
return handleEvents(
|
||||
willStart: { stream.write("\(prefix)start") },
|
||||
willFetch: { stream.write("\(prefix)fetch") },
|
||||
willTrackRegion: { stream.write("\(prefix)tracked region: \($0)") },
|
||||
databaseDidChange: { stream.write("\(prefix)database did change") },
|
||||
didReceiveValue: { stream.write("\(prefix)value: \($0)") },
|
||||
didFail: { stream.write("\(prefix)failure: \($0)") },
|
||||
didCancel: { stream.write("\(prefix)cancel") })
|
||||
willStart: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)start") },
|
||||
willFetch: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)fetch") },
|
||||
willTrackRegion: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)tracked region: \($0)") },
|
||||
databaseDidChange: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)database did change") },
|
||||
didReceiveValue: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)value: \($0)") },
|
||||
didFail: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)failure: \($0)") },
|
||||
didCancel: {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
stream.write("\(prefix)cancel") })
|
||||
}
|
||||
|
||||
// MARK: - Fetching Values
|
||||
|
||||
@@ -23,7 +23,7 @@ final class ValueObserver<Reducer: ValueReducer> {
|
||||
private let reduceQueue: DispatchQueue
|
||||
private var isChanged = false
|
||||
private let onChange: (Reducer.Value) -> Void
|
||||
private var lock = NSRecursiveLock() // protects _isCompleted
|
||||
private var lock = NSRecursiveLock() // protects _isCompleted and reducer
|
||||
|
||||
init(
|
||||
events: ValueObservationEvents,
|
||||
@@ -94,13 +94,15 @@ extension ValueObserver: TransactionObserver {
|
||||
// Synchronously
|
||||
fetchedFuture = DatabaseFuture(Result {
|
||||
try recordingSelectedRegionIfNeeded(db) {
|
||||
try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
try synchronized {
|
||||
try reducer.fetch(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
}
|
||||
})
|
||||
} else {
|
||||
// Concurrently
|
||||
guard let writer = writer else { return }
|
||||
fetchedFuture = writer.concurrentRead(reducer._fetch)
|
||||
fetchedFuture = writer.concurrentRead { db in try self.synchronized { try self.reducer._fetch(db) } }
|
||||
}
|
||||
|
||||
// 2. Reduce
|
||||
@@ -113,7 +115,7 @@ extension ValueObserver: TransactionObserver {
|
||||
if self.isCompleted { return }
|
||||
do {
|
||||
let fetchedValue = try fetchedFuture.wait()
|
||||
if let value = self.reducer._value(fetchedValue) {
|
||||
if let value = self.synchronized({ self.reducer._value(fetchedValue) }) {
|
||||
self.notifyChange(value)
|
||||
}
|
||||
} catch {
|
||||
@@ -144,7 +146,9 @@ extension ValueObserver {
|
||||
/// Fetch an observed value, and moves the reducer forward.
|
||||
func fetchValue(_ db: Database) throws -> Reducer.Value? {
|
||||
try recordingSelectedRegionIfNeeded(db) {
|
||||
try reducer.fetchAndReduce(db, requiringWriteAccess: requiresWriteAccess)
|
||||
try synchronized {
|
||||
try reducer.fetchAndReduce(db, requiringWriteAccess: requiresWriteAccess)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,7 +203,7 @@ extension ValueObserver {
|
||||
}
|
||||
|
||||
private var needsRecordingSelectedRegion: Bool {
|
||||
observedRegion == nil || !reducer._isSelectedRegionDeterministic
|
||||
observedRegion == nil || synchronized { !reducer._isSelectedRegionDeterministic }
|
||||
}
|
||||
|
||||
private func recordingSelectedRegionIfNeeded<T>(
|
||||
|
||||
@@ -43,8 +43,8 @@
|
||||
561729562235340E0006E219 /* EncodableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561729532235340E0006E219 /* EncodableRecord.swift */; };
|
||||
56176C7E1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
|
||||
56176C801EACCD31000F3F2B /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
|
||||
561CFA7D2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */; };
|
||||
561CFA7E2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */; };
|
||||
561CFA7D2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */; };
|
||||
561CFA7E2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */; };
|
||||
561CFAA12376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */; };
|
||||
561CFAA22376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */; };
|
||||
561CFAA42376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */; };
|
||||
@@ -98,6 +98,8 @@
|
||||
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 */; };
|
||||
563B533B267E2FA4009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5339267E2FA4009549B5 /* TableTests.swift */; };
|
||||
563B533C267E2FA4009549B5 /* TableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B5339267E2FA4009549B5 /* TableTests.swift */; };
|
||||
563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; };
|
||||
563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F99249E74E5007A48C9 /* Trace.swift */; };
|
||||
563B8F9E249E8AB0007A48C9 /* ValueObservationPrintTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */; };
|
||||
@@ -322,6 +324,8 @@
|
||||
5670329C212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; };
|
||||
567071F5208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; };
|
||||
56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
56713FE42691F487006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
5671FC221DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
|
||||
5671FC251DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */; };
|
||||
56741EAB1E66A8B3003E422D /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; };
|
||||
@@ -358,6 +362,8 @@
|
||||
567F45AF1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
|
||||
568068341EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
|
||||
568068381EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
|
||||
56894F332604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; };
|
||||
56894F342604FC1E00268F4D /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F322604FC1E00268F4D /* Table.swift */; };
|
||||
56894FE3260658A400268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; };
|
||||
56894FE8260658A500268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FA0260657F600268F4D /* Decimal.swift */; };
|
||||
56894FF2260658E600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894FF1260658E600268F4D /* FoundationDecimalTests.swift */; };
|
||||
@@ -523,8 +529,8 @@
|
||||
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 */; };
|
||||
56FF45471D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */; };
|
||||
56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; };
|
||||
56FF45471D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */; };
|
||||
56FF45591D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; };
|
||||
56FF455D1D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */; };
|
||||
6340BF831E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */; };
|
||||
@@ -795,7 +801,7 @@
|
||||
5615B284222B17B900061C1C /* AssociationHasOneThroughDecodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughDecodableRecordTests.swift; sourceTree = "<group>"; };
|
||||
561667001D08A49900ADD404 /* FoundationNSDecimalNumberTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDecimalNumberTests.swift; sourceTree = "<group>"; };
|
||||
561729532235340E0006E219 /* EncodableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncodableRecord.swift; sourceTree = "<group>"; };
|
||||
561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = "<group>"; };
|
||||
561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = "<group>"; };
|
||||
561CFA9F2376EF4F000C8BAA /* AssociationHasManyOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyOrderingTests.swift; sourceTree = "<group>"; };
|
||||
561CFAA32376EF59000C8BAA /* AssociationHasManyThroughOrderingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasManyThroughOrderingTests.swift; sourceTree = "<group>"; };
|
||||
56231E6025CEBF06001DFD2F /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = "<group>"; };
|
||||
@@ -833,6 +839,7 @@
|
||||
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>"; };
|
||||
563B5339267E2FA4009549B5 /* TableTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableTests.swift; sourceTree = "<group>"; };
|
||||
563B8F99249E74E5007A48C9 /* Trace.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Trace.swift; sourceTree = "<group>"; };
|
||||
563B8F9D249E8AB0007A48C9 /* ValueObservationPrintTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationPrintTests.swift; sourceTree = "<group>"; };
|
||||
563B8FB024A1CE9E007A48C9 /* DatabasePublishers.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePublishers.swift; sourceTree = "<group>"; };
|
||||
@@ -950,6 +957,7 @@
|
||||
566BE7132342541F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = "<group>"; };
|
||||
56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
567071F2208A00BE006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = "<group>"; };
|
||||
56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = "<group>"; };
|
||||
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
567156701CB18050007DC145 /* EncryptionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EncryptionTests.swift; sourceTree = "<group>"; };
|
||||
5671FC1F1DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3TokenizerDescriptor.swift; sourceTree = "<group>"; };
|
||||
@@ -974,6 +982,7 @@
|
||||
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
|
||||
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
|
||||
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
|
||||
56894F322604FC1E00268F4D /* Table.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Table.swift; sourceTree = "<group>"; };
|
||||
56894FA0260657F600268F4D /* Decimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Decimal.swift; sourceTree = "<group>"; };
|
||||
56894FF1260658E600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
|
||||
568ECB0C25D904CA00B71526 /* SQLSelection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLSelection.swift; sourceTree = "<group>"; };
|
||||
@@ -1109,7 +1118,7 @@
|
||||
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>"; };
|
||||
56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = "<group>"; };
|
||||
56FF45551D2CDA5200F21EF9 /* RecordUniqueIndexTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordUniqueIndexTests.swift; sourceTree = "<group>"; };
|
||||
6340BF7F1E5E3F7900832805 /* RecordPersistenceConflictPolicy.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPersistenceConflictPolicy.swift; sourceTree = "<group>"; };
|
||||
DC2393C61ABE35F8003FF113 /* GRDB-Bridging.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "GRDB-Bridging.h"; sourceTree = "<group>"; };
|
||||
@@ -1209,6 +1218,7 @@
|
||||
5674A6E31F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift */,
|
||||
5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */,
|
||||
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */,
|
||||
56713FE12691F487006153C3 /* JSONRequiredEncoder.swift */,
|
||||
5605F1581C672E4000235C62 /* StandardLibrary.swift */,
|
||||
);
|
||||
path = StandardLibrary;
|
||||
@@ -1243,11 +1253,9 @@
|
||||
5665FA3B2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift */,
|
||||
56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */,
|
||||
566A84422041AB2D00E50BFD /* MutablePersistableRecordChangesTests.swift */,
|
||||
56FF453F1D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift */,
|
||||
5674A71C1F30A8DF0095F066 /* MutablePersistableRecordEncodableTests.swift */,
|
||||
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
|
||||
563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */,
|
||||
561CFA7B2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift */,
|
||||
563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */,
|
||||
);
|
||||
name = PersistableRecord;
|
||||
@@ -1302,7 +1310,9 @@
|
||||
56176C9C1EACEA8C000F3F2B /* TableRecord */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56FF453F1D2C23BA00F21EF9 /* TableRecordDeleteTests.swift */,
|
||||
56FEE7FA1F47253700D930EA /* TableRecordTests.swift */,
|
||||
561CFA7B2373503D000C8BAA /* TableRecordUpdateTests.swift */,
|
||||
);
|
||||
name = TableRecord;
|
||||
sourceTree = "<group>";
|
||||
@@ -1371,6 +1381,7 @@
|
||||
56F34FC524B0A0C8007513FC /* SQLIdentifyingColumnsTests.swift */,
|
||||
566AD8C51D531BE4002EC1A8 /* TableDefinitionTests.swift */,
|
||||
56300B6A1C53D3E8005A543B /* TableRecord+QueryInterfaceRequestTests.swift */,
|
||||
563B5339267E2FA4009549B5 /* TableTests.swift */,
|
||||
5698AC7F1DA380A20056AF8C /* VirtualTableModuleTests.swift */,
|
||||
5653EB5620961F8900F46237 /* Association */,
|
||||
);
|
||||
@@ -1562,6 +1573,7 @@
|
||||
5656A84E2295BD56001FF3FF /* SQLRelation.swift */,
|
||||
568ECB0C25D904CA00B71526 /* SQLSelection.swift */,
|
||||
568ECB3425D91CEE00B71526 /* SQLSubquery.swift */,
|
||||
56894F322604FC1E00268F4D /* Table.swift */,
|
||||
);
|
||||
path = SQL;
|
||||
sourceTree = "<group>";
|
||||
@@ -2263,6 +2275,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5656A8722295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */,
|
||||
56713FE42691F487006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5636E9C11D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
F3BA801B1CFB2886003DC1BA /* CGFloat.swift in Sources */,
|
||||
563B8FBE24A1D388007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
@@ -2280,6 +2293,7 @@
|
||||
56CEB4F61EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
|
||||
5656A8522295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
56BB6EAE1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
56894F342604FC1E00268F4D /* Table.swift in Sources */,
|
||||
F3BA801A1CFB2876003DC1BA /* StatementColumnConvertible.swift in Sources */,
|
||||
566B91381FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
56CEB4FF1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
@@ -2395,7 +2409,7 @@
|
||||
files = (
|
||||
F3BA80D71CFB300A003DC1BA /* DatabaseValueTests.swift in Sources */,
|
||||
F3BA80C81CFB2FD8003DC1BA /* DatabaseQueueTests.swift in Sources */,
|
||||
56FF45471D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */,
|
||||
56FF45471D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */,
|
||||
F3BA810C1CFB3056003DC1BA /* StatementArguments+FoundationTests.swift in Sources */,
|
||||
F3BA80B91CFB2FD1003DC1BA /* DatabasePoolBackupTests.swift in Sources */,
|
||||
F3BA811E1CFB3063003DC1BA /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
|
||||
@@ -2544,7 +2558,7 @@
|
||||
5644DE8020F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */,
|
||||
56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */,
|
||||
56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */,
|
||||
561CFA7E2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
561CFA7E2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */,
|
||||
56B964D21DA521450002DA19 /* FTS5RecordTests.swift in Sources */,
|
||||
F3BA80F91CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */,
|
||||
5604484F25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */,
|
||||
@@ -2559,6 +2573,7 @@
|
||||
5653EB7120961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
|
||||
F3BA812B1CFB3063003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
5698ACA51DA4B0430056AF8C /* FTS4TableBuilderTests.swift in Sources */,
|
||||
563B533C267E2FA4009549B5 /* TableTests.swift in Sources */,
|
||||
5653EB6F20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
|
||||
564CE5C721B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
F3BA80B11CFB2FC4003DC1BA /* DatabaseTests.swift in Sources */,
|
||||
@@ -2624,6 +2639,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */,
|
||||
56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5636E9BE1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
F3BA80771CFB2E5C003DC1BA /* CGFloat.swift in Sources */,
|
||||
563B8FBD24A1D388007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
@@ -2641,6 +2657,7 @@
|
||||
56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
|
||||
5656A8512295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
56BB6EAB1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
56894F332604FC1E00268F4D /* Table.swift in Sources */,
|
||||
F3BA80761CFB2E55003DC1BA /* StatementColumnConvertible.swift in Sources */,
|
||||
566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
@@ -2862,7 +2879,7 @@
|
||||
5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */,
|
||||
F3BA81391CFB3064003DC1BA /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
56419C7F24A51D6E004967E1 /* DatabaseReaderReadPublisherTests.swift in Sources */,
|
||||
56FF45431D2C23BA00F21EF9 /* MutablePersistableRecordDeleteTests.swift in Sources */,
|
||||
56FF45431D2C23BA00F21EF9 /* TableRecordDeleteTests.swift in Sources */,
|
||||
F3BA80F01CFB3017003DC1BA /* FetchableRecordTests.swift in Sources */,
|
||||
5657AB491D108BA9006283EF /* FoundationNSNullTests.swift in Sources */,
|
||||
56419C8924A51D7D004967E1 /* RecordingError.swift in Sources */,
|
||||
@@ -2905,7 +2922,7 @@
|
||||
5644DE7F20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift in Sources */,
|
||||
F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */,
|
||||
56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */,
|
||||
561CFA7D2373503D000C8BAA /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
561CFA7D2373503D000C8BAA /* TableRecordUpdateTests.swift in Sources */,
|
||||
5623936C1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */,
|
||||
F3BA80E01CFB300F003DC1BA /* DatabaseTimestampTests.swift in Sources */,
|
||||
5604484E25DEEF7C002BAA79 /* AssociationPrefetchingRelationTests.swift in Sources */,
|
||||
@@ -2920,6 +2937,7 @@
|
||||
5653EB7020961FB200F46237 /* AssociationTableAliasTestsSQLTests.swift in Sources */,
|
||||
F3BA81311CFB3064003DC1BA /* RecordPrimaryKeySingleTests.swift in Sources */,
|
||||
5698AC431DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */,
|
||||
563B533B267E2FA4009549B5 /* TableTests.swift in Sources */,
|
||||
5653EB6E20961FB200F46237 /* AssociationBelongsToSQLDerivationTests.swift in Sources */,
|
||||
564CE5C621B8FFE600652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
F3BA80E11CFB300F003DC1BA /* DatabaseValueConversionTests.swift in Sources */,
|
||||
|
||||
@@ -50,7 +50,14 @@ TEST_ACTIONS = clean build build-for-testing test-without-building
|
||||
|
||||
# When adding support for an Xcode version, look for available devices with
|
||||
# `xcrun xctrace list devices` (or the deprecated `instruments -s devices`).
|
||||
ifeq ($(XCODEVERSION),12.4)
|
||||
ifeq ($(XCODEVERSION),12.5)
|
||||
MAX_SWIFT_VERSION = 5.4
|
||||
MIN_SWIFT_VERSION = 5.2
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.5"
|
||||
MIN_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 5s,OS=11.4"
|
||||
MAX_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=14.5"
|
||||
MIN_TVOS_DESTINATION = "platform=tvOS Simulator,name=Apple TV,OS=11.4"
|
||||
else ifeq ($(XCODEVERSION),12.4)
|
||||
MAX_SWIFT_VERSION = 5.3
|
||||
MIN_SWIFT_VERSION = 5.2
|
||||
MAX_IOS_DESTINATION = "platform=iOS Simulator,name=iPhone 12,OS=14.4"
|
||||
@@ -431,10 +438,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.8.0 \
|
||||
--module-version 5.8.0 \
|
||||
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.9.0 \
|
||||
--module-version 5.9.0 \
|
||||
--module GRDB \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.8/ \
|
||||
--root-url http://groue.github.io/GRDB.swift/docs/5.9/ \
|
||||
--output Documentation/Reference \
|
||||
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
|
||||
else
|
||||
|
||||
@@ -6,18 +6,17 @@
|
||||
<a href="https://developer.apple.com/swift/"><img alt="Swift 5.2" src="https://img.shields.io/badge/swift-5.2-orange.svg?style=flat"></a>
|
||||
<a href="https://developer.apple.com/swift/"><img alt="Platforms" src="https://img.shields.io/cocoapods/p/GRDB.swift.svg"></a>
|
||||
<a href="https://github.com/groue/GRDB.swift/blob/master/LICENSE"><img alt="License" src="https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000"></a>
|
||||
<a href="https://travis-ci.org/groue/GRDB.swift"><img alt="Build Status" src="https://travis-ci.org/groue/GRDB.swift.svg?branch=master"></a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
**Latest release**: May 16, 2021 • version 5.8.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
|
||||
**Latest release**: August 15, 2021 • version 5.9.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 10.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ • SQLite 3.8.5+ • Swift 5.2+ / Xcode 11.4+
|
||||
|
||||
| Swift version | GRDB version |
|
||||
| -------------- | ----------------------------------------------------------- |
|
||||
| **Swift 5.2+** | **v5.8.0** |
|
||||
| **Swift 5.2+** | **v5.9.0** |
|
||||
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
| Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
|
||||
@@ -316,7 +315,7 @@ Documentation
|
||||
|
||||
#### Reference
|
||||
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.8/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.9/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
|
||||
|
||||
#### Getting Started
|
||||
|
||||
@@ -510,7 +509,7 @@ let dbQueue = try DatabaseQueue(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.8/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.9/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
## Database Pools
|
||||
@@ -590,7 +589,7 @@ let dbPool = try DatabasePool(
|
||||
configuration: config)
|
||||
```
|
||||
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.8/Structs/Configuration.html) for more details.
|
||||
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.9/Structs/Configuration.html) for more details.
|
||||
|
||||
|
||||
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
|
||||
@@ -650,7 +649,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
|
||||
You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details.
|
||||
|
||||
@@ -798,6 +797,29 @@ try Row.fetchOne(...) // Row?
|
||||
let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) ...") // Int?
|
||||
```
|
||||
|
||||
**All those fetching methods require an SQL string that contains a single SQL statement.** When you want to fetch from multiple statements joined with a semicolon, iterate the multiple [prepared statements](#prepared-statements) found in the SQL string:
|
||||
|
||||
```swift
|
||||
let statements = try db.allStatements(sql: """
|
||||
SELECT ...;
|
||||
SELECT ...;
|
||||
SELECT ...;
|
||||
""")
|
||||
while let statement = try statements.next() {
|
||||
let players = try Player.fetchAll(statement)
|
||||
}
|
||||
```
|
||||
|
||||
You can join the results of all statements yielded by the `allStatements` method, like the SQLite [`sqlite3_exec`](https://www.sqlite.org/c3ref/exec.html) function:
|
||||
|
||||
```swift
|
||||
// A single cursor of all rows from all statements
|
||||
let rows = try db
|
||||
.allStatements(sql: "...")
|
||||
.flatMap { statement in try Row.fetchCursor(statement) }
|
||||
```
|
||||
|
||||
See [prepared statements](#prepared-statements) for more information about `allStatements()`.
|
||||
|
||||
### Cursors
|
||||
|
||||
@@ -885,7 +907,7 @@ try dbQueue.read { db in
|
||||
let dictionary = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
```
|
||||
|
||||
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.8/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
|
||||
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.9/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
|
||||
|
||||
```swift
|
||||
// Prints all Github links
|
||||
@@ -964,7 +986,7 @@ let rows = try Row.fetchAll(db,
|
||||
arguments: ["name": "Arthur"])
|
||||
```
|
||||
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
|
||||
|
||||
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
|
||||
|
||||
@@ -1249,7 +1271,7 @@ GRDB ships with built-in support for the following value types:
|
||||
|
||||
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
|
||||
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html):
|
||||
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
let url: URL = ...
|
||||
@@ -1552,6 +1574,23 @@ The `databaseValue` property returns [DatabaseValue](#databasevalue), a type tha
|
||||
|
||||
The `fromDatabaseValue()` factory method returns an instance of your custom type if the database value contains a suitable value. If the database value does not contain a suitable value, such as "foo" for Date, `fromDatabaseValue` *must* return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
|
||||
|
||||
Value types that adopt both `DatabaseValueConvertible` and an archival protocol ([Codable, Encodable or Decodable](https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types)) are automatically coded and decoded from JSON arrays and objects:
|
||||
|
||||
```swift
|
||||
// Encoded as a JSON object in the database:
|
||||
struct Color: Codable, DatabaseValueConvertible {
|
||||
var r: Double
|
||||
var g: Double
|
||||
var b: Double
|
||||
}
|
||||
```
|
||||
|
||||
For such codable value types, GRDB uses the standard [JSONDecoder](https://developer.apple.com/documentation/foundation/jsondecoder) and [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) from Foundation. By default, Data values are handled with the `.base64` strategy, Date with the `.millisecondsSince1970` strategy, and non conforming floats with the `.throw` strategy.
|
||||
|
||||
In order to customize the JSON format, provide a custom implementation of the `DatabaseValueConvertible` requirements.
|
||||
|
||||
> :point_up: **Note**: standard sequences such as `Array`, `Set`, or `Dictionary` do not conform to `DatabaseValueConvertible`, even conditionally. You won't be able to directly fetch or store arrays, sets, or dictionaries as JSON database values. You can get free JSON support from these standard types when they are embedded as properties of [Codable Records], though.
|
||||
|
||||
|
||||
## Transactions and Savepoints
|
||||
|
||||
@@ -1679,7 +1718,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
|
||||
}
|
||||
```
|
||||
|
||||
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.8/Structs/Configuration.html) configuration flag:
|
||||
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.9/Structs/Configuration.html) configuration flag:
|
||||
|
||||
```swift
|
||||
// fatal error: A transaction has been left opened at the end of a database access
|
||||
@@ -1781,40 +1820,38 @@ dbQueue.inTransaction(.exclusive) { db in ... }
|
||||
|
||||
**Prepared Statements** let you prepare an SQL query and execute it later, several times if you need, with different arguments.
|
||||
|
||||
There are two kinds of prepared statements: **select statements**, and **update statements**:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
let updateSQL = "INSERT INTO player (name, score) VALUES (:name, :score)"
|
||||
let updateStatement = try db.makeUpdateStatement(sql: updateSQL)
|
||||
let insertSQL = "INSERT INTO player (name, score) VALUES (:name, :score)"
|
||||
let insertStatement = try db.makeStatement(sql: insertSQL)
|
||||
|
||||
let selectSQL = "SELECT * FROM player WHERE name = ?"
|
||||
let selectStatement = try db.makeSelectStatement(sql: selectSQL)
|
||||
let selectStatement = try db.makeStatement(sql: selectSQL)
|
||||
}
|
||||
```
|
||||
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
|
||||
|
||||
```swift
|
||||
updateStatement.arguments = ["name": "Arthur", "score": 1000]
|
||||
insertStatement.arguments = ["name": "Arthur", "score": 1000]
|
||||
selectStatement.arguments = ["Arthur"]
|
||||
```
|
||||
|
||||
Alternatively, you can create a prepared statement with [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
let updateStatement = try db.makeUpdateStatement(literal: "INSERT ...")
|
||||
let selectStatement = try db.makeSelectStatement(literal: "SELECT ...")
|
||||
// ~~~~~~~
|
||||
let insertStatement = try db.makeStatement(literal: "INSERT ...")
|
||||
let selectStatement = try db.makeStatement(literal: "SELECT ...")
|
||||
// ~~~~~~~
|
||||
```
|
||||
|
||||
Update statements can be executed:
|
||||
Statements can be executed:
|
||||
|
||||
```swift
|
||||
try updateStatement.execute()
|
||||
try insertStatement.execute()
|
||||
```
|
||||
|
||||
Select statements can be used wherever a raw SQL query string would fit (see [fetch queries](#fetch-queries)):
|
||||
Statements can be used wherever a raw SQL query string would fit (see [fetch queries](#fetch-queries)):
|
||||
|
||||
```swift
|
||||
let rows = try Row.fetchCursor(selectStatement) // A Cursor of Row
|
||||
@@ -1826,13 +1863,57 @@ let player = try Player.fetchOne(selectStatement) // Player?
|
||||
You can set the arguments at the moment of the statement execution:
|
||||
|
||||
```swift
|
||||
try updateStatement.execute(arguments: ["name": "Arthur", "score": 1000])
|
||||
try insertStatement.execute(arguments: ["name": "Arthur", "score": 1000])
|
||||
let player = try Player.fetchOne(selectStatement, arguments: ["Arthur"])
|
||||
```
|
||||
|
||||
**When you want to build multiple statements joined with a semicolon**, use the `allStatements` method:
|
||||
|
||||
```swift
|
||||
let statements = try db.allStatements(sql: """
|
||||
INSERT INTO player (name, score) VALUES (?, ?);
|
||||
INSERT INTO player (name, score) VALUES (?, ?);
|
||||
""", arguments: ["Arthur", 100, "O'Brien", 1000])
|
||||
while let statement = try statements.next() {
|
||||
try statement.execute()
|
||||
}
|
||||
```
|
||||
|
||||
`allStatements` also supports [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
let statements = try db.allStatements(literal: """
|
||||
INSERT INTO player (name, score) VALUES (\("Arthur"), \(100));
|
||||
INSERT INTO player (name, score) VALUES (\("O'Brien"), \(1000));
|
||||
""")
|
||||
while let statement = try statements.next() {
|
||||
try statement.execute()
|
||||
}
|
||||
```
|
||||
|
||||
You can turn the [cursor](#cursors) returned from `allStatements` into a regular Swift array, but in this case make sure all individual statements can compile even if the previous ones were not run:
|
||||
|
||||
```swift
|
||||
// OK: Array of statements
|
||||
let statements = try Array(db.allStatements(sql: """
|
||||
INSERT ...;
|
||||
UPDATE ...;
|
||||
SELECT ...;
|
||||
"""))
|
||||
|
||||
// FAILURE: Can't build an array of statements since
|
||||
// the INSERT won't compile until CREATE TABLE is run.
|
||||
let statements = try Array(db.allStatements(sql: """
|
||||
CREATE TABLE player ...;
|
||||
INSERT INTO player ...;
|
||||
"""))
|
||||
```
|
||||
|
||||
See also `Database.execute(sql:)` in the [Executing Updates](#executing-updates) chapter.
|
||||
|
||||
> :point_up: **Note**: it is a programmer error to reuse a prepared statement that has failed: GRDB may crash if you do so.
|
||||
|
||||
See [row queries](#row-queries), [value queries](#value-queries), and [Records](#records) for more information.
|
||||
For more information about prepared statements, see the [Statement reference](http://groue.github.io/GRDB.swift/docs/5.9/Classes/Statement.html).
|
||||
|
||||
|
||||
### Prepared Statements Cache
|
||||
@@ -1843,14 +1924,20 @@ When the same query will be used several times in the lifetime of your applicati
|
||||
|
||||
> :point_up: **Note**: This is because you don't have the necessary tools. Statements are tied to specific SQLite connections and dispatch queues which you don't manage yourself, especially when you use [database pools](#database-pools). A change in the database schema [may, or may not](https://www.sqlite.org/compile.html#max_schema_retry) invalidate a statement.
|
||||
|
||||
Instead, use the `cachedUpdateStatement` and `cachedSelectStatement` methods. GRDB does all the hard caching and [memory management](#memory-management) stuff for you:
|
||||
Instead, use the `cachedStatement` method. GRDB does all the hard caching and [memory management](#memory-management) stuff for you:
|
||||
|
||||
```swift
|
||||
let updateStatement = try db.cachedUpdateStatement(sql: sql)
|
||||
let selectStatement = try db.cachedSelectStatement(sql: sql)
|
||||
let statement = try db.cachedStatement(sql: sql)
|
||||
```
|
||||
|
||||
Should a cached prepared statement throw an error, don't reuse it (it is a programmer error). Instead, reload it from the cache.
|
||||
Cached statements also support [SQL Interpolation]:
|
||||
|
||||
```swift
|
||||
let statement = try db.cachedStatement(literal: "INSERT ...")
|
||||
// ~~~~~~~
|
||||
```
|
||||
|
||||
> :warning: **Warning**: Should a cached prepared statement throw an error, don't reuse it (it is a programmer error). Instead, reload one from the cache.
|
||||
|
||||
|
||||
## Custom SQL Functions and Aggregates
|
||||
@@ -2263,7 +2350,7 @@ try dbQueue.read { db in
|
||||
let sqliteConnection = db.sqliteConnection
|
||||
|
||||
// The raw pointer to a statement:
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT ...")
|
||||
let statement = try db.makeStatement(sql: "SELECT ...")
|
||||
let sqliteStatement = statement.sqliteStatement
|
||||
}
|
||||
```
|
||||
@@ -2390,7 +2477,7 @@ try Player
|
||||
.updateAll(db, Column("score") += 1)
|
||||
```
|
||||
|
||||
:point_right: update methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol.
|
||||
:point_right: update methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. Batch updates are available on the [TableRecord] protocol.
|
||||
|
||||
|
||||
### Deleting Records
|
||||
@@ -2413,7 +2500,7 @@ try Player
|
||||
.deleteAll(db)
|
||||
```
|
||||
|
||||
:point_right: delete methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol.
|
||||
:point_right: delete methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. Batch deletes are available on the [TableRecord] protocol.
|
||||
|
||||
|
||||
### Counting Records
|
||||
@@ -2569,7 +2656,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set<Place>
|
||||
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
|
||||
```
|
||||
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html) for more information about the query arguments.
|
||||
|
||||
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
|
||||
|
||||
@@ -2747,7 +2834,11 @@ try place.updateChanges(db) { ... } // Maybe UPDATE
|
||||
try place.updateChanges(db) // Maybe UPDATE (Record class only)
|
||||
try place.delete(db) // DELETE
|
||||
try place.exists(db)
|
||||
```
|
||||
|
||||
The [TableRecord] protocol comes with batch operations:
|
||||
|
||||
```swift
|
||||
// Type methods
|
||||
try Place.updateAll(db, ...) // UPDATE
|
||||
try Place.deleteAll(db) // DELETE
|
||||
@@ -2848,6 +2939,9 @@ let players = try Player.fetchSet(db, ids: [1, 2, 3])
|
||||
let request = Player.filter(id: 1)
|
||||
let request = Player.filter(ids: [1, 2, 3])
|
||||
|
||||
let ids = try Player.selectID().fetchAll(db)
|
||||
let ids = try Player.filter(...).selectID().fetchSet(db)
|
||||
|
||||
try Player.deleteOne(db, id: 1)
|
||||
try Player.deleteAll(db, ids: [1, 2, 3])
|
||||
```
|
||||
@@ -2998,7 +3092,7 @@ protocol EncodableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.8/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.8/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.8/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
|
||||
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.9/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.9/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.9/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
|
||||
|
||||
> :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings).
|
||||
|
||||
@@ -3829,16 +3923,16 @@ This is the list of record methods, along with their required protocols. The [Re
|
||||
| `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#record-comparison) |
|
||||
| `record.updateChanges(db) { ... }` | [PersistableRecord] | [*](#record-comparison) |
|
||||
| `record.updateChanges(db)` | [Record](#record-class) | [*](#record-comparison) |
|
||||
| `Type.updateAll(db, ...)` | [PersistableRecord] | |
|
||||
| `Type.filter(...).updateAll(db, ...)` | [PersistableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.updateAll(db, ...)` | [TableRecord] | |
|
||||
| `Type.filter(...).updateAll(db, ...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| **Delete Records** | | |
|
||||
| `record.delete(db)` | [PersistableRecord] | |
|
||||
| `Type.deleteOne(db, key:...)` | [PersistableRecord] | <a href="#list-of-record-methods-1">¹</a> |
|
||||
| `Type.deleteOne(db, id:...)` | [PersistableRecord] & [Identifiable] | <a href="#list-of-record-methods-1">¹</a> |
|
||||
| `Type.deleteAll(db)` | [PersistableRecord] | |
|
||||
| `Type.deleteAll(db, keys:...)` | [PersistableRecord] | <a href="#list-of-record-methods-1">¹</a> |
|
||||
| `Type.deleteAll(db, ids:...)` | [PersistableRecord] & [Identifiable] | <a href="#list-of-record-methods-1">¹</a> |
|
||||
| `Type.filter(...).deleteAll(db)` | [PersistableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.deleteOne(db, key:...)` | [TableRecord] | <a href="#list-of-record-methods-1">¹</a> |
|
||||
| `Type.deleteOne(db, id:...)` | [TableRecord] & [Identifiable] | <a href="#list-of-record-methods-1">¹</a> |
|
||||
| `Type.deleteAll(db)` | [TableRecord] | |
|
||||
| `Type.deleteAll(db, keys:...)` | [TableRecord] | <a href="#list-of-record-methods-1">¹</a> |
|
||||
| `Type.deleteAll(db, ids:...)` | [TableRecord] & [Identifiable] | <a href="#list-of-record-methods-1">¹</a> |
|
||||
| `Type.filter(...).deleteAll(db)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| **Check Record Existence** | | |
|
||||
| `record.exists(db)` | [PersistableRecord] | |
|
||||
| **Convert Record to Dictionary** | | |
|
||||
@@ -3894,8 +3988,11 @@ This is the list of record methods, along with their required protocols. The [Re
|
||||
| `Type.none()` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.select(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.select(..., as:...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.selectID()` | [TableRecord] & Identifiable | [*](#identifiable-records) |
|
||||
| `Type.annotated(with:...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.filter(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.filter(id:)` | [TableRecord] & Identifiable | [*](#identifiable-records) |
|
||||
| `Type.filter(ids:)` | [TableRecord] & Identifiable | [*](#identifiable-records) |
|
||||
| `Type.matching(...)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.including(all:)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
| `Type.including(optional:)` | [TableRecord] | <a href="#list-of-record-methods-2">²</a> |
|
||||
@@ -3943,7 +4040,7 @@ let player = try Player.fetchOne(db, sql: "SELECT * FROM player WHERE id = ?", a
|
||||
<a name="list-of-record-methods-4">⁴</a> See [Prepared Statements](#prepared-statements):
|
||||
|
||||
```swift
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
let player = try Player.fetchOne(statement, arguments: [1]) // Player?
|
||||
```
|
||||
|
||||
@@ -4237,13 +4334,33 @@ let players = try request.fetchAll(db) // [Player]
|
||||
let count = try request.fetchCount(db) // Int
|
||||
```
|
||||
|
||||
All requests start from **a type** that adopts the `TableRecord` protocol, such as a `Record` subclass (see [Records](#records)):
|
||||
Query interface requests usually start from **a type** that adopts the `TableRecord` protocol, such as a `Record` subclass (see [Records](#records)):
|
||||
|
||||
```swift
|
||||
class Player : Record { ... }
|
||||
class Player: Record { ... }
|
||||
|
||||
// The request for all players:
|
||||
let request = Player.all()
|
||||
let players = try request.fetchAll(db) // [Player]
|
||||
```
|
||||
|
||||
Declare the table **columns** that you want to use for filtering, or sorting:
|
||||
When you can not use a record type, use `Table`:
|
||||
|
||||
```swift
|
||||
// The request for all rows from the player table:
|
||||
let table = Table("player")
|
||||
let request = table.all()
|
||||
let rows = try request.fetchAll(db) // [Row]
|
||||
|
||||
// The request for all players from the player table:
|
||||
let table = Table<Player>("player")
|
||||
let request = table.all()
|
||||
let players = try request.fetchAll(db) // [Player]
|
||||
```
|
||||
|
||||
> :point_up: **Note**: all examples in the documentation below use a record type, but you can always substitute a `Table` instead.
|
||||
|
||||
Next, declare the table **columns** that you want to use for filtering, or sorting:
|
||||
|
||||
```swift
|
||||
let idColumn = Column("id")
|
||||
@@ -4279,6 +4396,16 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Player.select(nameColumn, as: String.self)
|
||||
```
|
||||
|
||||
- `selectID()` is available on [Identifiable Records]. It supports all tables that have a single-column primary key:
|
||||
|
||||
```swift
|
||||
// SELECT id FROM player
|
||||
Player.selectID()
|
||||
|
||||
// SELECT id FROM player WHERE name IS NOT NULL
|
||||
Player.filter(nameColumn != nil).selectID()
|
||||
```
|
||||
|
||||
- `annotated(with: expression...)` extends the selection.
|
||||
|
||||
```swift
|
||||
@@ -4495,7 +4622,7 @@ Player // SELECT * FROM player
|
||||
```
|
||||
|
||||
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.8/Structs/StatementArguments.html):
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.9/Structs/StatementArguments.html):
|
||||
|
||||
```swift
|
||||
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
|
||||
@@ -4512,16 +4639,24 @@ By default, query interface requests select all columns:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
struct Player: TableRecord { ... }
|
||||
let request = Player.all()
|
||||
|
||||
// SELECT * FROM player
|
||||
let table = Table("player")
|
||||
let request = table.all()
|
||||
```
|
||||
|
||||
**The selection can be changed for each individual requests, or for all requests built from a given type.**
|
||||
**The selection can be changed for each individual requests, or in the case of record-based requests, for all requests built from this record type.**
|
||||
|
||||
The `select(...)` and `select(..., as:)` methods change the selection of a single request (see [Fetching from Requests] for detailed information):
|
||||
|
||||
```swift
|
||||
let request = Player.select(max(scoreColumn))
|
||||
let maxScore: Int? = try Int.fetchOne(db, request)
|
||||
let request = Player.select(max(Column("score")))
|
||||
let maxScore = try Int.fetchOne(db, request) // Int?
|
||||
|
||||
let request = Player.select(max(Column("score")), as: Int.self)
|
||||
let maxScore = try request.fetchOne(db) // Int?
|
||||
```
|
||||
|
||||
The default selection for a record type is controlled by the `databaseSelection` property:
|
||||
@@ -5037,7 +5172,13 @@ try Player
|
||||
.deleteAll(db)
|
||||
```
|
||||
|
||||
> :point_up: **Note** Deletion methods are only available for records that adopts the [PersistableRecord] protocol.
|
||||
> :point_up: **Note** Deletion methods are available on types that adopt the [TableRecord] protocol, and `Table`:
|
||||
>
|
||||
> ```swift
|
||||
> struct Player: TableRecord { ... }
|
||||
> try Player.deleteAll(db) // Fine
|
||||
> try Table("player").deleteAll(db) // Just as fine
|
||||
> ```
|
||||
|
||||
**Deleting records according to their primary key** is a common task.
|
||||
|
||||
@@ -5114,7 +5255,13 @@ Default [Conflict Resolution] rules apply, and you may also provide a specific o
|
||||
try Player.updateAll(db, onConflict: .ignore, /* assignments... */)
|
||||
```
|
||||
|
||||
> :point_up: **Note** The `updateAll` method is only available for records that adopts the [PersistableRecord] protocol.
|
||||
> :point_up: **Note** The `updateAll` method is available on types that adopt the [TableRecord] protocol, and `Table`:
|
||||
>
|
||||
> ```swift
|
||||
> struct Player: TableRecord { ... }
|
||||
> try Player.updateAll(db, ...) // Fine
|
||||
> try Table("player").updateAll(db, ...) // Just as fine
|
||||
> ```
|
||||
|
||||
|
||||
## Custom Requests
|
||||
@@ -5194,7 +5341,7 @@ try Player.customRequest().fetchAll(db) // [Player]
|
||||
|
||||
- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method.
|
||||
|
||||
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.8/Structs/AnyFetchRequest.html): a type-erased request.
|
||||
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.9/Structs/AnyFetchRequest.html): a type-erased request.
|
||||
|
||||
|
||||
## Joined Queries Support
|
||||
@@ -6372,7 +6519,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan
|
||||
|
||||
### DatabaseRegion
|
||||
|
||||
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.8/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
|
||||
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.9/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
|
||||
|
||||
A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion.
|
||||
|
||||
@@ -6382,7 +6529,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati
|
||||
|
||||
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
|
||||
|
||||
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.8/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
|
||||
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.9/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
|
||||
|
||||
|
||||
#### The DatabaseRegionConvertible Protocol
|
||||
@@ -7002,7 +7149,7 @@ In such a situation, you can still avoid fatal errors by exposing and handling e
|
||||
```swift
|
||||
// Untrusted arguments
|
||||
if let arguments = StatementArguments(arguments) {
|
||||
let statement = try db.makeSelectStatement(sql: sql)
|
||||
let statement = try db.makeStatement(sql: sql)
|
||||
try statement.setArguments(arguments)
|
||||
|
||||
var cursor = try Row.fetchCursor(statement)
|
||||
@@ -7502,7 +7649,7 @@ try snapshot2.read { db in
|
||||
|
||||
### DatabaseWriter and DatabaseReader Protocols
|
||||
|
||||
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.8/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.8/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
|
||||
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.9/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.9/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
|
||||
|
||||
These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example:
|
||||
|
||||
@@ -8176,7 +8323,7 @@ When this is the case, there are two possible explanations:
|
||||
try db.execute(sql: "UPDATE player SET name = ?", arguments: [name])
|
||||
```
|
||||
|
||||
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.8/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
|
||||
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.9/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
|
||||
|
||||
|
||||
|
||||
@@ -8249,7 +8396,7 @@ Sample Code
|
||||
**Thanks**
|
||||
|
||||
- [Pierlis](http://pierlis.com), where we write great software.
|
||||
- [@alextrob](https://github.com/alextrob), [@alexwlchan](https://github.com/alexwlchan), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@eburns-vmware](https://github.com/eburns-vmware), [@felixscheinost](https://github.com/felixscheinost), [@fpillet](http://github.com/fpillet), [@gcox](https://github.com/gcox), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@holsety](https://github.com/holsety), [@jroselightricks](https://github.com/jroselightricks), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@mallman](https://github.com/mallman), [@MartinP7r](https://github.com/MartinP7r), [@Marus](https://github.com/Marus), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@professordeng](https://github.com/professordeng), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@steipete](https://github.com/steipete), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@valexa](https://github.com/valexa), [@wuyuehyang](https://github.com/wuyuehyang), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB.
|
||||
- [@alextrob](https://github.com/alextrob), [@alexwlchan](https://github.com/alexwlchan), [@bellebethcooper](https://github.com/bellebethcooper), [@bfad](https://github.com/bfad), [@cfilipov](https://github.com/cfilipov), [@charlesmchen-signal](https://github.com/charlesmchen-signal), [@Chiliec](https://github.com/Chiliec), [@chrisballinger](https://github.com/chrisballinger), [@darrenclark](https://github.com/darrenclark), [@davidkraus](https://github.com/davidkraus), [@eburns-vmware](https://github.com/eburns-vmware), [@felixscheinost](https://github.com/felixscheinost), [@fpillet](http://github.com/fpillet), [@gcox](https://github.com/gcox), [@GetToSet](https://github.com/GetToSet), [@gjeck](https://github.com/gjeck), [@gusrota](https://github.com/gusrota), [@haikusw](https://github.com/haikusw), [@hartbit](https://github.com/hartbit), [@holsety](https://github.com/holsety), [@jroselightricks](https://github.com/jroselightricks), [@kdubb](https://github.com/kdubb), [@kluufger](https://github.com/kluufger), [@KyleLeneau](https://github.com/KyleLeneau), [@layoutSubviews](https://github.com/layoutSubviews), [@mallman](https://github.com/mallman), [@MartinP7r](https://github.com/MartinP7r), [@Marus](https://github.com/Marus), [@mattgallagher](https://github.com/mattgallagher), [@MaxDesiatov](https://github.com/MaxDesiatov), [@michaelkirk-signal](https://github.com/michaelkirk-signal), [@mtancock](https://github.com/mtancock), [@pakko972](https://github.com/pakko972), [@peter-ss](https://github.com/peter-ss), [@pierlo](https://github.com/pierlo), [@pocketpixels](https://github.com/pocketpixels), [@pp5x](https://github.com/pp5x), [@professordeng](https://github.com/professordeng), [@robcas3](https://github.com/robcas3), [@runhum](https://github.com/runhum), [@schveiguy](https://github.com/schveiguy), [@SD10](https://github.com/SD10), [@sobri909](https://github.com/sobri909), [@sroddy](https://github.com/sroddy), [@steipete](https://github.com/steipete), [@swiftlyfalling](https://github.com/swiftlyfalling), [@Timac](https://github.com/Timac), [@tternes](https://github.com/tternes), [@valexa](https://github.com/valexa), [@wuyuehyang](https://github.com/wuyuehyang), [@ZevEisenberg](https://github.com/ZevEisenberg), and [@zmeyc](https://github.com/zmeyc) for their contributions, help, and feedback on GRDB.
|
||||
- [@aymerick](https://github.com/aymerick) and [@kali](https://github.com/kali) because SQL.
|
||||
- [ccgus/fmdb](https://github.com/ccgus/fmdb) for its excellency.
|
||||
|
||||
@@ -8343,7 +8490,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
|
||||
[Sharing a Database]: Documentation/SharingADatabase.md
|
||||
[FAQ]: #faq
|
||||
[Database Observation]: #database-changes-observation
|
||||
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.8/Structs/SQLRequest.html
|
||||
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.9/Structs/SQLRequest.html
|
||||
[SQL literal]: Documentation/SQLInterpolation.md#sql-literal
|
||||
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
|
||||
[Query Interface Organization]: Documentation/QueryInterfaceOrganization.md
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>5.8.0</string>
|
||||
<string>5.9.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
|
||||
## Features
|
||||
|
||||
- [ ] Breaking: have DatabaseRegionObservation produce DatabaseCancellable just as ValueObservation.
|
||||
- [ ] Can Swift 5.5 help us with `select(.all)` (request of RowDecoder), `select(.id)` (request of RowDecoder.ID), `select(.rowid)` (request of Int64)?
|
||||
- [ ] Direct access to statement for bindings
|
||||
- [ ] Breaking: make `fetchOne(key:)` type-safe (have a single dedicated primary key type)
|
||||
- [ ] Property wrapper that decodes dictionaries (but how to tell the key column?)
|
||||
|
||||
@@ -113,8 +113,8 @@
|
||||
56419DD024A54062004967E1 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD024A54057004967E1 /* GRDBTestCase.swift */; };
|
||||
56419DD124A54062004967E1 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD124A54057004967E1 /* ValueObservationRecordTests.swift */; };
|
||||
56419DD224A54062004967E1 /* ValueObservationRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD124A54057004967E1 /* ValueObservationRecordTests.swift */; };
|
||||
56419DD324A54062004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD224A54057004967E1 /* MutablePersistableRecordUpdateTests.swift */; };
|
||||
56419DD424A54062004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD224A54057004967E1 /* MutablePersistableRecordUpdateTests.swift */; };
|
||||
56419DD324A54062004967E1 /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */; };
|
||||
56419DD424A54062004967E1 /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */; };
|
||||
56419DD524A54062004967E1 /* FTS5TokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD324A54057004967E1 /* FTS5TokenizerTests.swift */; };
|
||||
56419DD624A54062004967E1 /* FTS5TokenizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD324A54057004967E1 /* FTS5TokenizerTests.swift */; };
|
||||
56419DD724A54062004967E1 /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419CD424A54057004967E1 /* CGFloatTests.swift */; };
|
||||
@@ -321,8 +321,8 @@
|
||||
56419EA024A54063004967E1 /* FetchableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3824A5405E004967E1 /* FetchableRecordTests.swift */; };
|
||||
56419EA124A54063004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3924A5405F004967E1 /* QueryInterfaceExtensibilityTests.swift */; };
|
||||
56419EA224A54063004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3924A5405F004967E1 /* QueryInterfaceExtensibilityTests.swift */; };
|
||||
56419EA324A54063004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3A24A5405F004967E1 /* MutablePersistableRecordDeleteTests.swift */; };
|
||||
56419EA424A54063004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3A24A5405F004967E1 /* MutablePersistableRecordDeleteTests.swift */; };
|
||||
56419EA324A54063004967E1 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */; };
|
||||
56419EA424A54063004967E1 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */; };
|
||||
56419EA524A54063004967E1 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */; };
|
||||
56419EA624A54063004967E1 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */; };
|
||||
56419EA724A54063004967E1 /* CursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419D3C24A5405F004967E1 /* CursorTests.swift */; };
|
||||
@@ -504,7 +504,7 @@
|
||||
56419CCF24A54057004967E1 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
56419CD024A54057004967E1 /* GRDBTestCase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GRDBTestCase.swift; sourceTree = "<group>"; };
|
||||
56419CD124A54057004967E1 /* ValueObservationRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationRecordTests.swift; sourceTree = "<group>"; };
|
||||
56419CD224A54057004967E1 /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = "<group>"; };
|
||||
56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = "<group>"; };
|
||||
56419CD324A54057004967E1 /* FTS5TokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TokenizerTests.swift; sourceTree = "<group>"; };
|
||||
56419CD424A54057004967E1 /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
|
||||
56419CD524A54057004967E1 /* AssociationBelongsToSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLTests.swift; sourceTree = "<group>"; };
|
||||
@@ -608,7 +608,7 @@
|
||||
56419D3724A5405E004967E1 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = "<group>"; };
|
||||
56419D3824A5405E004967E1 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = "<group>"; };
|
||||
56419D3924A5405F004967E1 /* QueryInterfaceExtensibilityTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = QueryInterfaceExtensibilityTests.swift; sourceTree = "<group>"; };
|
||||
56419D3A24A5405F004967E1 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = "<group>"; };
|
||||
56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = "<group>"; };
|
||||
56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordTests.swift; sourceTree = "<group>"; };
|
||||
56419D3C24A5405F004967E1 /* CursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CursorTests.swift; sourceTree = "<group>"; };
|
||||
56419D3D24A5405F004967E1 /* DatabasePoolReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReleaseMemoryTests.swift; sourceTree = "<group>"; };
|
||||
@@ -892,11 +892,11 @@
|
||||
56419D0024A5405A004967E1 /* JoinSupportTests.swift */,
|
||||
56419CDC24A54058004967E1 /* MapCursorTests.swift */,
|
||||
56419D0224A5405A004967E1 /* MutablePersistableRecordChangesTests.swift */,
|
||||
56419D3A24A5405F004967E1 /* MutablePersistableRecordDeleteTests.swift */,
|
||||
56419D3A24A5405F004967E1 /* TableRecordDeleteTests.swift */,
|
||||
56419D2F24A5405E004967E1 /* MutablePersistableRecordEncodableTests.swift */,
|
||||
56419D4424A5405F004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
|
||||
56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */,
|
||||
56419CD224A54057004967E1 /* MutablePersistableRecordUpdateTests.swift */,
|
||||
56419CD224A54057004967E1 /* TableRecordUpdateTests.swift */,
|
||||
56419CFD24A5405A004967E1 /* NumericOverflowTests.swift */,
|
||||
56419D4F24A54060004967E1 /* OrderedDictionaryTests.swift */,
|
||||
56419D4524A5405F004967E1 /* PersistableRecordTests.swift */,
|
||||
@@ -1358,7 +1358,7 @@
|
||||
56419EA924A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */,
|
||||
56419E7F24A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */,
|
||||
56419EF124A54063004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */,
|
||||
56419EA324A54063004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */,
|
||||
56419EA324A54063004967E1 /* TableRecordDeleteTests.swift in Sources */,
|
||||
56419EFB24A54063004967E1 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
56419E3D24A54062004967E1 /* FTS3TableBuilderTests.swift in Sources */,
|
||||
56419DDF24A54062004967E1 /* FTS4TableBuilderTests.swift in Sources */,
|
||||
@@ -1367,7 +1367,7 @@
|
||||
56419D9B24A54062004967E1 /* TransactionObserverSavepointsTests.swift in Sources */,
|
||||
56419E0F24A54062004967E1 /* InflectionsTests.swift in Sources */,
|
||||
56419E2724A54062004967E1 /* FoundationURLTests.swift in Sources */,
|
||||
56419DD324A54062004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
56419DD324A54062004967E1 /* TableRecordUpdateTests.swift in Sources */,
|
||||
56419D6D24A54062004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */,
|
||||
56419E2124A54062004967E1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */,
|
||||
56419EDF24A54063004967E1 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
@@ -1581,7 +1581,7 @@
|
||||
56419EAA24A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */,
|
||||
56419E8024A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */,
|
||||
56419EF224A54063004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */,
|
||||
56419EA424A54063004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */,
|
||||
56419EA424A54063004967E1 /* TableRecordDeleteTests.swift in Sources */,
|
||||
56419EFC24A54063004967E1 /* FoundationDateComponentsTests.swift in Sources */,
|
||||
56419E3E24A54062004967E1 /* FTS3TableBuilderTests.swift in Sources */,
|
||||
56419DE024A54062004967E1 /* FTS4TableBuilderTests.swift in Sources */,
|
||||
@@ -1590,7 +1590,7 @@
|
||||
56419D9C24A54062004967E1 /* TransactionObserverSavepointsTests.swift in Sources */,
|
||||
56419E1024A54062004967E1 /* InflectionsTests.swift in Sources */,
|
||||
56419E2824A54062004967E1 /* FoundationURLTests.swift in Sources */,
|
||||
56419DD424A54062004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
56419DD424A54062004967E1 /* TableRecordUpdateTests.swift in Sources */,
|
||||
56419D6E24A54062004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */,
|
||||
56419E2224A54062004967E1 /* AssociationHasOneThroughRowScopeTests.swift in Sources */,
|
||||
56419EE024A54063004967E1 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
56419FC924A540A1004967E1 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFD24A54093004967E1 /* FetchRequestTests.swift */; };
|
||||
56419FCA24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */; };
|
||||
56419FCB24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */; };
|
||||
56419FCC24A540A1004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFF24A54093004967E1 /* MutablePersistableRecordDeleteTests.swift */; };
|
||||
56419FCD24A540A1004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFF24A54093004967E1 /* MutablePersistableRecordDeleteTests.swift */; };
|
||||
56419FCC24A540A1004967E1 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */; };
|
||||
56419FCD24A540A1004967E1 /* TableRecordDeleteTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */; };
|
||||
56419FCE24A540A1004967E1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0024A54093004967E1 /* AssociationBelongsToSQLDerivationTests.swift */; };
|
||||
56419FCF24A540A1004967E1 /* AssociationBelongsToSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0024A54093004967E1 /* AssociationBelongsToSQLDerivationTests.swift */; };
|
||||
56419FD024A540A1004967E1 /* MutablePersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0124A54093004967E1 /* MutablePersistableRecordTests.swift */; };
|
||||
@@ -25,8 +25,8 @@
|
||||
56419FD724A540A1004967E1 /* DatabaseRegionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0424A54093004967E1 /* DatabaseRegionTests.swift */; };
|
||||
56419FD824A540A1004967E1 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */; };
|
||||
56419FD924A540A1004967E1 /* DatabaseRegionObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */; };
|
||||
56419FDA24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0624A54093004967E1 /* MutablePersistableRecordUpdateTests.swift */; };
|
||||
56419FDB24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0624A54093004967E1 /* MutablePersistableRecordUpdateTests.swift */; };
|
||||
56419FDA24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */; };
|
||||
56419FDB24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */; };
|
||||
56419FDC24A540A1004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */; };
|
||||
56419FDD24A540A1004967E1 /* Record+QueryInterfaceRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */; };
|
||||
56419FDE24A540A1004967E1 /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419F0824A54093004967E1 /* NumericOverflowTests.swift */; };
|
||||
@@ -455,14 +455,14 @@
|
||||
47C5D1B9AFFE795AA1D6EA5D /* Pods-GRDBTestsEncrypted.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-GRDBTestsEncrypted.release.xcconfig"; path = "Target Support Files/Pods-GRDBTestsEncrypted/Pods-GRDBTestsEncrypted.release.xcconfig"; sourceTree = "<group>"; };
|
||||
56419EFD24A54093004967E1 /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = "<group>"; };
|
||||
56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = "<group>"; };
|
||||
56419EFF24A54093004967E1 /* MutablePersistableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordDeleteTests.swift; sourceTree = "<group>"; };
|
||||
56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = "<group>"; };
|
||||
56419F0024A54093004967E1 /* AssociationBelongsToSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationBelongsToSQLDerivationTests.swift; sourceTree = "<group>"; };
|
||||
56419F0124A54093004967E1 /* MutablePersistableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordTests.swift; sourceTree = "<group>"; };
|
||||
56419F0224A54093004967E1 /* MutablePersistableRecordEncodableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordEncodableTests.swift; sourceTree = "<group>"; };
|
||||
56419F0324A54093004967E1 /* OrderedDictionaryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionaryTests.swift; sourceTree = "<group>"; };
|
||||
56419F0424A54093004967E1 /* DatabaseRegionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionTests.swift; sourceTree = "<group>"; };
|
||||
56419F0524A54093004967E1 /* DatabaseRegionObservationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationTests.swift; sourceTree = "<group>"; };
|
||||
56419F0624A54093004967E1 /* MutablePersistableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecordUpdateTests.swift; sourceTree = "<group>"; };
|
||||
56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordUpdateTests.swift; sourceTree = "<group>"; };
|
||||
56419F0724A54093004967E1 /* Record+QueryInterfaceRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Record+QueryInterfaceRequestTests.swift"; sourceTree = "<group>"; };
|
||||
56419F0824A54093004967E1 /* NumericOverflowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NumericOverflowTests.swift; sourceTree = "<group>"; };
|
||||
56419F0924A54093004967E1 /* AssociationChainSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationChainSQLTests.swift; sourceTree = "<group>"; };
|
||||
@@ -896,11 +896,11 @@
|
||||
56419F6D24A5409A004967E1 /* JoinSupportTests.swift */,
|
||||
56419F7B24A5409B004967E1 /* MapCursorTests.swift */,
|
||||
56419F4524A54097004967E1 /* MutablePersistableRecordChangesTests.swift */,
|
||||
56419EFF24A54093004967E1 /* MutablePersistableRecordDeleteTests.swift */,
|
||||
56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */,
|
||||
56419F0224A54093004967E1 /* MutablePersistableRecordEncodableTests.swift */,
|
||||
56419F3124A54096004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
|
||||
56419F0124A54093004967E1 /* MutablePersistableRecordTests.swift */,
|
||||
56419F0624A54093004967E1 /* MutablePersistableRecordUpdateTests.swift */,
|
||||
56419F0624A54093004967E1 /* TableRecordUpdateTests.swift */,
|
||||
56419F0824A54093004967E1 /* NumericOverflowTests.swift */,
|
||||
56419F0324A54093004967E1 /* OrderedDictionaryTests.swift */,
|
||||
56419F1A24A54094004967E1 /* PersistableRecordTests.swift */,
|
||||
@@ -1316,7 +1316,7 @@
|
||||
5641A10424A540A1004967E1 /* DatabaseValueTests.swift in Sources */,
|
||||
5641A06824A540A1004967E1 /* RowFetchTests.swift in Sources */,
|
||||
5641A0E024A540A1004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */,
|
||||
56419FDA24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
56419FDA24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */,
|
||||
5641A01024A540A1004967E1 /* RecordEditedTests.swift in Sources */,
|
||||
5641A0A624A540A1004967E1 /* AssociationHasManySQLTests.swift in Sources */,
|
||||
56419FFC24A540A1004967E1 /* QueryInterfaceRequestTests.swift in Sources */,
|
||||
@@ -1366,7 +1366,7 @@
|
||||
5641A11424A540A1004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */,
|
||||
5641A0D024A540A1004967E1 /* FoundationNSDecimalNumberTests.swift in Sources */,
|
||||
5641A0C224A540A1004967E1 /* TransactionObserverTests.swift in Sources */,
|
||||
56419FCC24A540A1004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */,
|
||||
56419FCC24A540A1004967E1 /* TableRecordDeleteTests.swift in Sources */,
|
||||
5641A00624A540A1004967E1 /* SQLExpressionLiteralTests.swift in Sources */,
|
||||
5641A05824A540A1004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */,
|
||||
5641A05624A540A1004967E1 /* AssociationPrefetchingSQLTests.swift in Sources */,
|
||||
@@ -1539,7 +1539,7 @@
|
||||
5641A10524A540A1004967E1 /* DatabaseValueTests.swift in Sources */,
|
||||
5641A06924A540A1004967E1 /* RowFetchTests.swift in Sources */,
|
||||
5641A0E124A540A1004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */,
|
||||
56419FDB24A540A1004967E1 /* MutablePersistableRecordUpdateTests.swift in Sources */,
|
||||
56419FDB24A540A1004967E1 /* TableRecordUpdateTests.swift in Sources */,
|
||||
5641A01124A540A1004967E1 /* RecordEditedTests.swift in Sources */,
|
||||
5641A0A724A540A1004967E1 /* AssociationHasManySQLTests.swift in Sources */,
|
||||
56419FFD24A540A1004967E1 /* QueryInterfaceRequestTests.swift in Sources */,
|
||||
@@ -1589,7 +1589,7 @@
|
||||
5641A11524A540A1004967E1 /* ValueObservationDatabaseValueConvertibleTests.swift in Sources */,
|
||||
5641A0D124A540A1004967E1 /* FoundationNSDecimalNumberTests.swift in Sources */,
|
||||
5641A0C324A540A1004967E1 /* TransactionObserverTests.swift in Sources */,
|
||||
56419FCD24A540A1004967E1 /* MutablePersistableRecordDeleteTests.swift in Sources */,
|
||||
56419FCD24A540A1004967E1 /* TableRecordDeleteTests.swift in Sources */,
|
||||
5641A00724A540A1004967E1 /* SQLExpressionLiteralTests.swift in Sources */,
|
||||
5641A05924A540A1004967E1 /* MutablePersistableRecordChangesTests.swift in Sources */,
|
||||
5641A05724A540A1004967E1 /* AssociationPrefetchingSQLTests.swift in Sources */,
|
||||
|
||||
@@ -6,7 +6,7 @@ class DatabasePoolCrashTests: GRDBCrashTestCase {
|
||||
func testReaderCanNotStartTransaction() {
|
||||
assertCrash("DatabasePool readers can not start transactions or savepoints.") {
|
||||
try dbPool.read { db in
|
||||
let statement = try db.makeUpdateStatement(sql: "BEGIN TRANSACTION")
|
||||
let statement = try db.makeStatement(sql: "BEGIN TRANSACTION")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ class DatabasePoolCrashTests: GRDBCrashTestCase {
|
||||
func testReaderCanNotStartSavepoint() {
|
||||
assertCrash("DatabasePool readers can not start transactions or savepoints.") {
|
||||
try dbPool.read { db in
|
||||
let statement = try db.makeUpdateStatement(sql: "SAVEPOINT foo")
|
||||
let statement = try db.makeStatement(sql: "SAVEPOINT foo")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ class DatabaseValueConvertibleCrashTests: GRDBCrashTestCase {
|
||||
try db.execute(sql: "INSERT INTO ints (int) VALUES (1)")
|
||||
try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)")
|
||||
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT int FROM ints ORDER BY int")
|
||||
let statement = try db.makeStatement(sql: "SELECT int FROM ints ORDER BY int")
|
||||
let sequence = IntConvertible.fetch(statement)
|
||||
for _ in sequence { }
|
||||
}
|
||||
@@ -39,7 +39,7 @@ class DatabaseValueConvertibleCrashTests: GRDBCrashTestCase {
|
||||
try db.execute(sql: "INSERT INTO ints (int) VALUES (1)")
|
||||
try db.execute(sql: "INSERT INTO ints (int) VALUES (NULL)")
|
||||
|
||||
let statement = try db.makeSelectStatement(sql: "SELECT int FROM ints ORDER BY int")
|
||||
let statement = try db.makeStatement(sql: "SELECT int FROM ints ORDER BY int")
|
||||
_ = IntConvertible.fetchAll(statement)
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user