mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-02 04:48:44 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c93ba4fba8 |
No files matched your search
+30
-30
@@ -1,4 +1,4 @@
|
||||
# https://github.com/actions/runner-images/blob/main/images/macos/macos-15-Readme.md
|
||||
# https://github.com/actions/runner-images/blob/main/images/macos/macos-14-Readme.md
|
||||
|
||||
name: "GRDB CI"
|
||||
|
||||
@@ -40,20 +40,20 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
destination: "OS=18.5,name=iPhone 16 Pro"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.1,name=iPhone 15 Pro"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
destination: "OS=18.5,name=Apple TV"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.0,name=Apple TV"
|
||||
name: "tvOS"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: set -o pipefail && env NSUnbufferedIO=YES xcodebuild -project GRDB.xcodeproj -scheme GRDB -destination "${{ matrix.destination }}" OTHER_SWIFT_FLAGS='$(inherited) -D SQLITE_ENABLE_FTS5 -D SQLITE_ENABLE_PREUPDATE_HOOK' GCC_PREPROCESSOR_DEFINITIONS='$(inherited) GRDB_SQLITE_ENABLE_PREUPDATE_HOOK=1' clean test
|
||||
SPM:
|
||||
@@ -66,11 +66,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_SPM test_install_SPM
|
||||
SQLCipher3:
|
||||
@@ -83,11 +83,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher3Encrypted
|
||||
SQLCipher4:
|
||||
@@ -100,11 +100,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_SQLCipher4Encrypted
|
||||
CustomSQLite:
|
||||
@@ -117,11 +117,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_framework_GRDBCustomSQLiteOSX
|
||||
XCFramework:
|
||||
@@ -134,11 +134,11 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_16.4.app"
|
||||
runsOn: macOS-15
|
||||
name: "Xcode 16.4"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
name: "Xcode 16.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/checkout@v4
|
||||
- name: ${{ matrix.name }}
|
||||
run: make test_universal_xcframework
|
||||
|
||||
@@ -2,4 +2,4 @@ version: 1
|
||||
builder:
|
||||
configs:
|
||||
- documentation_targets: [GRDB]
|
||||
swift_version: 6.1
|
||||
swift_version: 6.0
|
||||
+142
-248
@@ -7,16 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 7.x Releases
|
||||
|
||||
- `7.8.x` Releases - [7.8.0](#780)
|
||||
- `7.7.x` Releases - [7.7.0](#770) - [7.7.1](#771)
|
||||
- `7.6.x` Releases - [7.6.0](#760) - [7.6.1](#761)
|
||||
- `7.5.x` Releases - [7.5.0](#750)
|
||||
- `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741)
|
||||
- `7.3.x` Releases - [7.3.0](#730)
|
||||
- `7.2.x` Releases - [7.2.0](#720)
|
||||
- `7.1.x` Releases - [7.1.0](#710)
|
||||
- `7.0.x` Releases - [7.0.0](#700)
|
||||
- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6) - [7.0.0-beta.7](#700-beta7)
|
||||
- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6)
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
@@ -140,103 +131,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 7.8.0
|
||||
|
||||
Released October 2, 2025
|
||||
|
||||
- **New**: Merged Migrations by [@groue](https://github.com/groue) in [#1818](https://github.com/groue/GRDB.swift/pull/1818)
|
||||
|
||||
## 7.7.1
|
||||
|
||||
Released September 29, 2025
|
||||
|
||||
- **Fixed**: Fix the save() method for record types with attached triggers by [@groue](https://github.com/groue) in [#1822](https://github.com/groue/GRDB.swift/pull/1822)
|
||||
|
||||
## 7.7.0
|
||||
|
||||
Released September 23, 2025
|
||||
|
||||
- **New**: Update GRDB7MigrationGuide.md reference by [@emmanuel-ferdman](https://github.com/emmanuel-ferdman) in [#1807](https://github.com/groue/GRDB.swift/pull/1807)
|
||||
- **New**: Persistable Database Views by [@groue](https://github.com/groue) in [#1810](https://github.com/groue/GRDB.swift/pull/1810)
|
||||
- **New**: Support for Xcode 26 by [@groue](https://github.com/groue) in [#1813](https://github.com/groue/GRDB.swift/pull/1813)
|
||||
- **Fixed**: Fix another race condition regarding Task cancellation, completing [#1797](https://github.com/groue/GRDB.swift/pull/1797)
|
||||
|
||||
## 7.6.1
|
||||
|
||||
Released July 23, 2025
|
||||
|
||||
- **Fixed**: Fix race condition regarding Task cancellation by [@groue](https://github.com/groue) in [#1797](https://github.com/groue/GRDB.swift/pull/1797)
|
||||
|
||||
## 7.6.0
|
||||
|
||||
Released July 20, 2025
|
||||
|
||||
- **New**: All closures that accept DatabaseComponents can throw by [@groue](https://github.com/groue) in [#1768](https://github.com/groue/GRDB.swift/pull/1768)
|
||||
- **New**: Add Sendable conformance to DatabasePreUpdateEvent.Kind, matching DatabaseEvent.Kind by [@Jason-Abbott](https://github.com/Jason-Abbott) in [#1773](https://github.com/groue/GRDB.swift/pull/1773)
|
||||
- **New**: Add custom build instruction for hardened runtime by [@Jason-Abbott](https://github.com/Jason-Abbott) in [#1776](https://github.com/groue/GRDB.swift/pull/1776)
|
||||
- **New**: Access task locals from asynchronous database accesses by [@groue](https://github.com/groue) in [#1794](https://github.com/groue/GRDB.swift/pull/1794)
|
||||
- **New**: Throwing row accessors by [@groue](https://github.com/groue) in [#1796](https://github.com/groue/GRDB.swift/pull/1796)
|
||||
|
||||
## 7.5.0
|
||||
|
||||
Released May 11, 2025
|
||||
|
||||
- **New**: Make it possible to create a raw FTS5Pattern without any database connection by [@groue](https://github.com/groue) in [#1764](https://github.com/groue/GRDB.swift/pull/1764)
|
||||
- **New**: Build request with closures by [@groue](https://github.com/groue) in [#1759](https://github.com/groue/GRDB.swift/pull/1759)
|
||||
|
||||
## 7.4.1
|
||||
|
||||
Released March 28, 2025
|
||||
|
||||
- Removed a compiler warning
|
||||
|
||||
## 7.4.0
|
||||
|
||||
Released March 22, 2025
|
||||
|
||||
- **New**: Add the MIN and MAX multi-argument SQL functions to the query interface by [@groue](https://github.com/groue) in [#1745](https://github.com/groue/GRDB.swift/pull/1745)
|
||||
- **Fixed**: Transaction observers are not impacted by Task Cancellation by [@groue](https://github.com/groue) in [#1747](https://github.com/groue/GRDB.swift/pull/1747). This fixes unexpected `ValueObservation` failures in applications that perform asynchronous writes.
|
||||
|
||||
## 7.3.0
|
||||
|
||||
Released February 23, 2025
|
||||
|
||||
- **New**: Support for temporary virtual tables by [@groue](https://github.com/groue) in [#1731](https://github.com/groue/GRDB.swift/pull/1731)
|
||||
- Fixed a compiler error in Xcode 16.3 beta ([#1729](https://github.com/groue/GRDB.swift/pull/1729), [#1730](https://github.com/groue/GRDB.swift/pull/1730))
|
||||
|
||||
## 7.2.0
|
||||
|
||||
Released February 12, 2025
|
||||
|
||||
- **New**: Select ids with selectID() by [@groue](https://github.com/groue) in [#1719](https://github.com/groue/GRDB.swift/pull/1719)
|
||||
|
||||
## 7.1.0
|
||||
|
||||
Released February 5, 2025
|
||||
|
||||
- **New**: Expose `sqlite3_libversion_number` as `Database.sqliteLibVersionNumber` by [@groue](https://github.com/groue) in [#1713](https://github.com/groue/GRDB.swift/pull/1713)
|
||||
- **Fixed**: DatabaseQueue restores its read/write abilities when an async read-only database access is cancelled by [@groue](https://github.com/groue) in [#1716](https://github.com/groue/GRDB.swift/pull/1716)
|
||||
- **New**: Allow RxGRDB to compile without warning by [@groue](https://github.com/groue) in [#1717](https://github.com/groue/GRDB.swift/pull/1717)
|
||||
|
||||
## 7.0.0
|
||||
|
||||
Released January 26, 2025
|
||||
|
||||
- **New**: Support for JSONB expressions by [@groue](https://github.com/groue) in [#1699](https://github.com/groue/GRDB.swift/pull/1699)
|
||||
- **Breaking Change**: Fix inflections of Bias, Focus, Gas, and Lens by [@groue](https://github.com/groue) in [#1703](https://github.com/groue/GRDB.swift/pull/1703)
|
||||
|
||||
## 7.0.0-beta.7
|
||||
|
||||
Released January 19, 2025
|
||||
|
||||
- **New**: Select all columns from a table, but a few ones by [@groue](https://github.com/groue) in [#1700](https://github.com/groue/GRDB.swift/pull/1700)
|
||||
- **Fixed**: Fix typo in Readme.md by [@kevinlg](https://github.com/kevinlg) in [#1697](https://github.com/groue/GRDB.swift/pull/1697)
|
||||
- **New**: Bump custom SQLite to 3.47.2 by [@groue](https://github.com/groue) in [#1696](https://github.com/groue/GRDB.swift/pull/1696)
|
||||
- **Fixed**: Update LICENSE, fix copyright license year by [@JasonnnW3000](https://github.com/JasonnnW3000) in [#1695](https://github.com/groue/GRDB.swift/pull/1695)
|
||||
- **Fixed**: Core: import `ucrt` on Windows for `strcmp` by [@compnerd](https://github.com/compnerd) in [#1662](https://github.com/groue/GRDB.swift/pull/1662)
|
||||
- **Fixed**: Foundation: elide extensions on Windows to match Linux by [@compnerd](https://github.com/compnerd) in [#1661](https://github.com/groue/GRDB.swift/pull/1661)
|
||||
- **Fixed**: Docs: fixes typos "FST"->"FTS" by [@nylki](https://github.com/nylki) in [#1660](https://github.com/groue/GRDB.swift/pull/1660)
|
||||
|
||||
## 7.0.0-beta.6
|
||||
|
||||
Released October 13, 2024
|
||||
@@ -278,7 +172,7 @@ Released September 29, 2024
|
||||
|
||||
[Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) describes in detail how to bump the GRDB version in your application.
|
||||
|
||||
The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
|
||||
The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
|
||||
|
||||
The [demo app](Documentation/DemoApps/) was rewritten from scratch in a brand new Xcode 16 project.
|
||||
|
||||
@@ -337,8 +231,8 @@ Released July 11, 2024
|
||||
Released April 21, 2024
|
||||
|
||||
- **Fixed**: [#1533](https://github.com/groue/GRDB.swift/pull/1533) by [@groue](https://github.com/groue): Fix a bug in Decodable support
|
||||
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/singlerowtables) guide was updated with guidance about default configuration values.
|
||||
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
|
||||
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide was updated with guidance about default configuration values.
|
||||
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
|
||||
|
||||
## 6.26.0
|
||||
|
||||
@@ -363,7 +257,7 @@ Released February 25, 2024
|
||||
|
||||
Released January 21, 2024
|
||||
|
||||
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
|
||||
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
|
||||
- **New**: Associations that involve views instead of tables were already supported, with an explicit `ForeignKey` in their definition. When the foreign key is missing, a clear diagnostic message is now emitted, instead of an unhelpful "no such table" runtime error.
|
||||
|
||||
## 6.24.1
|
||||
@@ -390,7 +284,7 @@ Released November 26, 2023
|
||||
|
||||
- **New**: [#1452](https://github.com/groue/GRDB.swift/pull/1452) by [@groue](https://github.com/groue): SQLite 3.44.0, FILTER and ORDER BY clauses in aggregate functions
|
||||
- **New**: [#1460](https://github.com/groue/GRDB.swift/pull/1460) by [@groue](https://github.com/groue): Explicit change notifications help applications deal with undetected database changes.
|
||||
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
|
||||
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
|
||||
|
||||
## 6.21.0
|
||||
|
||||
@@ -426,8 +320,8 @@ Released October 4, 2023 • [diff](https://github.com/groue/GRDB.swift/compa
|
||||
- **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions
|
||||
- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method.
|
||||
- **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information.
|
||||
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/json) article provides an overview of JSON handling.
|
||||
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
|
||||
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling.
|
||||
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
|
||||
|
||||
## 6.18.0
|
||||
|
||||
@@ -451,14 +345,14 @@ Released July 9, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/
|
||||
- **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13
|
||||
- **New**: :star: [#1405](https://github.com/groue/GRDB.swift/pull/1405) Simplify the declaration of BelongsTo associations in the database schema
|
||||
- **Documentation Update**: The documentation was updated for the new recommended way to declare associations in the database schema, with the `belongsTo()` method introduced by [#1405](https://github.com/groue/GRDB.swift/pull/1405):
|
||||
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
|
||||
- [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema)
|
||||
- [Migrations](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations)
|
||||
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices)
|
||||
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
|
||||
- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema)
|
||||
- [Migrations](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations)
|
||||
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
|
||||
- [Associations](Documentation/AssociationsBasics.md)
|
||||
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/belongstoassociation)
|
||||
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/hasmanyassociation)
|
||||
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/hasoneassociation)
|
||||
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/belongstoassociation)
|
||||
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasmanyassociation)
|
||||
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasoneassociation)
|
||||
|
||||
|
||||
## 6.15.1
|
||||
@@ -475,7 +369,7 @@ Released June 2, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/
|
||||
|
||||
- **New**: [#1382](https://github.com/groue/GRDB.swift/pull/1382) Add `DerivableRequest.all()`
|
||||
- **New**: [#1384](https://github.com/groue/GRDB.swift/pull/1384) Allow ValueObservation to start from a truncated wal file
|
||||
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
|
||||
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
|
||||
|
||||
|
||||
## 6.14.0
|
||||
@@ -510,7 +404,7 @@ Released April 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compar
|
||||
|
||||
Released April 10, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.1...v6.10.2)
|
||||
|
||||
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC.
|
||||
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC.
|
||||
- **Documentation Update**: The [Demo Applications](Documentation/DemoApps/) demonstrate how their `AppDatabase` "database manager" can provide a base database configuration.
|
||||
|
||||
## 6.10.1
|
||||
@@ -537,8 +431,8 @@ Released March 14, 2023 • [diff](https://github.com/groue/GRDB.swift/compar
|
||||
Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.0...v6.9.1)
|
||||
|
||||
- **Documentation Updates**: Moved more README chapters into DocC:
|
||||
- [`RowAdapter`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter)
|
||||
- [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:))
|
||||
- [`RowAdapter`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter)
|
||||
- [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:))
|
||||
|
||||
## 6.9.0
|
||||
|
||||
@@ -547,9 +441,9 @@ Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compar
|
||||
- **New**: [#1348](https://github.com/groue/GRDB.swift/pull/1348) by [@groue](https://github.com/groue): SQLite argument binding optimization
|
||||
- **New**: `FTS5.api(db)` returns a pointer to the `fts5_api` structure, useful for low-level [FTS5 customization](https://www.sqlite.org/fts5.html#extending_fts5).
|
||||
- **Documentation Updates**: Moved more README chapters into DocC, enhanced and extended DocC articles:
|
||||
- [Database Connections](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections)
|
||||
- [Prepared Statements](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statement)
|
||||
- [DatabaseValueConvertible](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasevalueconvertible)
|
||||
- [Database Connections](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections)
|
||||
- [Prepared Statements](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement)
|
||||
- [DatabaseValueConvertible](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible)
|
||||
|
||||
## 6.8.0
|
||||
|
||||
@@ -557,7 +451,7 @@ Released February 24, 2023 • [diff](https://github.com/groue/GRDB.swift/com
|
||||
|
||||
- **New**: [#1338](https://github.com/groue/GRDB.swift/pull/1338) by [@groue](https://github.com/groue): TimestampedRecord sample code
|
||||
- **New**: `EncodableRecord.databaseChanges(modify:)` modifies a record and returns a dictionary of applied changes.
|
||||
- **Documentation Update**: The [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps) article provides a sample `TimestampedRecord` protocol that application may adapt for their own use.
|
||||
- **Documentation Update**: The [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article provides a sample `TimestampedRecord` protocol that application may adapt for their own use.
|
||||
|
||||
## 6.7.0
|
||||
|
||||
@@ -568,7 +462,7 @@ Released February 19, 2023 • [diff](https://github.com/groue/GRDB.swift/com
|
||||
- **Fixed**: [#1327](https://github.com/groue/GRDB.swift/pull/1327) by [@groue](https://github.com/groue): Remove dependency on any specific SwiftLint version.
|
||||
- **New**: [#1331](https://github.com/groue/GRDB.swift/pull/1331) by [@groue](https://github.com/groue): Transaction Date
|
||||
- **New**: [#1336](https://github.com/groue/GRDB.swift/pull/1336) by [@groue](https://github.com/groue): Enable FTS5 by default
|
||||
- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records.
|
||||
- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records.
|
||||
- Added support for `Table` in SQL interpolation.
|
||||
|
||||
## 6.6.1
|
||||
@@ -598,11 +492,11 @@ Released November 28, 2022 • [diff](https://github.com/groue/GRDB.swift/com
|
||||
- **New**: `DatabaseReader.configuration.readQoS` and `writeQoS` return the effective quality of service of read-only and write database accesses. This helps application code avoid priority inversion and similar scheduling misuses when needed.
|
||||
- **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed.
|
||||
- **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime.
|
||||
- **New**: A new [`DatabaseSnapshotReader`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesnapshotreader) protocol was introduced for types that see an unchanging database content (`DatabaseSnapshot` and the new `DatabaseSnapshotPool`).
|
||||
- **New**: [`Database.registerAccess(to:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/registeraccess(to:)) has `ValueObservation` track a region. This helps building optimized observations of a constant database region with [`ValueObservation.trackingConstantRegion(_:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/trackingconstantregion(_:)).
|
||||
- **New**: Open several connections to the same in-memory database with [`DatabaseQueue(named:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue/init(named:configuration:)).
|
||||
- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tabledefinition) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended.
|
||||
- **New**: The [Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) documentation article has a brand new "Database Schema Recommendations" section.
|
||||
- **New**: A new [`DatabaseSnapshotReader`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshotreader) protocol was introduced for types that see an unchanging database content (`DatabaseSnapshot` and the new `DatabaseSnapshotPool`).
|
||||
- **New**: [`Database.registerAccess(to:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/registeraccess(to:)) has `ValueObservation` track a region. This helps building optimized observations of a constant database region with [`ValueObservation.trackingConstantRegion(_:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/trackingconstantregion(_:)).
|
||||
- **New**: Open several connections to the same in-memory database with [`DatabaseQueue(named:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue/init(named:configuration:)).
|
||||
- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended.
|
||||
- **New**: The [Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) documentation article has a brand new "Database Schema Recommendations" section.
|
||||
- **New**: Multiple improvements to the DocC documentation.
|
||||
|
||||
## 6.3.1
|
||||
@@ -1731,7 +1625,7 @@ The [Advanced DatabasePool](README.md#advanced-databasepool) chapter has been ex
|
||||
|
||||
```diff
|
||||
class DatabasePool {
|
||||
+ func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
|
||||
+ func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
+ func invalidateReadOnlyConnections()
|
||||
}
|
||||
|
||||
@@ -1851,7 +1745,7 @@ The [ValueObservation](README.md#valueobservation) chapter has been updated so t
|
||||
}
|
||||
|
||||
extension ValueObservation where Reducer == Void {
|
||||
+ static func tracking<Value>(fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value) -> ValueObservation<ValueReducers.Fetch<Value>>
|
||||
+ static func tracking<Value>(fetch: @escaping (Database) throws -> Value) -> ValueObservation<ValueReducers.Fetch<Value>>
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1896,7 +1790,7 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling)
|
||||
+ var configuration: Configuration { get }
|
||||
+
|
||||
+ #if compiler(>=5.0)
|
||||
+ func asyncRead(_ block: @escaping (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void)
|
||||
+ func asyncRead(_ block: @escaping (Result<Database, Error>) -> Void)
|
||||
+ #endif
|
||||
}
|
||||
|
||||
@@ -1904,7 +1798,7 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling)
|
||||
+ func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
|
||||
+
|
||||
+ #if compiler(>=5.0)
|
||||
+ func asyncWrite<T>(_ updates: @escaping (DatabaseBase<some SQLiteAPI>) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void)
|
||||
+ func asyncWrite<T>(_ updates: @escaping (Database) throws -> T, completion: @escaping (Database, Result<T, Error>) -> Void)
|
||||
+ #endif
|
||||
}
|
||||
```
|
||||
@@ -1984,8 +1878,8 @@ The [ValueObservation Error Handling](README.md#valueobservation-error-handling)
|
||||
|
||||
protocol FetchRequest {
|
||||
+ // deprecated
|
||||
func prepare(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
|
||||
+ func makePreparedRequest(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
|
||||
+ func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
}
|
||||
```
|
||||
|
||||
@@ -2189,37 +2083,37 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati
|
||||
}
|
||||
|
||||
class Row {
|
||||
- static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor
|
||||
- static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row]
|
||||
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row?
|
||||
+ static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor
|
||||
+ static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row]
|
||||
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row?
|
||||
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RowCursor
|
||||
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Row]
|
||||
- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Row?
|
||||
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RowCursor
|
||||
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Row]
|
||||
+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Row?
|
||||
}
|
||||
|
||||
extension FetchableRecord {
|
||||
- static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
|
||||
- static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
|
||||
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
|
||||
+ static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
|
||||
+ static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
|
||||
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
|
||||
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
|
||||
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
|
||||
- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
|
||||
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
|
||||
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
|
||||
+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
- static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
|
||||
- static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
|
||||
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
|
||||
+ static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
|
||||
+ static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
|
||||
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
|
||||
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
|
||||
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
|
||||
- static func fetchOne(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
|
||||
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DatabaseValueCursor<Self>
|
||||
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
|
||||
+ static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
- static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
- static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
|
||||
+ static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
+ static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?]
|
||||
- static func fetchCursor(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
- static func fetchAll(_ db: Database, _ sql: String, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Wrapped?]
|
||||
+ static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
+ static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Wrapped?]
|
||||
}
|
||||
|
||||
extension TableRecord {
|
||||
@@ -2324,7 +2218,7 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati
|
||||
struct ValueObservation<Reducer> {
|
||||
- var extent: Database.TransactionObservationExtent
|
||||
- static func tracking(_ regions: DatabaseRegionConvertible..., reducer: Reducer) -> ValueObservation
|
||||
- static func tracking<Value>(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value) -> ValueObservation<DistinctUntilChangedValueReducer<RawValueReducer<Value>>> where Value: Equatable
|
||||
- static func tracking<Value>(_ regions: DatabaseRegionConvertible..., fetchDistinct fetch: @escaping (Database) throws -> Value) -> ValueObservation<DistinctUntilChangedValueReducer<RawValueReducer<Value>>> where Value: Equatable
|
||||
}
|
||||
```
|
||||
|
||||
@@ -2467,12 +2361,12 @@ It comes with new features, but also a few breaking changes. The [GRDB 4 Migrati
|
||||
+ class DatabaseFuture<Value> { }
|
||||
|
||||
protocol FetchRequest {
|
||||
- func prepare(_ db: DatabaseBase<some SQLiteAPI>) throws -> (SelectStatement, RowAdapter?)
|
||||
+ func prepare(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
|
||||
- func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
|
||||
+ func prepare(_ db: Database, forSingleResult singleResult: Bool) throws -> (SelectStatement, RowAdapter?)
|
||||
}
|
||||
|
||||
struct AnyFetchRequest<T> : FetchRequest {
|
||||
- init(_ prepare: @escaping (DatabaseBase<some SQLiteAPI>) throws -> (SelectStatement, RowAdapter?))
|
||||
- init(_ prepare: @escaping (Database) throws -> (SelectStatement, RowAdapter?))
|
||||
+ init(_ prepare: @escaping (Database, _ singleResult: Bool) throws -> (SelectStatement, RowAdapter?))
|
||||
}
|
||||
|
||||
@@ -2595,24 +2489,24 @@ This release comes with:
|
||||
}
|
||||
|
||||
extension MutablePersistableRecord {
|
||||
+ mutating func updateChanges(_ db: DatabaseBase<some SQLiteAPI>, with change: (inout Self) throws -> Void) throws -> Bool
|
||||
+ mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool
|
||||
}
|
||||
|
||||
extension PersistableRecord {
|
||||
+ func updateChanges(_ db: DatabaseBase<some SQLiteAPI>, with change: (Self) throws -> Void) throws -> Bool
|
||||
+ func updateChanges(_ db: Database, with change: (Self) throws -> Void) throws -> Bool
|
||||
}
|
||||
|
||||
struct ValueObservation<Reducer> {
|
||||
+ static func tracking(
|
||||
+ _ regions: [DatabaseRegionConvertible],
|
||||
+ reducer: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Reducer)
|
||||
+ reducer: @escaping (Database) throws -> Reducer)
|
||||
+ -> ValueObservation
|
||||
}
|
||||
|
||||
+extension ValueObservation where Reducer == Void {
|
||||
+ static func tracking<Value>(
|
||||
+ _ regions: [DatabaseRegionConvertible],
|
||||
+ fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value)
|
||||
+ fetch: @escaping (Database) throws -> Value)
|
||||
+ -> ValueObservation<ValueReducers.Raw<Value>>
|
||||
+ static func combine<R1: ValueReducer, ...>(_ o1: ValueObservation<R1>, ...)
|
||||
+ -> ValueObservation<...>
|
||||
@@ -2697,13 +2591,13 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
|
||||
}
|
||||
|
||||
+protocol DatabaseRegionConvertible {
|
||||
+ func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
|
||||
+ func databaseRegion(_ db: Database) throws -> DatabaseRegion
|
||||
+}
|
||||
+
|
||||
+extension DatabaseRegion: DatabaseRegionConvertible { }
|
||||
+
|
||||
+struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
|
||||
+ init(_ region: @escaping (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion)
|
||||
+ init(_ region: @escaping (Database) throws -> DatabaseRegion)
|
||||
+ init(_ region: DatabaseRegionConvertible)
|
||||
+}
|
||||
|
||||
@@ -2719,7 +2613,7 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
|
||||
+protocol ValueReducer {
|
||||
+ associatedtype Fetched
|
||||
+ associatedtype Value
|
||||
+ func fetch(_ db: DatabaseBase<some SQLiteAPI>) throws -> Fetched
|
||||
+ func fetch(_ db: Database) throws -> Fetched
|
||||
+ mutating func value(_ fetched: Fetched) -> Value?
|
||||
+}
|
||||
+
|
||||
@@ -2728,7 +2622,7 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
|
||||
+}
|
||||
+
|
||||
+struct AnyValueReducer<Fetched, Value>: ValueReducer {
|
||||
+ init(fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Fetched, value: @escaping (Fetched) -> Value?)
|
||||
+ init(fetch: @escaping (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?)
|
||||
+ init<Reducer: ValueReducer>(_ reducer: Reducer) where Reducer.Fetched == Fetched, Reducer.Value == Value
|
||||
+}
|
||||
|
||||
@@ -2751,12 +2645,12 @@ It used to be possible to define custom types that adopt the [DatabaseReader and
|
||||
+extension ValueObservation where Reducer == Void {
|
||||
+ static func tracking<Value>(
|
||||
+ _ regions: DatabaseRegionConvertible...,
|
||||
+ fetch: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value)
|
||||
+ fetch: @escaping (Database) throws -> Value)
|
||||
+ -> ValueObservation<ValueReducers.Raw<Value>>
|
||||
+
|
||||
+ static func tracking<Value>(
|
||||
+ _ regions: DatabaseRegionConvertible...,
|
||||
+ fetchDistinct: @escaping (DatabaseBase<some SQLiteAPI>) throws -> Value)
|
||||
+ fetchDistinct: @escaping (Database) throws -> Value)
|
||||
+ -> ValueObservation<ValueReducers.Distinct<Value>>
|
||||
+ where Value: Equatable
|
||||
+
|
||||
@@ -2801,7 +2695,7 @@ This release comes with **Association Aggregates**. They let you compute values
|
||||
```diff
|
||||
protocol AggregatingRequest {
|
||||
- func group(_ expressions: [SQLExpressible]) -> Self
|
||||
+ func group(_ expressions: @escaping (DatabaseBase<some SQLiteAPI>) throws -> [SQLExpressible]) -> Self
|
||||
+ func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self
|
||||
}
|
||||
|
||||
+extension AggregatingRequest {
|
||||
@@ -2879,7 +2773,7 @@ Released September 16, 2018 • [diff](https://github.com/groue/GRDB.swift/co
|
||||
|
||||
```diff
|
||||
protocol DatabaseWriter : DatabaseReader {
|
||||
+ func concurrentRead<T>(_ block: @escaping (DatabaseBase<some SQLiteAPI>) throws -> T) -> Future<T>
|
||||
+ func concurrentRead<T>(_ block: @escaping (Database) throws -> T) -> Future<T>
|
||||
+ @available(*, deprecated)
|
||||
func readFromCurrentState(_ block: @escaping (Database) -> Void) throws
|
||||
}
|
||||
@@ -2938,10 +2832,10 @@ Fixes:
|
||||
|
||||
```diff
|
||||
class DatabaseQueue {
|
||||
- func write<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
|
||||
+ func write<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
|
||||
- func unsafeReentrantRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
|
||||
+ func unsafeReentrantRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
|
||||
- func write<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
+ func write<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
- func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
|
||||
+ func unsafeReentrantRead<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
}
|
||||
```
|
||||
|
||||
@@ -3189,14 +3083,14 @@ Released February 25, 2018 • [diff](https://github.com/groue/GRDB.swift/com
|
||||
|
||||
extension MutablePersistable {
|
||||
+ @discardableResult
|
||||
+ func updateChanges(_ db: DatabaseBase<some SQLiteAPI>, from record: MutablePersistable) throws -> Bool
|
||||
+ func updateChanges(_ db: Database, from record: MutablePersistable) throws -> Bool
|
||||
+ func databaseEqual(_ record: Self) -> Bool
|
||||
+ func databaseChanges(from record: MutablePersistable) -> [String: DatabaseValue]
|
||||
}
|
||||
class Record {
|
||||
- final func updateChanges(_ db: DatabaseBase<some SQLiteAPI>) throws
|
||||
- final func updateChanges(_ db: Database) throws
|
||||
+ @discardableResult
|
||||
+ final func updateChanges(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
|
||||
+ final func updateChanges(_ db: Database) throws -> Bool
|
||||
}
|
||||
|
||||
+@available(*, deprecated, message: "Prefer changes methods defined on the MutablePersistable protocol: databaseEqual(_:), databaseChanges(from:), updateChanges(from:)")
|
||||
@@ -3212,7 +3106,7 @@ Released February 25, 2018 • [diff](https://github.com/groue/GRDB.swift/com
|
||||
|
||||
extension TableMapping {
|
||||
+ static func selectionSQL(alias: String? = nil) -> String
|
||||
+ static func numberOfSelectedColumns(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
|
||||
+ static func numberOfSelectedColumns(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
+struct EmptyRowAdapter: RowAdapter { }
|
||||
@@ -3335,7 +3229,7 @@ Released January 18, 2018 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
|
||||
protocol Request {
|
||||
+ // Default implementation
|
||||
+ func fetchedRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
|
||||
+ func fetchedRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
+extension Row: RandomAccessCollection {
|
||||
@@ -3402,8 +3296,8 @@ Released January 11, 2018 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
}
|
||||
|
||||
extension RowConvertible where Self: TableMapping {
|
||||
- static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, key: [String: DatabaseValueConvertible?]) throws -> Self?
|
||||
+ static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, key: [String: DatabaseValueConvertible?]?) throws -> Self?
|
||||
- static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Self?
|
||||
+ static func fetchOne(_ db: Database, key: [String: DatabaseValueConvertible?]?) throws -> Self?
|
||||
}
|
||||
```
|
||||
|
||||
@@ -3533,7 +3427,7 @@ Released October 24, 2017 • [diff](https://github.com/groue/GRDB.swift/comp
|
||||
|
||||
```diff
|
||||
extension Request {
|
||||
+ func asSQLRequest(_ db: DatabaseBase<some SQLiteAPI>, cached: Bool = false) throws -> SQLRequest
|
||||
+ func asSQLRequest(_ db: Database, cached: Bool = false) throws -> SQLRequest
|
||||
}
|
||||
struct SQLRequest {
|
||||
+ let sql: String
|
||||
@@ -3784,15 +3678,15 @@ New features have been added in order to plug a few holes and support the [RxGRD
|
||||
|
||||
-extension TableMapping {
|
||||
+extension MutablePersistable {
|
||||
@discardableResult static func deleteAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
|
||||
@discardableResult static func deleteAll<Sequence: Swift.Sequence>(_ db: DatabaseBase<some SQLiteAPI>, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible
|
||||
@discardableResult static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: DatabaseBase<some SQLiteAPI>, key: PrimaryKeyType?) throws -> Bool
|
||||
@discardableResult static func deleteAll(_ db: DatabaseBase<some SQLiteAPI>, keys: [[String: DatabaseValueConvertible?]]) throws -> Int
|
||||
@discardableResult static func deleteOne(_ db: DatabaseBase<some SQLiteAPI>, key: [String: DatabaseValueConvertible?]) throws -> Bool
|
||||
@discardableResult static func deleteAll(_ db: Database) throws -> Int
|
||||
@discardableResult static func deleteAll<Sequence: Swift.Sequence>(_ db: Database, keys: Sequence) throws -> Int where Sequence.Element: DatabaseValueConvertible
|
||||
@discardableResult static func deleteOne<PrimaryKeyType: DatabaseValueConvertible>(_ db: Database, key: PrimaryKeyType?) throws -> Bool
|
||||
@discardableResult static func deleteAll(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> Int
|
||||
@discardableResult static func deleteOne(_ db: Database, key: [String: DatabaseValueConvertible?]) throws -> Bool
|
||||
}
|
||||
-extension QueryInterfaceRequest {
|
||||
+extension QueryInterfaceRequest where RowDecoder: MutablePersistable {
|
||||
@discardableResult func deleteAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
|
||||
@discardableResult func deleteAll(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
protocol TableMapping {
|
||||
@@ -3862,30 +3756,30 @@ New features have been added in order to plug a few holes and support the [RxGRD
|
||||
+ static func fetchCursor(...) throws -> RecordCursor<Self>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: RowConvertible {
|
||||
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<RowDecoder>
|
||||
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> RecordCursor<RowDecoder>
|
||||
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
|
||||
+ func fetchCursor(_ db: Database) throws -> RecordCursor<RowDecoder>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible {
|
||||
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<RowDecoder>
|
||||
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseValueCursor<RowDecoder>
|
||||
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder>
|
||||
+ func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> ColumnCursor<RowDecoder>
|
||||
+ func fetchCursor(_ db: Database) throws -> ColumnCursor<RowDecoder>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible {
|
||||
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<RowDecoder._Wrapped?>
|
||||
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
|
||||
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<RowDecoder._Wrapped?>
|
||||
+ func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder._Wrapped>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: _OptionalProtocol, RowDecoder._Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> NullableColumnCursor<RowDecoder._Wrapped>
|
||||
+ func fetchCursor(_ db: Database) throws -> NullableColumnCursor<RowDecoder._Wrapped>
|
||||
}
|
||||
extension TypedRequest where RowDecoder: Row {
|
||||
- func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseCursor<Row>
|
||||
+ func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowCursor
|
||||
- func fetchCursor(_ db: Database) throws -> DatabaseCursor<Row>
|
||||
+ func fetchCursor(_ db: Database) throws -> RowCursor
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
- @available(*, deprecated) static func primaryKeyRowComparator(_ db: DatabaseBase<some SQLiteAPI>) throws -> (Row, Row) -> Bool
|
||||
- @available(*, deprecated) static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
|
||||
}
|
||||
|
||||
+final class AnyDatabaseReader : DatabaseReader {
|
||||
@@ -4048,7 +3942,7 @@ Released July 13, 2017 • [diff](https://github.com/groue/GRDB.swift/compare
|
||||
}
|
||||
|
||||
protocol DatabaseReader {
|
||||
+ func unsafeReentrantRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
|
||||
+ func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
}
|
||||
```
|
||||
|
||||
@@ -4110,7 +4004,7 @@ Released July 1, 2017 • [diff](https://github.com/groue/GRDB.swift/compare/
|
||||
|
||||
extension TableMapping {
|
||||
+ @available(*, deprecated)
|
||||
static func primaryKeyRowComparator(_ db: DatabaseBase<some SQLiteAPI>) throws -> (Row, Row) -> Bool
|
||||
static func primaryKeyRowComparator(_ db: Database) throws -> (Row, Row) -> Bool
|
||||
}
|
||||
```
|
||||
|
||||
@@ -4235,8 +4129,8 @@ It comes with breaking changes, but the good news is that they are the last (unt
|
||||
}
|
||||
|
||||
extension Request {
|
||||
- func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AnyRequest
|
||||
+ func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AdaptedRequest<Self>
|
||||
- func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AnyRequest
|
||||
+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedRequest<Self>
|
||||
}
|
||||
|
||||
protocol TypedRequest : Request {
|
||||
@@ -4245,8 +4139,8 @@ protocol TypedRequest : Request {
|
||||
}
|
||||
|
||||
extension TypedRequest {
|
||||
- func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AnyTypedRequest<Fetched>
|
||||
+ func adapted(_ adapter: @escaping (DatabaseBase<some SQLiteAPI>) throws -> RowAdapter) -> AdaptedTypedRequest<Self>
|
||||
- func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AnyTypedRequest<Fetched>
|
||||
+ func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedTypedRequest<Self>
|
||||
}
|
||||
```
|
||||
|
||||
@@ -4366,7 +4260,7 @@ Released April 3, 2017
|
||||
- Support for [reactive](https://reactivex.io) extensions:
|
||||
- `SelectStatement.SelectionInfo` is an opaque value that knows which database tables and columns are read by a [select statement](https://github.com/groue/GRDB.swift#prepared-statements).
|
||||
- `DatabaseEventKind.impacts(_ selectionInfo:SelectStatement.SelectionInfo)` tells whether a database change has any impact on the results of a select statement. See [Database Changes Observation](https://github.com/groue/GRDB.swift#database-changes-observation)
|
||||
- `TableMapping.primaryKeyRowComparator(_ db: DatabaseBase<some SQLiteAPI>)` returns a function that compares two database rows and return true if and only if they have the same non-null primary key.
|
||||
- `TableMapping.primaryKeyRowComparator(_ db: Database)` returns a function that compares two database rows and return true if and only if they have the same non-null primary key.
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
@@ -4684,19 +4578,19 @@ Many APIs were changed:
|
||||
}
|
||||
|
||||
final class DatabasePool {
|
||||
- func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
|
||||
- func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
|
||||
- func read<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
- func nonIsolatedRead<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
- func readFromWrite(_ block: @escaping (Database) -> Void)
|
||||
+ func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
|
||||
+ func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
|
||||
+ func read<T>(_ block: (Database) throws -> T) throws -> T
|
||||
+ func nonIsolatedRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
+ func readFromWrite(_ block: @escaping (Database) -> Void) throws
|
||||
}
|
||||
|
||||
protocol DatabaseReader {
|
||||
- func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
|
||||
- func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T
|
||||
+ func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
|
||||
+ func nonIsolatedRead<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T
|
||||
- func read<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
- func nonIsolatedRead<T>(_ block: (Database) throws -> T) rethrows -> T
|
||||
+ func read<T>(_ block: (Database) throws -> T) throws -> T
|
||||
+ func nonIsolatedRead<T>(_ block: (Database) throws -> T) throws -> T
|
||||
}
|
||||
|
||||
protocol DatabaseWriter {
|
||||
@@ -4747,13 +4641,13 @@ Many APIs were changed:
|
||||
}
|
||||
|
||||
protocol MutablePersistable : TableMapping {
|
||||
- func exists(_ db: DatabaseBase<some SQLiteAPI>) -> Bool
|
||||
+ func exists(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
|
||||
- func exists(_ db: Database) -> Bool
|
||||
+ func exists(_ db: Database) throws -> Bool
|
||||
}
|
||||
|
||||
extension MutablePersistable {
|
||||
- func performExists(_ db: DatabaseBase<some SQLiteAPI>) -> Bool
|
||||
+ func performExists(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
|
||||
- func performExists(_ db: Database) -> Bool
|
||||
+ func performExists(_ db: Database) throws -> Bool
|
||||
}
|
||||
|
||||
extension QueryInterfaceRequest {
|
||||
@@ -4780,8 +4674,8 @@ Many APIs were changed:
|
||||
}
|
||||
|
||||
extension TableMapping {
|
||||
- static func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) -> Int
|
||||
+ static func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
|
||||
- static func fetchCount(_ db: Database) -> Int
|
||||
+ static func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
```
|
||||
|
||||
@@ -4959,7 +4853,7 @@ Released October 16, 2016
|
||||
protocol VirtualTableModule {
|
||||
- func moduleArguments(_ definition: TableDefinition) -> [String]
|
||||
+ func moduleArguments(for definition: TableDefinition, in db: Database) throws -> [String]
|
||||
+ func database(_ db: DatabaseBase<some SQLiteAPI>, didCreate tableName: String, using definition: TableDefinition) throws
|
||||
+ func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
|
||||
}
|
||||
```
|
||||
|
||||
@@ -5032,7 +4926,7 @@ Released September 28, 2016
|
||||
|
||||
**Breaking Changes**
|
||||
|
||||
- The SQLForeignKeyAction, SQLColumnType, SQLConflictResolution, and SQLCollation types have been renamed Database.ForeignKeyAction, Database.ColumnType, DatabaseConflictResolution, and Database.CollationName.
|
||||
- The SQLForeignKeyAction, SQLColumnType, SQLConflictResolution, and SQLCollation types have been renamed Database.ForeignKeyAction, Database.ColumnType, Database.ConflictResolution, and Database.CollationName.
|
||||
|
||||
|
||||
## 0.84.0
|
||||
@@ -5295,8 +5189,8 @@ Released September 11, 2016
|
||||
- func databaseDidRollback(db: Database)
|
||||
+ func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
+ func databaseDidChange(with event: DatabaseEvent)
|
||||
+ func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>)
|
||||
+ func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>)
|
||||
+ func databaseDidCommit(_ db: Database)
|
||||
+ func databaseDidRollback(_ db: Database)
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
- func databaseWillChangeWithEvent(event: DatabasePreUpdateEvent)
|
||||
+ func databaseWillChange(with event: DatabasePreUpdateEvent)
|
||||
@@ -5319,19 +5213,19 @@ Released September 11, 2016
|
||||
- func delete(db: Database) throws -> Bool
|
||||
- func exists(db: Database) -> Bool
|
||||
+ mutating func didInsert(with rowID: Int64, for column: String?)
|
||||
+ mutating func insert(_ db: DatabaseBase<some SQLiteAPI>) throws
|
||||
+ func update(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws
|
||||
+ mutating func save(_ db: DatabaseBase<some SQLiteAPI>) throws
|
||||
+ @discardableResult func delete(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
|
||||
+ func exists(_ db: DatabaseBase<some SQLiteAPI>) -> Bool
|
||||
+ mutating func insert(_ db: Database) throws
|
||||
+ func update(_ db: Database, columns: Set<String>) throws
|
||||
+ mutating func save(_ db: Database) throws
|
||||
+ @discardableResult func delete(_ db: Database) throws -> Bool
|
||||
+ func exists(_ db: Database) -> Bool
|
||||
}
|
||||
protocol Persistable : MutablePersistable {
|
||||
- func didInsertWithRowID(rowID: Int64, forColumn column: String?)
|
||||
- func insert(db: Database) throws
|
||||
- func save(db: Database) throws
|
||||
+ func didInsert(with rowID: Int64, for column: String?)
|
||||
+ func insert(_ db: DatabaseBase<some SQLiteAPI>) throws
|
||||
+ func save(_ db: DatabaseBase<some SQLiteAPI>) throws
|
||||
+ func insert(_ db: Database) throws
|
||||
+ func save(_ db: Database) throws
|
||||
}
|
||||
protocol TableMapping {
|
||||
- static func databaseTableName() -> String
|
||||
@@ -5351,10 +5245,10 @@ Released September 11, 2016
|
||||
+ class var databaseTableName: String
|
||||
+ func awakeFromFetch(row: Row)
|
||||
+ func didInsert(with rowID: Int64, for column: String?)
|
||||
+ func update(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws
|
||||
+ func insert(_ db: DatabaseBase<some SQLiteAPI>) throws
|
||||
+ func save(_ db: DatabaseBase<some SQLiteAPI>) throws
|
||||
+ @discardableResult func delete(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
|
||||
+ func update(_ db: Database, columns: Set<String>) throws
|
||||
+ func insert(_ db: Database) throws
|
||||
+ func save(_ db: Database) throws
|
||||
+ @discardableResult func delete(_ db: Database) throws -> Bool
|
||||
}
|
||||
```
|
||||
|
||||
@@ -5363,7 +5257,7 @@ Released September 11, 2016
|
||||
```diff
|
||||
protocol FetchRequest {
|
||||
- func prepare(db: Database) throws -> (SelectStatement, RowAdapter?)
|
||||
+ func prepare(_ db: DatabaseBase<some SQLiteAPI>) throws -> (SelectStatement, RowAdapter?)
|
||||
+ func prepare(_ db: Database) throws -> (SelectStatement, RowAdapter?)
|
||||
}
|
||||
-struct SQLColumn {}
|
||||
+struct Column {}
|
||||
@@ -5943,10 +5837,10 @@ Released May 17, 2016
|
||||
|
||||
```diff
|
||||
struct DatabaseMigrator {
|
||||
- mutating func registerMigration(identifier: String, withDisabledForeignKeyChecks disabledForeignKeyChecks: Bool = false, migrate: (DatabaseBase<some SQLiteAPI>) throws -> Void)
|
||||
+ mutating func registerMigration(identifier: String, migrate: (DatabaseBase<some SQLiteAPI>) throws -> Void)
|
||||
- mutating func registerMigration(identifier: String, withDisabledForeignKeyChecks disabledForeignKeyChecks: Bool = false, migrate: (Database) throws -> Void)
|
||||
+ mutating func registerMigration(identifier: String, migrate: (Database) throws -> Void)
|
||||
+ @available(iOS 8.2, OSX 10.10, *)
|
||||
+ mutating func registerMigrationWithDisabledForeignKeyChecks(identifier: String, migrate: (DatabaseBase<some SQLiteAPI>) throws -> Void)
|
||||
+ mutating func registerMigrationWithDisabledForeignKeyChecks(identifier: String, migrate: (Database) throws -> Void)
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Sharing a Database in an App Group Container
|
||||
============================================
|
||||
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing).
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing).
|
||||
+118
-134
@@ -58,26 +58,15 @@ GRDB Associations
|
||||
Associations streamline common operations in your code, make them safer, and more efficient. For example, consider a library application that has two record types, author and book:
|
||||
|
||||
```swift
|
||||
struct Author: Codable, Identifiable, FetchableRecord, PersistableRecord {
|
||||
struct Author {
|
||||
var id: Int64
|
||||
var name: String
|
||||
|
||||
enum Columns {
|
||||
static let id = Column(CodingKeys.id)
|
||||
static let name = Column(CodingKeys.name)
|
||||
}
|
||||
}
|
||||
|
||||
struct Book: Codable, Identifiable, FetchableRecord, PersistableRecord {
|
||||
struct Book {
|
||||
var id: Int64
|
||||
var authorId: Int64?
|
||||
var title: String
|
||||
|
||||
enum Columns {
|
||||
static let id = Column(CodingKeys.id)
|
||||
static let authorId = Column(CodingKeys.authorId)
|
||||
static let title = Column(CodingKeys.title)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -86,7 +75,7 @@ Now, suppose we wanted to load all books from an existing author. We'd need to d
|
||||
```swift
|
||||
let author: Author = ...
|
||||
let books = try Book
|
||||
.filter { $0.authorId == author.id }
|
||||
.filter(Column("authorId") == author.id)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
@@ -132,7 +121,7 @@ let books = try author.books.fetchAll(db)
|
||||
As for loading all pairs of books and authors, it is not only easier, but also *much more efficient*:
|
||||
|
||||
```swift
|
||||
struct BookInfo: Decodable, FetchableRecord {
|
||||
struct BookInfo: FetchableRecord, Decodable {
|
||||
let book: Book
|
||||
let author: Author?
|
||||
}
|
||||
@@ -141,7 +130,7 @@ let request = Book.including(optional: Book.author)
|
||||
let bookInfos = BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome. The [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:)) method can help you consume the rows fetched from joined queries, as in `SELECT book.*, author.* FROM ...`.
|
||||
Before we dive in, please remember that associations can not generate all possible SQL queries that involve several tables. You may also *prefer* writing SQL, and this is just OK, because your SQL skills are welcome. The [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:)) method can help you consume the rows fetched from joined queries, as in `SELECT book.*, author.* FROM ...`.
|
||||
|
||||
|
||||
## Required Protocols
|
||||
@@ -739,15 +728,9 @@ Your help is needed. You have to instruct GRDB which foreign key to use:
|
||||
|
||||
```swift
|
||||
struct Book: TableRecord {
|
||||
// Table columns
|
||||
enum Columns {
|
||||
static let authorId = Column("authorId")
|
||||
static let translatorId = Column("translatorId")
|
||||
}
|
||||
|
||||
// Define foreign keys
|
||||
static let authorForeignKey = ForeignKey([Columns.authorId])
|
||||
static let translatorForeignKey = ForeignKey([Columns.translatorId])
|
||||
static let authorForeignKey = ForeignKey(["authorId"])
|
||||
static let translatorForeignKey = ForeignKey(["translatorId"])
|
||||
|
||||
// Use foreign keys to define associations:
|
||||
static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
@@ -764,11 +747,24 @@ struct Person: TableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
Foreign keys can also be defined from query interface columns:
|
||||
|
||||
```swift
|
||||
struct Book: TableRecord {
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, title, authorId, translatorId
|
||||
}
|
||||
|
||||
static let authorForeignKey = ForeignKey([Columns.authorId])
|
||||
static let translatorForeignKey = ForeignKey([Columns.translatorId])
|
||||
}
|
||||
```
|
||||
|
||||
When the destination table of a foreign key does not define any primary key, you need to provide the full definition of a foreign key:
|
||||
|
||||
```swift
|
||||
struct Book: TableRecord {
|
||||
static let authorForeignKey = ForeignKey([Columns.authorId], to: [Person.Columns.id])
|
||||
static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])
|
||||
static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
}
|
||||
```
|
||||
@@ -840,8 +836,8 @@ Requests for associated records can be filtered and ordered like all [query inte
|
||||
```swift
|
||||
let novels = try author
|
||||
.books
|
||||
.filter { $0.kind == BookKind.novel }
|
||||
.order(\.publishDate.desc)
|
||||
.filter(Column("kind") == BookKind.novel)
|
||||
.order(Column("publishDate").desc)
|
||||
.fetchAll(db) // [Book]
|
||||
```
|
||||
|
||||
@@ -925,7 +921,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var author: PartialAuthor
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.including(required: Book.author.select { [$0.name, $0.country] })
|
||||
.including(required: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -939,7 +935,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select(\.country)
|
||||
.annotated(withRequired: Book.author.select(Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -986,7 +982,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var author: PartialAuthor?
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.including(optional: Book.author.select { [$0.name, $0.country] })
|
||||
.including(optional: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1000,7 +996,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String?
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select(\.country))
|
||||
.annotated(withOptional: Book.author.select(Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1068,7 +1064,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var books: [PartialBook]
|
||||
}
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books.select { [$0.title, $0.year] })
|
||||
.including(all: Author.books.select(Column("title"), Column("year")))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1083,7 +1079,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
}
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books
|
||||
.select(\.title)
|
||||
.select(Column("title"))
|
||||
.forKey("bookTitles"))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
@@ -1097,7 +1093,7 @@ For example, fetch books along with the name and country of their author:
|
||||
// SELECT book.*, author.name, author.country
|
||||
// FROM book
|
||||
// JOIN author ON author.id = book.authorId
|
||||
let request = Book.annotated(withRequired: Book.author.select { [$0.name, $0.country] })
|
||||
let request = Book.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
|
||||
```
|
||||
|
||||
This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, records are not present in the fetched results: the associated record is "required".
|
||||
@@ -1112,7 +1108,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String // A column of the required associated record
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select { [$0.name, $0.country] })
|
||||
.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1126,7 +1122,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var authorName: String
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select { $0.name.forKey("authorName") })
|
||||
.annotated(withRequired: Book.author.select(Column("name").forKey("authorName")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1139,7 +1135,7 @@ For example, fetch books along with the name and country of their eventual autho
|
||||
// SELECT book.*, author.name, author.country
|
||||
// FROM book
|
||||
// LEFT JOIN author ON author.id = book.authorId
|
||||
let request = Book.annotated(withOptional: Book.author.select { [$0.name, $0.country] })
|
||||
let request = Book.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
|
||||
```
|
||||
|
||||
This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, the columns of the associated record are NULL: the associated record is "optional".
|
||||
@@ -1154,7 +1150,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String? // A column of the optional associated record
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select { [$0.name, $0.country] })
|
||||
.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1168,7 +1164,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var authorName: String?
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select { $0.name.forKey("authorName") })
|
||||
.annotated(withOptional: Book.author.select(Column("name").forKey("authorName")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1182,7 +1178,7 @@ For example, fetch books by French authors:
|
||||
// FROM book
|
||||
// JOIN author ON author.id = book.authorId
|
||||
// AND author.country = 'France'
|
||||
let request = Book.joining(required: Book.author.filter { $0.country == "France" })
|
||||
let request = Book.joining(required: Book.author.filter(Column("country") == "France"))
|
||||
```
|
||||
|
||||
This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. When the associated record does not exist, the base record is not present in the fetched results: the associated record is "required".
|
||||
@@ -1192,7 +1188,7 @@ To fetch results from such a request, you do not need to define a dedicated reco
|
||||
```swift
|
||||
// Fetch all books by French authors
|
||||
let books = try Book
|
||||
.joining(required: Book.author.filter { $0.country == "France" })
|
||||
.joining(required: Book.author.filter(Column("country") == "France"))
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
@@ -1243,7 +1239,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.including(required: Book.author.select { [$0.name, $0.country] })
|
||||
.including(required: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1258,9 +1254,9 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select {
|
||||
[$0.name.forKey("authorName"), $0.country]
|
||||
})
|
||||
.annotated(withRequired: Book.author.select(
|
||||
Column("name").forKey("authorName"),
|
||||
Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1290,7 +1286,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.including(optional: Book.author.select { [$0.name, $0.country] })
|
||||
.including(optional: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1305,9 +1301,9 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select {
|
||||
[$0.name.forKey("authorName"), $0.country]
|
||||
})
|
||||
.annotated(withOptional: Book.author.select(
|
||||
Column("name").forKey("authorName"),
|
||||
Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1337,7 +1333,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books.select { [$0.title, $0.year] })
|
||||
.including(all: Author.books.select(Column("title"), Column("year")))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1350,7 +1346,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books
|
||||
.select(\.title)
|
||||
.select(Column("title"))
|
||||
.forKey("bookTitles"))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
@@ -1464,7 +1460,7 @@ The `filter(_:)`, `filter(id:)`, `filter(ids:)`, `filter(key:)` and `filter(keys
|
||||
// FROM book
|
||||
// JOIN person ON person.id = book.authorId
|
||||
// AND person.countryCode = 'FR'
|
||||
let frenchAuthor = Book.author.filter { $0.countryCode == "FR" }
|
||||
let frenchAuthor = Book.author.filter(Column("countryCode") == "FR")
|
||||
let request = Book.joining(required: frenchAuthor)
|
||||
|
||||
// This request feeds the Book record:
|
||||
@@ -1478,10 +1474,10 @@ The one below fetches all authors along with their novels and poems:
|
||||
```swift
|
||||
let request = Author
|
||||
.including(all: Author.book
|
||||
.filter { $0.kind == "novel" }
|
||||
.filter(Column("kind") == "novel")
|
||||
.forKey("novels"))
|
||||
.including(all: Author.book
|
||||
.filter { $0.kind == "poems" }
|
||||
.filter(Column("kind") == "poems")
|
||||
.forKey("poems"))
|
||||
|
||||
// This request can feed the following record:
|
||||
@@ -1512,7 +1508,7 @@ The `order()` method, that you already know for [sorting simple requests](../REA
|
||||
// FROM book
|
||||
// JOIN person ON person.id = book.authorId
|
||||
// ORDER BY person.name
|
||||
let sortedAuthor = Book.author.order(\.name)
|
||||
let sortedAuthor = Book.author.order(Column("name"))
|
||||
let request = Book.including(required: sortedAuthor)
|
||||
```
|
||||
|
||||
@@ -1523,10 +1519,10 @@ When you sort both the base record and the associated record, the request is sor
|
||||
// FROM book
|
||||
// JOIN person ON person.id = book.authorId
|
||||
// ORDER BY book.publishDate DESC, person.name
|
||||
let sortedAuthor = Book.author.order(\.name)
|
||||
let sortedAuthor = Book.author.order(Column("name"))
|
||||
let request = Book
|
||||
.including(required: sortedAuthor)
|
||||
.order(\.publishDate.desc)
|
||||
.order(Column("publishDate").desc)
|
||||
```
|
||||
|
||||
**There are more sorting options:**
|
||||
@@ -1563,7 +1559,7 @@ The `Team.players` association is ordered by position, so that all team players
|
||||
|
||||
```swift
|
||||
extension Team {
|
||||
static let players = hasMany(Player.self).order(\.position)
|
||||
static let players = hasMany(Player.self).order(Column("position"))
|
||||
|
||||
var players: QueryInterfaceRequest<Player> {
|
||||
request(for: Team.players)
|
||||
@@ -1595,7 +1591,7 @@ Again, the `Team.players` association is ordered by position, so that all team p
|
||||
|
||||
```swift
|
||||
extension Team {
|
||||
static let playerRoles = hasMany(PlayerRole.self).order(\.position)
|
||||
static let playerRoles = hasMany(PlayerRole.self).order(Column("position"))
|
||||
|
||||
static let players = hasMany(Player.self, through: playerRoles, using: PlayerRole.player)
|
||||
|
||||
@@ -1627,9 +1623,9 @@ let teamInfos = try Team
|
||||
|
||||
// Custom ordering
|
||||
let team: Team = ...
|
||||
let players = try team.players.order(\.name).fetchAll(db)
|
||||
let players = try team.players.order(Column("name")).fetchAll(db)
|
||||
let teamInfos = try Team
|
||||
.including(all: Team.players.order(\.name))
|
||||
.including(all: Team.players.order(Column("name")))
|
||||
.asRequest(of: TeamInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1655,7 +1651,7 @@ To specify the selection in a specific request, use the `select` method:
|
||||
// SELECT book.*, author.id, author.name
|
||||
// FROM book
|
||||
// JOIN author ON author.id = book.authorId
|
||||
let restrictedAuthor = Book.author.select { [$0.id, $0.name] }
|
||||
let restrictedAuthor = Book.author.select(Column("id"), Column("name"))
|
||||
let request = Book.including(required: restrictedAuthor)
|
||||
```
|
||||
|
||||
@@ -1677,7 +1673,7 @@ Associations support more refinements:
|
||||
}
|
||||
|
||||
let distinctBookKinds = Author.books
|
||||
.select(\.kind)
|
||||
.select(Column("kind"))
|
||||
.distinct()
|
||||
.forKey("bookKinds")
|
||||
|
||||
@@ -1703,8 +1699,10 @@ Associations support more refinements:
|
||||
}
|
||||
|
||||
let bookKindInfos = Author.books
|
||||
.select { [$0.kind, max($0.year).forKey("maxYear")] }
|
||||
.group(\.kind)
|
||||
.select(
|
||||
Column("kind"),
|
||||
max(Column("year")).forKey("maxYear"))
|
||||
.group(Column("kind"))
|
||||
.forKey("bookKindInfos")
|
||||
|
||||
let authorInfos: [AuthorInfo] = try Author
|
||||
@@ -1774,7 +1772,7 @@ Let's first see a wrong way to do it:
|
||||
// WHERE book.publishDate >= book.deathDate
|
||||
let request = Book
|
||||
.joining(required: Book.author)
|
||||
.filter { $0.publishDate >= $0.deathDate }
|
||||
.filter(Column("publishDate") >= Column("deathDate"))
|
||||
```
|
||||
|
||||
When executed, we'll get a DatabaseError of code 1, "no such column: book.deathDate".
|
||||
@@ -1784,35 +1782,21 @@ That is because the "deathDate" column has been used for filtering books, when i
|
||||
To fix this error, we need a **table alias**:
|
||||
|
||||
```swift
|
||||
let authorAlias = TableAlias<Author>()
|
||||
let authorAlias = TableAlias()
|
||||
```
|
||||
|
||||
We modify the `Book.author` association so that it uses this table alias, and we use the table alias to qualify author columns where needed:
|
||||
|
||||
```swift
|
||||
// Swift 6.1
|
||||
//
|
||||
// > SELECT book.*
|
||||
// > FROM book
|
||||
// > JOIN person ON person.id = book.authorId
|
||||
// > WHERE book.publishDate >= person.deathDate
|
||||
// SELECT book.*
|
||||
// FROM book
|
||||
// JOIN person ON person.id = book.authorId
|
||||
// WHERE book.publishDate >= person.deathDate
|
||||
let request = Book
|
||||
.joining(required: Book.author.aliased(authorAlias))
|
||||
.filter { $0.publishDate >= authorAlias.deathDate }
|
||||
|
||||
// Swift 6.0
|
||||
//
|
||||
// > SELECT book.*
|
||||
// > FROM book
|
||||
// > JOIN person ON person.id = book.authorId
|
||||
// > WHERE book.publishDate >= person.deathDate
|
||||
let request = Book
|
||||
.joining(required: Book.author.aliased(authorAlias))
|
||||
.filter { $0.publishDate >= authorAlias[Author.Columns.deathDate] }
|
||||
.filter(Column("publishDate") >= authorAlias[Column("deathDate")])
|
||||
```
|
||||
|
||||
Note that Swift 6.1 is required for the short syntac `alias.column`. From now on, we will only give examples in Swift 6.1.
|
||||
|
||||
**Table aliases** can also improve control over the ordering of request results. In the example below, we override the [default ordering](#sorting-associations) of associated records by sorting on author names first:
|
||||
|
||||
```swift
|
||||
@@ -1822,7 +1806,7 @@ Note that Swift 6.1 is required for the short syntac `alias.column`. From now on
|
||||
// ORDER BY person.name, book.publishDate
|
||||
let request = Book
|
||||
.joining(required: Book.author.aliased(authorAlias))
|
||||
.order { [authorAlias.name, $0.publishDate] }
|
||||
.order(authorAlias[Column("name")], Column("publishDate"))
|
||||
```
|
||||
|
||||
**Table aliases** can be given a name. This name is guaranteed to be used as the table alias in the SQL query. This guarantee lets you write SQL snippets when you need it:
|
||||
@@ -1833,8 +1817,8 @@ let request = Book
|
||||
// JOIN person a ON a.id = b.authorId
|
||||
// AND a.countryCode = 'FR'
|
||||
// WHERE b.publishDate >= a.deathDate
|
||||
let bookAlias = TableAlias<Book>(name: "b")
|
||||
let authorAlias = TableAlias<Person>(name: "a")
|
||||
let bookAlias = TableAlias(name: "b")
|
||||
let authorAlias = TableAlias(name: "a")
|
||||
let request = Book.aliased(bookAlias)
|
||||
.joining(required: Book.author.aliased(authorAlias)
|
||||
.filter(sql: "a.countryCode = ?", arguments: ["FR"]))
|
||||
@@ -1854,11 +1838,11 @@ let request = Book.aliased(bookAlias)
|
||||
>
|
||||
> ```swift
|
||||
> // NOT IMPLEMENTED: loading all authors along with their posthumous books
|
||||
> let authorAlias = TableAlias<Author>()
|
||||
> let authorAlias = TableAlias()
|
||||
> let request = Author
|
||||
> .aliased(authorAlias)
|
||||
> .including(all: Author.books
|
||||
> .filter { $0.publishDate >= authorAlias.deathDate })
|
||||
> .filter(Column("publishDate") >= authorAlias[Column("deathDate")]))
|
||||
> ```
|
||||
|
||||
|
||||
@@ -1920,7 +1904,7 @@ For example, we can start by defining base requests as extensions to the [Deriva
|
||||
extension DerivableRequest<Author> {
|
||||
/// Filters authors by country
|
||||
func filter(country: String) -> Self {
|
||||
filter { $0.country == country }
|
||||
filter(Column("country") == country)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1933,13 +1917,12 @@ extension DerivableRequest<Book> {
|
||||
|
||||
/// Order books by author name and then book title
|
||||
func orderedByAuthorNameAndYear() -> Self {
|
||||
let authorAlias = TableAlias<Author>()
|
||||
let authorAlias = TableAlias()
|
||||
return self
|
||||
.joining(optional: Book.author.aliased(authorAlias))
|
||||
.order { [
|
||||
authorAlias.name.collating(.localizedCaseInsensitiveCompare),
|
||||
$0.year,
|
||||
] }
|
||||
.order(
|
||||
authorAlias[Column("name")].collating(.localizedCaseInsensitiveCompare),
|
||||
Column("year"))
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -2080,7 +2063,7 @@ Keys can also be customized with the `forKey` method:
|
||||
```swift
|
||||
extension Author {
|
||||
static let novels = books
|
||||
.filter { $0.kind == "novel" }
|
||||
.filter(Column("kind") == "novel")
|
||||
.forKey("novels")
|
||||
}
|
||||
Author.including(all: Author.novels) // association key "novels"
|
||||
@@ -2186,25 +2169,26 @@ struct BookInfo: FetchableRecord {
|
||||
|
||||
init(row: Row) throws {
|
||||
book = try Book(row: row)
|
||||
author = try row.decode(forKey: "author")
|
||||
country = try row.decodeIfPresent(forKey: "country")
|
||||
coverImage = try row.decodeIfPresent(forKey: "coverImage")
|
||||
author = row["author"]
|
||||
country = row["country"]
|
||||
coverImage = row["coverImage"]
|
||||
}
|
||||
}
|
||||
|
||||
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
When you extract a record from a row, GRDB looks up the tree of **association keys**:
|
||||
You are already familiar with row subscripts to decode [database values](../README.md#column-values):
|
||||
|
||||
```swift
|
||||
let author = try row.decode(Author.self, forKey: "author")
|
||||
let name: String = row["name"]
|
||||
```
|
||||
|
||||
If the key is not found, or only associated with columns that are all NULL, an optional record is decoded as nil:
|
||||
When you extract a record instead of a value from a row, GRDB looks up the tree of **association keys**. If the key is not found, or only associated with columns that all contain NULL values, an optional record is decoded as nil:
|
||||
|
||||
```swift
|
||||
let country = try row.decodeIfPresent(Country.self, forKey: "country")
|
||||
let author: Author = row["author"]
|
||||
let country: Country? = row["country"]
|
||||
```
|
||||
|
||||
You can also perform custom navigation in the tree by using *row scopes*. See [Row Adapters] for more information.
|
||||
@@ -2220,7 +2204,7 @@ struct AuthorInfo: FetchableRecord {
|
||||
|
||||
init(row: Row) throws {
|
||||
author = try Author(row: row)
|
||||
books = try row.decode(forKey: "books")
|
||||
books = row["books"]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2304,7 +2288,7 @@ let author: Author = ...
|
||||
let bookCount = try author.books.fetchCount(db) // Int
|
||||
|
||||
// The year of the most recent book by this author
|
||||
let request = author.books.select { max($0.year) }
|
||||
let request = author.books.select(max(yearColumn))
|
||||
let maxBookYear = try Int.fetchOne(db, request) // Int?
|
||||
```
|
||||
|
||||
@@ -2375,7 +2359,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
// GROUP BY author.id
|
||||
let request = Author.annotated(with:
|
||||
Author.books.count,
|
||||
Author.books.max(\.year))
|
||||
Author.books.max(Column("year")))
|
||||
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
|
||||
@@ -2392,13 +2376,13 @@ The default name is built from the aggregating method, the **[association key](#
|
||||
|
||||
| Method | Association Key | Aggregated Column | Aggregate name |
|
||||
| ------ | --------------- | ----------------- | -------------- |
|
||||
| `Author.books.isEmpty`. | `books` | - | `hasNoBook` |
|
||||
| `Author.books.count`. | `books` | - | `bookCount` |
|
||||
| `Author.books.min(\.year)` | `books` | `year` | `minBookYear` |
|
||||
| `Author.books.max(\.year)` | `books` | `year` | `maxBookYear` |
|
||||
| `Author.books.average(\.price)` | `books` | `price` | `averageBookPrice` |
|
||||
| `Author.books.sum(\.awards)` | `books` | `awards` | `bookAwardsSum` |
|
||||
| `Author.books.total((\.awards))` | `books` | `awards` | `bookAwardsSum` ¹ |
|
||||
| `Author.books.isEmpty`. | `books` | - | `hasNoBook` |
|
||||
| `Author.books.count`. | `books` | - | `bookCount` |
|
||||
| `Author.books.min(Column("year"))` | `books` | `year` | `minBookYear` |
|
||||
| `Author.books.max(Column("year"))` | `books` | `year` | `maxBookYear` |
|
||||
| `Author.books.average(Column("price"))` | `books` | `price` | `averageBookPrice` |
|
||||
| `Author.books.sum(Column("awards"))` | `books` | `awards` | `bookAwardsSum` |
|
||||
| `Author.books.total(Column("awards"))` | `books` | `awards` | `bookAwardsSum` ¹ |
|
||||
|
||||
¹ The default name of the `total` aggregate has a `Sum` suffix, just like the `sum` aggregate. Both compute sums, one with the `SUM` SQL function, the other with `TOTAL`. See [SQLite documentation](https://www.sqlite.org/lang_aggfunc.html#sumunc) for the difference between these aggregate functions.
|
||||
|
||||
@@ -2527,7 +2511,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Author.having(Author.books.max(\.year) >= 2010)
|
||||
let request = Author.having(Author.books.max(Column("year")) >= 2010)
|
||||
```
|
||||
|
||||
- Authors who wrote at least one book of kind "novel":
|
||||
@@ -2546,7 +2530,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let novels = Author.books.filter { $0.kind == "novel" }
|
||||
let novels = Author.books.filter(Column("kind") == "novel")
|
||||
let request = Author.having(novels.isEmpty == false)
|
||||
```
|
||||
|
||||
@@ -2632,7 +2616,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Author.having(Author.books.max(\.year) >= 2010)
|
||||
let request = Author.having(Author.books.max(Column("year")) >= 2010)
|
||||
```
|
||||
|
||||
- Arithmetic operators `+`, `-`, `*`, `/`
|
||||
@@ -2672,7 +2656,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Team.annotated(with: Team.players.min(\.score) ?? 0)
|
||||
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
|
||||
```
|
||||
|
||||
- SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions:
|
||||
@@ -2690,7 +2674,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Team.annotated(with: abs(Team.players.max(\.score)))
|
||||
let request = Team.annotated(with: abs(Team.players.max(Column("score"))))
|
||||
```
|
||||
|
||||
### Isolation of Multiple Aggregates
|
||||
@@ -2727,8 +2711,8 @@ In the example below, we use compute two aggregates from the same association `A
|
||||
}
|
||||
|
||||
let request = Author.annotated(with:
|
||||
Author.books.min(\.year), // association key "books"
|
||||
Author.books.max(\.year)) // association key "books"
|
||||
Author.books.min(Column("year")), // association key "books"
|
||||
Author.books.max(Column("year"))) // association key "books"
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
@@ -2798,11 +2782,11 @@ But in the following example, we use the same association `Author.books` twice,
|
||||
}
|
||||
|
||||
let novelCount = Author.books
|
||||
.filter { $0.kind == "novel" }
|
||||
.filter(Column("kind") == "novel")
|
||||
.forKey("novels") // association key "novels"
|
||||
.count
|
||||
let theatrePlayCount = Author.books
|
||||
.filter { $0.kind == "theatrePlay" }
|
||||
.filter(Column("kind") == "theatrePlay")
|
||||
.forKey("theatrePlays") // association key "theatrePlays"
|
||||
.count
|
||||
let request = Author.annotated(with: novelCount, theatrePlayCount)
|
||||
@@ -2829,11 +2813,11 @@ But in the following example, we use the same association `Author.books` twice,
|
||||
```swift
|
||||
// WRONG: not counting distinct sets of associated books
|
||||
let novelCount = Author.books // association key "books"
|
||||
.filter { $0.kind == "novel" }
|
||||
.filter(Column("kind") == "novel")
|
||||
.count
|
||||
.forKey("novelCount")
|
||||
let theatrePlayCount = Author.books // association key "books"
|
||||
.filter { $0.kind == "theatrePlay" }
|
||||
.filter(Column("kind") == "theatrePlay")
|
||||
.count
|
||||
.forKey("theatrePlayCount")
|
||||
let request = Author.annotated(with: novelCount, theatrePlayCount)
|
||||
@@ -2863,11 +2847,11 @@ Those methods are defined on extensions to the `DerivableRequest` protocol:
|
||||
```swift
|
||||
extension DerivableRequest<Author> {
|
||||
func filter(country: String) -> Self {
|
||||
filter { $0.country == country }
|
||||
filter(Column("country") == country)
|
||||
}
|
||||
|
||||
func orderedByName() -> Self {
|
||||
order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
order(Column("name").collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2898,11 +2882,11 @@ See [Recommended Practices for Designing Record Types] for more information.
|
||||
|
||||
```swift
|
||||
// NOT IMPLEMENTED: loading all authors along with their posthumous books
|
||||
let authorAlias = TableAlias<Author>()
|
||||
let authorAlias = TableAlias()
|
||||
let request = Author
|
||||
.aliased(authorAlias)
|
||||
.including(all: Author.books
|
||||
.filter { $0.publishDate >= authorAlias.deathDate })
|
||||
.filter(Column("publishDate") >= authorAlias[Column("deathDate")]))
|
||||
```
|
||||
|
||||
- **You can't use the `including(all:)` method with a [HasMany] and a [HasManyThrough] associations that share the same base association in the same request**:
|
||||
@@ -2979,7 +2963,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[Further Refinements to Associations]: #further-refinements-to-associations
|
||||
[The Types of Associations]: #the-types-of-associations
|
||||
[FetchableRecord]: ../README.md#fetchablerecord-protocols
|
||||
[migration]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations
|
||||
[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
|
||||
[Record]: ../README.md#records
|
||||
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
|
||||
[Associations and the Database Schema]: #associations-and-the-database-schema
|
||||
@@ -3014,16 +2998,16 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
[Isolation of Multiple Aggregates]: #isolation-of-multiple-aggregates
|
||||
[DerivableRequest Protocol]: #derivablerequest-protocol
|
||||
[Known Issues]: #known-issues
|
||||
[Row Adapters]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter
|
||||
[Row Adapters]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter
|
||||
[query interface requests]: ../README.md#requests
|
||||
[TableRecord]: ../README.md#tablerecord-protocol
|
||||
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices
|
||||
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices
|
||||
[regular aggregating methods]: ../README.md#fetching-aggregated-values
|
||||
[EncodableRecord]: ../README.md#persistablerecord-protocol
|
||||
[PersistableRecord]: ../README.md#persistablerecord-protocol
|
||||
[Codable Records]: ../README.md#codable-records
|
||||
[persistence methods]: ../README.md#persistence-methods
|
||||
[database observation tools]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation
|
||||
[database observation tools]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[FAQ]: ../README.md#faq-associations
|
||||
[common table expressions]: CommonTableExpressions.md
|
||||
[Common Table Expressions]: CommonTableExpressions.md
|
||||
|
||||
+12
-12
@@ -226,11 +226,11 @@ This publisher has the same behavior as ValueObservation:
|
||||
|
||||
- It notifies an initial value before the eventual changes.
|
||||
- It may coalesce subsequent changes into a single notification.
|
||||
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
|
||||
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
|
||||
- It only completes when it is cancelled.
|
||||
- By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously.
|
||||
|
||||
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservationscheduler).
|
||||
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservationscheduler).
|
||||
|
||||
For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the publisher is subscribed. It can help your application update the user interface without having to wait for any asynchronous notifications:
|
||||
|
||||
@@ -332,7 +332,7 @@ let hallOfFamePublisher = ValueObservation
|
||||
|
||||
// 2nd request
|
||||
let bestPlayers = try Player
|
||||
.order(\.score.desc)
|
||||
.order(Column("score").desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
@@ -358,7 +358,7 @@ let totalPlayerCountPublisher = ValueObservation
|
||||
// OK
|
||||
let bestPlayerPublisher = ValueObservation
|
||||
.tracking(Player
|
||||
.order(\.score.desc)
|
||||
.order(Column("score").desc)
|
||||
.limit(10)
|
||||
.fetchAll)
|
||||
.publisher(in: dbQueue)
|
||||
@@ -382,23 +382,23 @@ let cancellable = hallOfFamePublisher.sink(
|
||||
[Usage]: #usage
|
||||
[Asynchronous Database Access]: #asynchronous-database-access
|
||||
[Combine]: https://developer.apple.com/documentation/combine
|
||||
[Database Changes Observation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation
|
||||
[Database Changes Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[Database Observation]: #database-observation
|
||||
[Combine and Data Consistency]: #combine-and-data-consistency
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
|
||||
[Demo Application]: DemoApps/GRDBCombineDemo/README.md
|
||||
[SQLite]: http://sqlite.org
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation
|
||||
[SharedValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/sharedvalueobservation
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[SharedValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sharedvalueobservation
|
||||
[`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin
|
||||
[`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling
|
||||
[`SharedValueObservation.publisher()`]: #sharedvalueobservationpublisher
|
||||
[`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue
|
||||
[`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates
|
||||
[`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread
|
||||
[`migratePublisher(_:receiveOn:)`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator/migratepublisher(_:receiveon:)
|
||||
[`migratePublisher(_:receiveOn:)`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator/migratepublisher(_:receiveon:)
|
||||
[configured]: ../README.md#databasepool-configuration
|
||||
[database pool]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool
|
||||
[database queue]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue
|
||||
[database snapshot]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesnapshot
|
||||
[database pool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
|
||||
[database queue]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue
|
||||
[database snapshot]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshot
|
||||
[scheduler]: https://developer.apple.com/documentation/combine/scheduler
|
||||
@@ -31,7 +31,7 @@ The CTE request can be provided as a [query interface request]:
|
||||
// WITH playerName AS (SELECT name FROM player) ...
|
||||
let playerNameCTE = CommonTableExpression(
|
||||
named: "playerName",
|
||||
request: Player.select(\.name))
|
||||
request: Player.select(Column("name")))
|
||||
```
|
||||
|
||||
You can feed a CTE with raw SQL as well (second and third examples use [SQL Interpolation]):
|
||||
@@ -123,7 +123,7 @@ And we can then filter the `player` table with a subquery:
|
||||
// WHERE name = (SELECT * FROM playerName)
|
||||
let request = Player
|
||||
.with(playerNameCTE)
|
||||
.filter { $0.name == playerNameCTE.all() }
|
||||
.filter(Column("name") == playerNameCTE.all())
|
||||
```
|
||||
|
||||
> **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
|
||||
@@ -167,13 +167,13 @@ Common table expressions can also be used as subqueries, when you update or dele
|
||||
// UPDATE player SET name = (SELECT * FROM playerName)
|
||||
try Player
|
||||
.with(playerNameCTE)
|
||||
.updateAll(db) { $0.name.set(to: playerNameCTE.all()) }
|
||||
.updateAll(db, Column("name").set(to: playerNameCTE.all()))
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien')
|
||||
// DELETE FROM player WHERE name = (SELECT * FROM playerName)
|
||||
try Player
|
||||
.with(playerNameCTE)
|
||||
.filter { $0.name == playerNameCTE.all() }
|
||||
.filter(Column("name") == playerNameCTE.all())
|
||||
.deleteAll(db)
|
||||
```
|
||||
|
||||
@@ -281,15 +281,9 @@ struct Chat: Codable, FetchableRecord, PersistableRecord {
|
||||
}
|
||||
|
||||
struct Message: Codable, FetchableRecord, PersistableRecord {
|
||||
var chatId: Int64
|
||||
var chatID: Int64
|
||||
var date: Date
|
||||
...
|
||||
|
||||
enum Columns {
|
||||
static let chatId = Column("chatId")
|
||||
static let date = Column("date")
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -321,8 +315,8 @@ We start by defining the CTE request, which loads the latest messages of all cha
|
||||
```swift
|
||||
// SELECT *, MAX(date) FROM message GROUP BY chatID
|
||||
let latestMessageRequest = Message
|
||||
.annotated { max($0.date) }
|
||||
.group(\.chatId)
|
||||
.annotated(with: max(Column("date")))
|
||||
.group(Column("chatID"))
|
||||
```
|
||||
|
||||
We can now define the CTE for the latest messages:
|
||||
@@ -330,7 +324,7 @@ We can now define the CTE for the latest messages:
|
||||
```swift
|
||||
// WITH latestMessage AS
|
||||
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
|
||||
let latestMessageCTE = CommonTableExpression<Message>(
|
||||
let latestMessageCTE = CommonTableExpression(
|
||||
named: "latestMessage",
|
||||
request: latestMessageRequest)
|
||||
```
|
||||
@@ -343,9 +337,9 @@ The association from a chat to its latest message follows:
|
||||
let latestMessage = Chat.association(
|
||||
to: latestMessageCTE,
|
||||
on: { chat, latestMessage in
|
||||
chat.id == latestMessage.chatId
|
||||
chat[Column("id")] == latestMessage[Column("chatID")]
|
||||
})
|
||||
.order(\.date.desc)
|
||||
.order(Column("date").desc)
|
||||
```
|
||||
|
||||
The final request can now be defined:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
:twisted_rightwards_arrows: Concurrency
|
||||
=======================================
|
||||
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
|
||||
@@ -5,56 +5,54 @@ By default, GRDB uses the version of SQLite that ships with the target operating
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.47.2](https://www.sqlite.org/changes.html).**
|
||||
|
||||
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver).
|
||||
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
|
||||
|
||||
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
|
||||
|
||||
> Warning: The technique described here is not compatible with the Swift Package Manager (SPM). It will create [build issues](https://github.com/groue/GRDB.swift/issues/1709) with SPM companion librairies such as [GRDBQuery](https://github.com/groue/GRDBQuery) or [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting).
|
||||
|
||||
**To install GRDB with a custom SQLite build:**
|
||||
|
||||
1. Clone the GRDB git repository, checkout the latest tagged version:
|
||||
|
||||
|
||||
```sh
|
||||
cd [GRDB directory]
|
||||
git checkout [latest tag]
|
||||
git submodule update --init SQLiteCustom/src
|
||||
```
|
||||
|
||||
|
||||
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
|
||||
|
||||
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool).
|
||||
|
||||
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool).
|
||||
|
||||
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
|
||||
|
||||
4. Create four files in the `GRDBCustomSQLite` folder:
|
||||
|
||||
- `SQLiteLib-USER.xcconfig`: this file sets the extra SQLite compilation flags.
|
||||
|
||||
|
||||
```xcconfig
|
||||
// As many -D options as there are custom SQLite compilation options
|
||||
// Note: there is no space between -D and the option name.
|
||||
CUSTOM_SQLLIBRARY_CFLAGS = -DSQLITE_ENABLE_SNAPSHOT -DSQLITE_ENABLE_FTS5
|
||||
```
|
||||
|
||||
|
||||
- `GRDBCustomSQLite-USER.xcconfig`: this file lets GRDB know about extra compilation flags, and enables extra GRDB APIs.
|
||||
|
||||
|
||||
```xcconfig
|
||||
// As many -D options as there are custom SQLite compilation options
|
||||
// Note: there is one space between -D and the option name.
|
||||
CUSTOM_OTHER_SWIFT_FLAGS = -D SQLITE_ENABLE_SNAPSHOT -D SQLITE_ENABLE_FTS5
|
||||
```
|
||||
|
||||
|
||||
- `GRDBCustomSQLite-USER.h`: this file lets your application know about extra compilation flags.
|
||||
|
||||
|
||||
```c
|
||||
// As many #define as there are custom SQLite compilation options
|
||||
#define SQLITE_ENABLE_SNAPSHOT
|
||||
#define SQLITE_ENABLE_FTS5
|
||||
```
|
||||
|
||||
|
||||
- `GRDBCustomSQLite-INSTALL.sh`: this file installs the three other files.
|
||||
|
||||
|
||||
```sh
|
||||
# License: MIT License
|
||||
# https://github.com/swiftlyfalling/SQLiteLib/blob/master/LICENSE
|
||||
@@ -63,52 +61,52 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
# PROJECT PATHS
|
||||
# !! MODIFY THESE TO MATCH YOUR PROJECT HIERARCHY !!
|
||||
#######################################################
|
||||
|
||||
|
||||
# The path to the folder containing GRDBCustom.xcodeproj:
|
||||
GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB"
|
||||
|
||||
|
||||
# The path to your custom "SQLiteLib-USER.xcconfig":
|
||||
SQLITELIB_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/SQLiteLib-USER.xcconfig"
|
||||
|
||||
|
||||
# The path to your custom "GRDBCustomSQLite-USER.xcconfig":
|
||||
CUSTOMSQLITE_XCCONFIG_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.xcconfig"
|
||||
|
||||
|
||||
# The path to your custom "GRDBCustomSQLite-USER.h":
|
||||
CUSTOMSQLITE_H_USER_PATH="${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-USER.h"
|
||||
|
||||
|
||||
#######################################################
|
||||
#
|
||||
#######################################################
|
||||
|
||||
|
||||
|
||||
|
||||
if [ ! -d "$GRDB_SOURCE_PATH" ];
|
||||
then
|
||||
echo "error: Path to GRDB source (GRDB_SOURCE_PATH) missing/incorrect: $GRDB_SOURCE_PATH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
SyncFileChanges () {
|
||||
SOURCE=$1
|
||||
DESTINATIONPATH=$2
|
||||
DESTINATIONFILENAME=$3
|
||||
DESTINATION="${DESTINATIONPATH}/${DESTINATIONFILENAME}"
|
||||
|
||||
|
||||
if [ ! -f "$SOURCE" ];
|
||||
then
|
||||
echo "error: Source file missing: $SOURCE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
rsync -a "$SOURCE" "$DESTINATION"
|
||||
}
|
||||
|
||||
|
||||
SyncFileChanges $SQLITELIB_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom/src" "SQLiteLib-USER.xcconfig"
|
||||
SyncFileChanges $CUSTOMSQLITE_XCCONFIG_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.xcconfig"
|
||||
SyncFileChanges $CUSTOMSQLITE_H_USER_PATH "${GRDB_SOURCE_PATH}/SQLiteCustom" "GRDBCustomSQLite-USER.h"
|
||||
|
||||
|
||||
echo "Finished syncing"
|
||||
```
|
||||
|
||||
|
||||
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
|
||||
|
||||
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
|
||||
@@ -118,21 +116,17 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
7. Add the `GRDBCustom.framework` from the targeted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
|
||||
|
||||
8. Add a Run Script phase for your target in the **Pre-actions** section of the **Build** tab of your **application scheme**:
|
||||
|
||||
|
||||
```sh
|
||||
source "${PROJECT_DIR}/GRDBCustomSQLite/GRDBCustomSQLite-INSTALL.sh"
|
||||
```
|
||||
|
||||
|
||||
The path should be the path to your `GRDBCustomSQLite-INSTALL.sh` file.
|
||||
|
||||
|
||||
Select your application target in the "Provide build settings from" menu.
|
||||
|
||||
9. Check the "Shared" checkbox of your application scheme (this lets you commit the pre-action in your Version Control System).
|
||||
|
||||
10. If you have enabled "Hardened Runtime" for your target (**Build Settings**/**Signing**) then you may need to check **Disable Library Validation** under the **Hardened Runtime** section of the **Signing & Capabilities** tab.
|
||||
|
||||
(The build error without this exception is "Library not loaded ... different Team IDs")
|
||||
|
||||
Now you can use GRDB with your custom SQLite build:
|
||||
|
||||
```swift
|
||||
|
||||
@@ -158,7 +158,7 @@
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 2600;
|
||||
LastUpgradeCheck = 1600;
|
||||
TargetAttributes = {
|
||||
56CFC6432C9F1DC9000B5023 = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
@@ -293,7 +293,6 @@
|
||||
MTL_FAST_MATH = YES;
|
||||
ONLY_ACTIVE_ARCH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
@@ -351,7 +350,6 @@
|
||||
MTL_ENABLE_DEBUG_INFO = NO;
|
||||
MTL_FAST_MATH = YES;
|
||||
SDKROOT = iphoneos;
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
VALIDATE_PRODUCT = YES;
|
||||
@@ -382,7 +380,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.1;
|
||||
SWIFT_VERSION = 6.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Debug;
|
||||
@@ -411,7 +409,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 6.1;
|
||||
SWIFT_VERSION = 6.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
};
|
||||
name = Release;
|
||||
@@ -427,7 +425,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
||||
SWIFT_VERSION = 6.1;
|
||||
SWIFT_VERSION = 6.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
|
||||
};
|
||||
@@ -444,7 +442,7 @@
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = NO;
|
||||
SWIFT_VERSION = 6.1;
|
||||
SWIFT_VERSION = 6.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo";
|
||||
};
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2600"
|
||||
LastUpgradeVersion = "1600"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -12,10 +12,10 @@ import os.log
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
/// let appDatabase = try AppDatabase(dbQueue)
|
||||
/// ```
|
||||
struct AppDatabase: Sendable {
|
||||
final class AppDatabase: Sendable {
|
||||
/// Access to the database.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
private let dbWriter: any DatabaseWriter
|
||||
|
||||
/// Creates a `AppDatabase`, and makes sure the database schema
|
||||
@@ -30,19 +30,19 @@ struct AppDatabase: Sendable {
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations>
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
|
||||
private var migrator: DatabaseMigrator {
|
||||
var migrator = DatabaseMigrator()
|
||||
|
||||
#if DEBUG
|
||||
// Speed up development by nuking the database when migrations change
|
||||
// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations#The-eraseDatabaseOnSchemaChange-Option>
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations#The-eraseDatabaseOnSchemaChange-Option>
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
#endif
|
||||
|
||||
migrator.registerMigration("v1") { db in
|
||||
// Create a table
|
||||
// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema>
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema>
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
@@ -77,7 +77,7 @@ extension AppDatabase {
|
||||
// }
|
||||
//
|
||||
// Uncomment for enabling SQL logging if the `SQL_TRACE` environment variable is set.
|
||||
// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/trace(options:_:)>
|
||||
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
|
||||
// if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
|
||||
// config.prepareDatabase { db in
|
||||
// let dbName = db.description
|
||||
@@ -93,7 +93,7 @@ extension AppDatabase {
|
||||
// #if DEBUG
|
||||
// // Protect sensitive information by enabling verbose debugging in
|
||||
// // DEBUG builds only.
|
||||
// // See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/configuration/publicstatementarguments>
|
||||
// // See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
|
||||
// config.publicStatementArguments = true
|
||||
// #endif
|
||||
|
||||
@@ -130,7 +130,7 @@ extension AppDatabase {
|
||||
|
||||
/// Refresh all players (by performing some random changes, for demo purpose).
|
||||
func refreshPlayers() async throws {
|
||||
try await dbWriter.write { db in
|
||||
try await dbWriter.write { [self] db in
|
||||
if try Player.all().isEmpty(db) {
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
@@ -165,7 +165,7 @@ extension AppDatabase {
|
||||
}
|
||||
|
||||
/// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`.
|
||||
private func createRandomPlayers(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
private func createRandomPlayers(_ db: Database) throws {
|
||||
for _ in 0..<8 {
|
||||
_ = try Player.makeRandom().inserted(db) // insert but ignore inserted id
|
||||
}
|
||||
|
||||
@@ -64,3 +64,45 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
// Convenience access to player columns in this file
|
||||
private typealias Columns = Player.Columns
|
||||
|
||||
// MARK: - Player Database Requests
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByName().fetchAll(db)
|
||||
/// }
|
||||
func orderedByName() -> Self {
|
||||
// Sort by name in a localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// A request of players ordered by score.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let players: [Player] = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchAll(db)
|
||||
/// }
|
||||
/// let bestPlayer: Player? = try dbWriter.read { db in
|
||||
/// try Player.all().orderedByScore().fetchOne(db)
|
||||
/// }
|
||||
func orderedByScore() -> Self {
|
||||
// Sort by descending score, and then by name, in a
|
||||
// localized case insensitive fashion
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison
|
||||
order(
|
||||
Columns.score.desc,
|
||||
Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ extension AppDatabase {
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// Apply recommendations from
|
||||
// <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections>
|
||||
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
|
||||
|
||||
// Create the "Application Support/Database" directory if needed
|
||||
let fileManager = FileManager.default
|
||||
@@ -47,7 +47,7 @@ extension AppDatabase {
|
||||
/// Creates an empty database for SwiftUI previews
|
||||
static func empty() -> AppDatabase {
|
||||
// Connect to an in-memory database
|
||||
// See https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections
|
||||
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
|
||||
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
@@ -41,22 +41,15 @@ import GRDB
|
||||
let observation = ValueObservation.tracking { [ordering] db in
|
||||
switch ordering {
|
||||
case .byName:
|
||||
try Player
|
||||
.order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
.fetchAll(db)
|
||||
try Player.all().orderedByName().fetchAll(db)
|
||||
case .byScore:
|
||||
try Player
|
||||
.order { [
|
||||
$0.score.desc,
|
||||
$0.name.collating(.localizedCaseInsensitiveCompare),
|
||||
] }
|
||||
.fetchAll(db)
|
||||
try Player.all().orderedByScore().fetchAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
// Start observing the database.
|
||||
// Previous observation, if any, is cancelled.
|
||||
cancellable = observation.start(in: appDatabase.reader, scheduling: .immediate) { error in
|
||||
cancellable = observation.start(in: appDatabase.reader) { error in
|
||||
// Handle error
|
||||
} onChange: { [unowned self] players in
|
||||
self.players = players
|
||||
|
||||
@@ -11,8 +11,8 @@ The topics covered in this demo are:
|
||||
|
||||
- How to setup a database in an iOS app.
|
||||
- How to define a simple [Codable Record](../../../README.md#codable-records).
|
||||
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation).
|
||||
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
|
||||
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
|
||||
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
**Files of interest:**
|
||||
@@ -23,7 +23,7 @@ The topics covered in this demo are:
|
||||
|
||||
- [AppDatabase.swift](GRDBDemo/Database/AppDatabase.swift)
|
||||
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and provides methods that read and write.
|
||||
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and provides methods that read and write.
|
||||
|
||||
`AppDatabase` is [tested](GRDBDemoTests/AppDatabaseTests.swift).
|
||||
|
||||
|
||||
@@ -2,4 +2,4 @@
|
||||
|
||||
FetchedRecordsController has been removed in GRDB 5.
|
||||
|
||||
See [Database Observation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation) for other ways to observe the database.
|
||||
See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for other ways to observe the database.
|
||||
@@ -91,7 +91,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
|
||||
|
||||
**FTS3 and FTS4 full-text tables store and index textual content.**
|
||||
|
||||
Create tables with the `create(virtualTable:options:using:_:)` method:
|
||||
Create tables with the `create(virtualTable:using:)` method:
|
||||
|
||||
```swift
|
||||
// CREATE VIRTUAL TABLE document USING fts3(content)
|
||||
@@ -301,7 +301,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](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -316,7 +316,7 @@ Use them in the [query interface](../README.md#the-query-interface):
|
||||
let documents = try Document.matching(pattern).fetchAll(db)
|
||||
|
||||
// Search in a specific column:
|
||||
let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
|
||||
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
@@ -326,7 +326,7 @@ let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
|
||||
|
||||
To use FTS5, you'll need a [custom SQLite build] that activates the `SQLITE_ENABLE_FTS5` compilation option.
|
||||
|
||||
Create FTS5 tables with the `create(virtualTable:options:using:_:)` method:
|
||||
Create FTS5 tables with the `create(virtualTable:using:)` method:
|
||||
|
||||
```swift
|
||||
// CREATE VIRTUAL TABLE document USING fts5(content)
|
||||
@@ -550,7 +550,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](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -565,7 +565,7 @@ Use them in the [query interface](../README.md#the-query-interface):
|
||||
let documents = try Document.matching(pattern).fetchAll(db)
|
||||
|
||||
// Search in a specific column:
|
||||
let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
|
||||
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
@@ -689,7 +689,7 @@ let books = Book.fetchAll(db, sql: sql, arguments: [pattern])
|
||||
|
||||
**You can define [record](../README.md#records) types around the full-text virtual tables.**
|
||||
|
||||
The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) for more information.
|
||||
The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) for more information.
|
||||
|
||||
## Unicode Full-Text Gotchas
|
||||
|
||||
|
||||
@@ -501,10 +501,10 @@ let publisher = observation
|
||||
This change is innocuous for database boolean values that are `0`, `1`, or `NULL`. However, it is a breaking change for all other database values.
|
||||
|
||||
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
|
||||
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
|
||||
[removeDuplicates]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/removeduplicates()
|
||||
[removeDuplicates]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()
|
||||
[Custom SQL functions]: ../README.md#custom-sql-functions
|
||||
[Batch updates]: ../README.md#update-requests
|
||||
[SQL Interpolation]: SQLInterpolation.md
|
||||
@@ -512,4 +512,4 @@ let publisher = observation
|
||||
[SQLRequest]: ../README.md#custom-requests
|
||||
[QueryInterfaceRequest]: ../README.md#requests
|
||||
[Combine publishers]: Combine.md
|
||||
[Database Observation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation
|
||||
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
@@ -178,12 +178,12 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
|
||||
```swift
|
||||
// GRDB 6: remove those methods from your code
|
||||
func insert(_ db: DatabaseBase<some SQLiteAPI>) throws
|
||||
func insert(_ db: Database) throws
|
||||
func didInsert(with rowID: Int64, for column: String?)
|
||||
func update(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws
|
||||
func save(_ db: DatabaseBase<some SQLiteAPI>) throws
|
||||
func delete(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
|
||||
func exists(_ db: DatabaseBase<some SQLiteAPI>) throws -> Bool
|
||||
func update(_ db: Database, columns: Set<String>) throws
|
||||
func save(_ db: Database) throws
|
||||
func delete(_ db: Database) throws -> Bool
|
||||
func exists(_ db: Database) throws -> Bool
|
||||
```
|
||||
|
||||
- `insert(_:)`: customization is now made with [persistence callbacks].
|
||||
@@ -195,7 +195,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
|
||||
To help you update your applications with persistence callbacks, let's look at two examples.
|
||||
|
||||
First, check the updated [Single-Row Tables](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/singlerowtables) guide, if your application defines a "singleton record".
|
||||
First, check the updated [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide, if your application defines a "singleton record".
|
||||
|
||||
Next, let's consider a record that performs some validation before insertion and updates. In GRDB 5, this would look like:
|
||||
|
||||
@@ -204,12 +204,12 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
struct Link: PersistableRecord {
|
||||
var url: URL
|
||||
|
||||
func insert(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
func insert(_ db: Database) throws {
|
||||
try validate()
|
||||
try performInsert(db)
|
||||
}
|
||||
|
||||
func update(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws {
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
try validate()
|
||||
try performUpdate(db, columns: columns)
|
||||
}
|
||||
@@ -229,7 +229,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
struct Link: PersistableRecord {
|
||||
var url: URL
|
||||
|
||||
func willSave(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
func willSave(_ db: Database) throws {
|
||||
if url.host == nil {
|
||||
throw ValidationError("url must be absolute.")
|
||||
}
|
||||
@@ -249,7 +249,7 @@ The record protocols have been refactored. We tried to keep the amount of modifi
|
||||
class Link: Record {
|
||||
var url: URL
|
||||
|
||||
override func willSave(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
override func willSave(_ db: Database) throws {
|
||||
try super.willSave(db)
|
||||
if url.host == nil {
|
||||
throw ValidationError("url must be absolute.")
|
||||
|
||||
@@ -10,7 +10,6 @@ Migrating From GRDB 6 to GRDB 7
|
||||
- [Column Coding Strategies](#column-coding-strategies)
|
||||
- [Cancellable Async Database Accesses](#cancellable-async-database-accesses)
|
||||
- [Default Transaction Kind](#default-transaction-kind)
|
||||
- [Associations to record types named Bias, Focus, Gas, and Lens](#associations-to-record-types-named-bias-focus-gas-and-lens)
|
||||
- [ValueObservation and the Main Actor](#valueobservation-and-the-main-actor)
|
||||
- [Access to SQLite C functions](#access-to-sqlite-c-functions)
|
||||
- [The Record Base Class is Discouraged](#the-record-base-class-is-discouraged)
|
||||
@@ -97,53 +96,6 @@ try await task.value
|
||||
|
||||
Other asynchronous database accesses, such as methods accepting a completion blocks (`asyncRead`, etc.), Combine publishers, RxSwift observables, do not handle cancellation and will proceed to completion by default.
|
||||
|
||||
## Associations to record types named Bias, Focus, Gas, and Lens
|
||||
|
||||
GRDB 7 has fixed its singularization and pluralization rules for database tables named "bias", "focus", "gas", and "lens".
|
||||
|
||||
If your application defines associations to those tables, you can now rely on proper inflections (pluralization and singularization).
|
||||
|
||||
With GRDB 7, you can remove custom association keys:
|
||||
|
||||
```swift
|
||||
struct Camera: TableRecord {
|
||||
// GRDB 6: fix incorrect GRDB inflection
|
||||
static let lenses = hasMany(Lens.self).forKey("lenses")
|
||||
// GRDB 7
|
||||
static let lenses = hasMany(Lens.self)
|
||||
}
|
||||
```
|
||||
|
||||
If your application was not specifying custom association keys in order to fix the wrong inflections, then it may define types that will no longer decode their properties as intended:
|
||||
|
||||
```swift
|
||||
// Works in GRDB 6, breaks in GRDB 7
|
||||
struct CameraWithLenses: Decodable, FetchableRecord {
|
||||
var camera: Camera
|
||||
var lens: [Lens] // <- incorrect pluralization
|
||||
}
|
||||
let results = Camera
|
||||
.including(all: Camera.lenses)
|
||||
.asRequest(of: CameraWithLenses.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
There are two possible solutions. One is to rename properties, the other is to keep on using the wrong inflection (it's your call):
|
||||
|
||||
```swift
|
||||
// GRDB 7, alternative 1
|
||||
struct CameraWithLenses: Decodable, FetchableRecord {
|
||||
var camera: Camera
|
||||
var lenses: [Lens] // <- fixed pluralization
|
||||
}
|
||||
|
||||
// GRDB 7, alternative 2
|
||||
struct Camera: TableRecord {
|
||||
// Use "lens" instead of "lenses" for GRDB 6 compatibility.
|
||||
static let lenses = hasMany(Lens.self).forKey("lens")
|
||||
}
|
||||
```
|
||||
|
||||
## Default Transaction Kind
|
||||
|
||||
Some applications specify a default transaction kind, which was previously recommended in the [Sharing a Database] guide:
|
||||
@@ -162,7 +114,7 @@ You can still specify a transaction kind explicitly when necessary. See [Transac
|
||||
|
||||
In GRDB 7, `ValueObservation` fosters the main actor, because it is frequently used to automatically update database values on screen.
|
||||
|
||||
By default, its [`start`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be started on the main actor, and its notification callbacks run on the main actor as well.
|
||||
By default, its [`start`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be started on the main actor, and its notification callbacks run on the main actor as well.
|
||||
|
||||
It is not necessary to call `MainActor.assumeIsolated` in `ValueObservation` callbacks:
|
||||
|
||||
@@ -269,14 +221,14 @@ Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non
|
||||
|
||||
## Other Changes
|
||||
|
||||
- `DatabasePool.concurrentRead` has been removed. Use [`asyncConcurrentRead`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool/asyncconcurrentread(_:)) instead.
|
||||
- `DatabasePool.concurrentRead` has been removed. Use [`asyncConcurrentRead`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool/asyncconcurrentread(_:)) instead.
|
||||
|
||||
- The `PersistenceContainer` subscript no longer guarantees that the value returned is the same as what was previously set. It only guarantees that both values are encoded identically in the database.
|
||||
|
||||
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/GRDB.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
|
||||
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/grdb.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
|
||||
|
||||
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide
|
||||
[Sharing a Database]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing
|
||||
[Transaction Kinds]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactions#Transaction-Kinds
|
||||
[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/swiftconcurrency
|
||||
[Record]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/record
|
||||
[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databasesharing
|
||||
[Transaction Kinds]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/transactions#Transaction-Kinds
|
||||
[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/swiftconcurrency
|
||||
[Record]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/record
|
||||
@@ -1,4 +1,4 @@
|
||||
Good Practices for Designing Record Types
|
||||
=========================================
|
||||
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
@@ -1,3 +1,3 @@
|
||||
# Migrations
|
||||
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations).
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations).
|
||||
@@ -32,14 +32,14 @@ try dbQueue.inDatabase { db in
|
||||
CREATE TABLE place (
|
||||
id INTEGER PRIMARY KEY,
|
||||
title TEXT,
|
||||
isFavorite BOOLEAN NOT NULL,
|
||||
favorite BOOLEAN NOT NULL,
|
||||
latitude DOUBLE NOT NULL,
|
||||
longitude DOUBLE NOT NULL
|
||||
)
|
||||
""")
|
||||
|
||||
try db.execute(sql: """
|
||||
INSERT INTO place (title, isFavorite, latitude, longitude)
|
||||
INSERT INTO place (title, favorite, latitude, longitude)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""", arguments: ["Paris", true, 48.85341, 2.3488])
|
||||
let parisId = db.lastInsertedRowID
|
||||
@@ -52,11 +52,11 @@ try! dbQueue.inDatabase { db in
|
||||
let rows = try Row.fetchCursor(db, sql: "SELECT * FROM place")
|
||||
while let row = try rows.next() {
|
||||
let title: String = row["title"]
|
||||
let isFavorite: Bool = row["isFavorite"]
|
||||
let favorite: Bool = row["favorite"]
|
||||
let coordinate = CLLocationCoordinate2D(
|
||||
latitude: row["latitude"],
|
||||
longitude: row["longitude"])
|
||||
print("Fetched", title, isFavorite, coordinate)
|
||||
print("Fetched", title, favorite, coordinate)
|
||||
}
|
||||
|
||||
let placeCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! // Int
|
||||
@@ -69,43 +69,35 @@ try! dbQueue.inDatabase { db in
|
||||
struct Place {
|
||||
var id: Int64?
|
||||
var title: String?
|
||||
var isFavorite: Bool
|
||||
var favorite: Bool
|
||||
var coordinate: CLLocationCoordinate2D
|
||||
}
|
||||
|
||||
// Adopt FetchableRecord
|
||||
extension Place : FetchableRecord {
|
||||
init(row: Row) {
|
||||
id = row[Columns.id]
|
||||
title = row[Columns.title]
|
||||
isFavorite = row[Columns.isFavorite]
|
||||
id = row["id"]
|
||||
title = row["title"]
|
||||
favorite = row["favorite"]
|
||||
coordinate = CLLocationCoordinate2DMake(
|
||||
row[Columns.latitude],
|
||||
row[Columns.longitude])
|
||||
row["latitude"],
|
||||
row["longitude"])
|
||||
}
|
||||
}
|
||||
|
||||
// Adopt TableRecord
|
||||
extension Place : TableRecord {
|
||||
static let databaseTableName = "place"
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let title = Column("title")
|
||||
static let isFavorite = Column("isFavorite")
|
||||
static let latitude = Column("latitude")
|
||||
static let longitude = Column("longitude")
|
||||
}
|
||||
}
|
||||
|
||||
// Adopt MutablePersistableRecord
|
||||
extension Place : MutablePersistableRecord {
|
||||
func encode(to container: inout PersistenceContainer) throws {
|
||||
container[Columns.id] = id
|
||||
container[Columns.title] = title
|
||||
container[Columns.isFavorite] = isFavorite
|
||||
container[Columns.latitude] = coordinate.latitude
|
||||
container[Columns.longitude] = coordinate.longitude
|
||||
container["id"] = id
|
||||
container["title"] = title
|
||||
container["favorite"] = favorite
|
||||
container["latitude"] = coordinate.latitude
|
||||
container["longitude"] = coordinate.longitude
|
||||
}
|
||||
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
@@ -117,13 +109,13 @@ try dbQueue.inDatabase { db in
|
||||
var berlin = Place(
|
||||
id: nil,
|
||||
title: "Berlin",
|
||||
isFavorite: false,
|
||||
favorite: false,
|
||||
coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053))
|
||||
|
||||
try berlin.insert(db)
|
||||
berlin.id // some value
|
||||
|
||||
berlin.isFavorite = true
|
||||
berlin.favorite = true
|
||||
try berlin.update(db)
|
||||
|
||||
// Fetch from SQL
|
||||
@@ -132,10 +124,13 @@ try dbQueue.inDatabase { db in
|
||||
|
||||
//: Avoid SQL with the query interface:
|
||||
|
||||
berlin = try Place.filter { $0.title == "Berlin" }.fetchOne(db)! // Place
|
||||
let title = Column("title")
|
||||
let favorite = Column("favorite")
|
||||
|
||||
berlin = try Place.filter(title == "Berlin").fetchOne(db)! // Place
|
||||
let paris = try Place.fetchOne(db, key: 1) // Place?
|
||||
let favoritePlaces = try Place // [Place]
|
||||
.filter { $0.isFavorite == true }
|
||||
.order { $0.title }
|
||||
.filter(favorite == true)
|
||||
.order(title)
|
||||
.fetchAll(db)
|
||||
}
|
||||
@@ -40,12 +40,12 @@ class TableChangeObserver : NSObject, TransactionObserver {
|
||||
changedTableNames.insert(event.tableName)
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>) {
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
print("Changed table(s): \(changedTableNames.joined(separator: ", "))")
|
||||
changedTableNames = []
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>) {
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
changedTableNames = []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ Columns are special expressions that allow some optimizations and niceties:
|
||||
ValueObservation.tracking { db in
|
||||
try Player.fetchOne(db, id: 1)
|
||||
// or
|
||||
try Player.filter { $0.id == 1 }.fetchOne(db)
|
||||
try Player.filter(Column("id") == 1).fetchOne(db)
|
||||
}
|
||||
|
||||
// Non-optimized observations
|
||||
@@ -110,7 +110,7 @@ Columns are special expressions that allow some optimizations and niceties:
|
||||
// Nicer SQL
|
||||
// SELECT * FROM player WHERE id = 1
|
||||
try Player.fetchOne(db, id: 1)
|
||||
try Player.filter { $0.id == 1 }.fetchOne(db)
|
||||
try Player.filter(Column("id") == 1).fetchOne(db)
|
||||
|
||||
// Less nice SQL
|
||||
// SELECT * FROM player WHERE id = 1 LIMIT 1
|
||||
@@ -123,7 +123,7 @@ Columns are special expressions that allow some optimizations and niceties:
|
||||
|
||||
```swift
|
||||
protocol DatabaseRegionConvertible {
|
||||
func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
|
||||
func databaseRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
```
|
||||
|
||||
@@ -195,7 +195,7 @@ protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredRequest,
|
||||
- `SelectionRequest` provides selection methods such as `select(selection)` or `annotated(with: selection)`
|
||||
- `TableRequest` provides table targeting methods such as `aliased(tableAlias)`
|
||||
|
||||
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) and [Associations](AssociationsBasics.md).
|
||||
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) and [Associations](AssociationsBasics.md).
|
||||
|
||||
### FetchRequest
|
||||
|
||||
@@ -207,10 +207,10 @@ protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
associatedtype RowDecoder
|
||||
|
||||
/// Returns a PreparedRequest that is ready to be executed.
|
||||
func makePreparedRequest(_ db: DatabaseBase<some SQLiteAPI>, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
```
|
||||
|
||||
@@ -261,7 +261,7 @@ The basic value types conform to [DatabaseValueConvertible] so that they can fee
|
||||
```swift
|
||||
// SELECT * FROM player WHERE name = 'O''Brien'
|
||||
// ~~~~~~~~~~
|
||||
Player.filter { $0.name == "O'Brien" }
|
||||
Player.filter(Column("name") == "O'Brien")
|
||||
```
|
||||
|
||||
### QueryInterfaceRequest
|
||||
@@ -346,9 +346,8 @@ Functions and methods that build an SQL expression should return an SQLExpressio
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE LENGTH(name) > 0
|
||||
Player.filter {
|
||||
length($0.name) > 0 // SQLExpression
|
||||
}
|
||||
let expression = length(Column("name")) > 0 // SQLExpression
|
||||
Player.filter(expression)
|
||||
```
|
||||
|
||||
When it looks like GRDB APIs are unable to build a particular expression, use [SQL]:
|
||||
@@ -359,7 +358,7 @@ func date(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
|
||||
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
|
||||
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
|
||||
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
```
|
||||
|
||||
This technique, based on [SQL Interpolation], is composable and works well even when several tables are involved. See how the `createdAt` column below is correctly attributed to the `player` table:
|
||||
@@ -369,7 +368,7 @@ This technique, based on [SQL Interpolation], is composable and works well even
|
||||
// JOIN team ON team.id = player.teamId
|
||||
// WHERE DATE(player.createdAt) = '2020-01-23'
|
||||
let request = Player
|
||||
.filter { date($0.createdAt) == "2020-01-23" }
|
||||
.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
.including(required: Player.team)
|
||||
```
|
||||
|
||||
@@ -498,7 +497,7 @@ protocol SQLSelectable {
|
||||
SQLSelectable feeds the `select()` method of the query interface:
|
||||
|
||||
```swift
|
||||
Player.select(.allColumns)
|
||||
Player.select(AllColumns())
|
||||
Player.select(Column("name"), Column("score"))
|
||||
```
|
||||
|
||||
@@ -506,7 +505,7 @@ All [SQLSpecificExpressible] values are selectable. Other selectable values are:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
Player.select(.allColumns)
|
||||
Player.select(AllColumns())
|
||||
|
||||
// SELECT MAX(score) AS maxScore FROM player
|
||||
Player.select(max(Column("score")).forKey("maxScore"))
|
||||
@@ -584,7 +583,7 @@ SQLSubqueryable provides the GRDB support for subqueries. Its [SQLSpecificExpres
|
||||
// SELECT * FROM player
|
||||
// WHERE score >= (SELECT AVG(score) FROM player)
|
||||
let averageScore = Player.select(average(Column("score")))
|
||||
Player.filter { $0.score >= averageScore }
|
||||
Player.filter(Column("score") >= averageScore)
|
||||
```
|
||||
|
||||
SQLSubqueryable has the `contains(_:)` and `exists()` methods that support the `value IN (subquery)` and `EXISTS (subquery)` expressions.
|
||||
@@ -608,8 +607,8 @@ myRequest(Player.select(...).filter(...))
|
||||
[association aggregates]: AssociationsBasics.md#association-aggregates
|
||||
[Column]: #column
|
||||
[ColumnExpression]: #columnexpression
|
||||
[DatabaseRegionConvertible]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionconvertible
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation
|
||||
[DatabaseRegionConvertible]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionconvertible
|
||||
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
|
||||
[DatabaseValue]: #databasevalue
|
||||
[DatabaseValueConvertible]: #databasevalueconvertible
|
||||
[DerivableRequest]: #derivablerequest
|
||||
|
||||
@@ -175,7 +175,7 @@ func date(_ expression: SQLExpressible) -> SQLExpression {
|
||||
SQL("DATE(\(expression))").sqlExpression
|
||||
}
|
||||
|
||||
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
|
||||
let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
```
|
||||
|
||||
|
||||
@@ -204,7 +204,7 @@ Let's extend Player with database methods.
|
||||
```swift
|
||||
extension Player {
|
||||
/// Deletes all player with no score
|
||||
static func deleteAllWithoutScore(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
static func deleteAllWithoutScore(_ db: Database) throws {
|
||||
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
|
||||
}
|
||||
}
|
||||
@@ -365,7 +365,7 @@ Let's extend Player with database methods.
|
||||
|
||||
This chapter lists all kinds of supported interpolations.
|
||||
|
||||
- Types adopting the [TableRecord] protocol and [Table](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/table) instances:
|
||||
- Types adopting the [TableRecord] protocol and [Table](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/table) instances:
|
||||
|
||||
```swift
|
||||
struct Player: TableRecord { ... }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Sharing a Database
|
||||
==================
|
||||
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing).
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing).
|
||||
@@ -1,4 +1,4 @@
|
||||
Single-Row Tables
|
||||
=================
|
||||
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/singlerowtables).
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables).
|
||||
@@ -90,7 +90,7 @@ For your convenience, those record protocols can be derived from the [Decodable
|
||||
|
||||
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
|
||||
|
||||
See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
|
||||
See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
|
||||
|
||||
|
||||
### Allow database records to cross threads
|
||||
@@ -149,16 +149,16 @@ Next, you choose the dispatch queue on which notifications happen (generally the
|
||||
|
||||
Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, or SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported.
|
||||
|
||||
See [Database Observation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation) for further information.
|
||||
See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for further information.
|
||||
|
||||
|
||||
### Non-blocking database reads
|
||||
|
||||
GRDB ships with two ways to access databases, [database queues](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue) and [pools](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool).
|
||||
GRDB ships with two ways to access databases, [database queues](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue) and [pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool).
|
||||
|
||||
Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen.
|
||||
|
||||
[Database pools](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
|
||||
[Database pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured).
|
||||
|
||||
|
||||
### Strong and clear multi-threading guarantees
|
||||
@@ -190,7 +190,7 @@ Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and
|
||||
|
||||
For detailed information about GRDB concurrency, check the [Concurrency Guide].
|
||||
|
||||
For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
|
||||
For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
|
||||
|
||||
### Never pay for using raw SQL
|
||||
@@ -207,13 +207,13 @@ try player.updateChanges {
|
||||
|
||||
// SELECT * FROM player ORDER BY score DESC LIMIT 10
|
||||
let bestPlayers: [Player] = try Player
|
||||
.order(\.score.desc)
|
||||
.order(scoreColumn.desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
// SELECT MAX(score) FROM player
|
||||
let maximumScore: Int? = try Player
|
||||
.select { max($0.score) }
|
||||
.select(max(scoreColumn))
|
||||
.asRequestOf(Int.self)
|
||||
.fetchOne(db)
|
||||
|
||||
@@ -285,12 +285,12 @@ If this little tour of GRDB has convinced you, the real trip starts here: [GRDB]
|
||||
|
||||
Happy GRDB! :gift:
|
||||
|
||||
[Concurrency Guide]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency
|
||||
[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
|
||||
[Core Data]: https://developer.apple.com/documentation/coredata
|
||||
[DatabasePool]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool
|
||||
[DatabasePool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
|
||||
[Diesel]: http://diesel.rs
|
||||
[FCModel]: https://github.com/marcoarment/FCModel
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation
|
||||
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
|
||||
[Fluent]: https://github.com/vapor/fluent
|
||||
[FMDB]: https://github.com/ccgus/fmdb
|
||||
[GRDB]: https://github.com/groue/GRDB.swift
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '7.8.0'
|
||||
s.version = '7.0.0-beta.6'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
@@ -9,7 +9,7 @@ Pod::Spec.new do |s|
|
||||
s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" }
|
||||
s.module_name = 'GRDB'
|
||||
|
||||
s.swift_versions = ['6.1']
|
||||
s.swift_versions = ['6']
|
||||
s.ios.deployment_target = '13.0'
|
||||
s.osx.deployment_target = '10.15'
|
||||
s.watchos.deployment_target = '7.0'
|
||||
@@ -21,7 +21,7 @@ Pod::Spec.new do |s|
|
||||
ss.framework = 'Foundation'
|
||||
ss.library = 'sqlite3'
|
||||
ss.xcconfig = {
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5 -D GRDBFRAMEWORK',
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_ENABLE_FTS5',
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
@@ -68,7 +68,6 @@
|
||||
562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; };
|
||||
562206081E420EA4005860AC /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; };
|
||||
5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; };
|
||||
56231A442DCF3A19007676E4 /* TableAlias.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231A432DCF3A19007676E4 /* TableAlias.swift */; };
|
||||
562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; };
|
||||
562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; };
|
||||
5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; };
|
||||
@@ -81,7 +80,6 @@
|
||||
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ECF25D1ACD0008C2BDD /* Table.swift */; };
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56256ED825D1B316008C2BDD /* ForeignKey.swift */; };
|
||||
562756431E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562756421E963AAC0035B653 /* DatabaseWriterTests.swift */; };
|
||||
562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */; };
|
||||
562B58CB2A29BBEF00E8C75D /* Issue1383.sqlite in Resources */ = {isa = PBXBuildFile; fileRef = 562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */; };
|
||||
562EA8261F17B2AC00FA528C /* CompilationProtocolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */; };
|
||||
562EA82F1F17B9EB00FA528C /* CompilationSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */; };
|
||||
@@ -224,7 +222,6 @@
|
||||
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
|
||||
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */; };
|
||||
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56848972242DE36F002F9702 /* ValueObservationScheduler.swift */; };
|
||||
568515A42E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */; };
|
||||
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */; };
|
||||
56894F752606576600268F4D /* FoundationDecimalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F742606576600268F4D /* FoundationDecimalTests.swift */; };
|
||||
56894FB72606589700268F4D /* Decimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56894F94260657D600268F4D /* Decimal.swift */; };
|
||||
@@ -275,7 +272,6 @@
|
||||
56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */; };
|
||||
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
|
||||
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; };
|
||||
56AC93DF2E291C4700DB6C74 /* DispatchQueueActor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */; };
|
||||
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; };
|
||||
56AE6424222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */; };
|
||||
56AFEF2F29969F6E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */; };
|
||||
@@ -290,7 +286,6 @@
|
||||
56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B01DA51D010002DA19 /* FTS5TokenizerDescriptor.swift */; };
|
||||
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964B81DA51D0A0002DA19 /* FTS5Pattern.swift */; };
|
||||
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */; };
|
||||
56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */; };
|
||||
56BF2282241781C5003D86EB /* UtilsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF2281241781C5003D86EB /* UtilsTests.swift */; };
|
||||
56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; };
|
||||
56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; };
|
||||
@@ -492,7 +487,6 @@
|
||||
561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
|
||||
561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
56231A432DCF3A19007676E4 /* TableAlias.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableAlias.swift; sourceTree = "<group>"; };
|
||||
562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = "<group>"; };
|
||||
5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = "<group>"; };
|
||||
5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = "<group>"; };
|
||||
@@ -506,7 +500,6 @@
|
||||
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>"; };
|
||||
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSource.swift; sourceTree = "<group>"; };
|
||||
562B58CA2A29BBEF00E8C75D /* Issue1383.sqlite */ = {isa = PBXFileReference; lastKnownFileType = file; path = Issue1383.sqlite; sourceTree = "<group>"; };
|
||||
562EA8251F17B2AC00FA528C /* CompilationProtocolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationProtocolTests.swift; sourceTree = "<group>"; };
|
||||
562EA82E1F17B9EB00FA528C /* CompilationSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CompilationSubClassTests.swift; sourceTree = "<group>"; };
|
||||
@@ -678,7 +671,6 @@
|
||||
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
|
||||
56848972242DE36F002F9702 /* ValueObservationScheduler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationScheduler.swift; sourceTree = "<group>"; };
|
||||
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecordMappedOnMutableViewTests.swift; sourceTree = "<group>"; };
|
||||
5685C1922AD52EE600DA4B7A /* ListDumpFormat.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ListDumpFormat.swift; sourceTree = "<group>"; };
|
||||
5687359E1CEDE16C009B9116 /* Betty.jpeg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = Betty.jpeg; sourceTree = "<group>"; };
|
||||
56894F742606576600268F4D /* FoundationDecimalTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationDecimalTests.swift; sourceTree = "<group>"; };
|
||||
@@ -775,7 +767,6 @@
|
||||
56A8C22F1D1914540096E9D4 /* UUID.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UUID.swift; sourceTree = "<group>"; };
|
||||
56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSUUIDTests.swift; sourceTree = "<group>"; };
|
||||
56AACAA722ACED7100A40F2A /* Fetch.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Fetch.swift; sourceTree = "<group>"; };
|
||||
56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DispatchQueueActor.swift; sourceTree = "<group>"; };
|
||||
56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HasOneThroughAssociation.swift; sourceTree = "<group>"; };
|
||||
56AE6423222AAC9500AD1B0B /* AssociationHasOneThroughSQLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLTests.swift; sourceTree = "<group>"; };
|
||||
56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleEscapingTests.swift; sourceTree = "<group>"; };
|
||||
@@ -797,7 +788,6 @@
|
||||
56B964C11DA521450002DA19 /* FTS5RecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5RecordTests.swift; sourceTree = "<group>"; };
|
||||
56B964C21DA521450002DA19 /* FTS5TableBuilderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5TableBuilderTests.swift; sourceTree = "<group>"; };
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SchedulingWatchdog.swift; sourceTree = "<group>"; };
|
||||
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseSchemaSourceTests.swift; sourceTree = "<group>"; };
|
||||
56BF2281241781C5003D86EB /* UtilsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UtilsTests.swift; sourceTree = "<group>"; };
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSavepointTests.swift; sourceTree = "<group>"; };
|
||||
56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = "<group>"; };
|
||||
@@ -1003,7 +993,6 @@
|
||||
56B021C81D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */,
|
||||
563363A91C933FF8000BE133 /* MutablePersistableRecordTests.swift */,
|
||||
563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */,
|
||||
568515A32E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift */,
|
||||
);
|
||||
name = PersistableRecord;
|
||||
sourceTree = "<group>";
|
||||
@@ -1295,7 +1284,6 @@
|
||||
568D13182207213E00674B58 /* SQLQueryGenerator.swift */,
|
||||
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */,
|
||||
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */,
|
||||
56231A432DCF3A19007676E4 /* TableAlias.swift */,
|
||||
);
|
||||
path = SQLGeneration;
|
||||
sourceTree = "<group>";
|
||||
@@ -1493,7 +1481,6 @@
|
||||
56EA86931C91DFE7002BB4DF /* DatabaseReaderTests.swift */,
|
||||
564CE5BD21B8FFA300652B19 /* DatabaseRegionObservationTests.swift */,
|
||||
56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */,
|
||||
56BCA2612E6C28EF00E4F08D /* DatabaseSchemaSourceTests.swift */,
|
||||
568EB71D2921234800E59445 /* DatabaseSnapshotPoolTests.swift */,
|
||||
566A8424204120B700E50BFD /* DatabaseSnapshotTests.swift */,
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */,
|
||||
@@ -1600,19 +1587,18 @@
|
||||
569EF0E1200D2D8400A9FA45 /* DatabaseRegion.swift */,
|
||||
564CE5AB21B8FAB400652B19 /* DatabaseRegionObservation.swift */,
|
||||
5695311E1C907A8C00CF1A2B /* DatabaseSchemaCache.swift */,
|
||||
562822F92E631F1E00B5A627 /* DatabaseSchemaSource.swift */,
|
||||
566A84192041146100E50BFD /* DatabaseSnapshot.swift */,
|
||||
568EB71829211E0700E59445 /* DatabaseSnapshotPool.swift */,
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
|
||||
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
|
||||
56AC93DE2E291C4700DB6C74 /* DispatchQueueActor.swift */,
|
||||
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
|
||||
56A238761B9C75030082EB20 /* Row.swift */,
|
||||
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
|
||||
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */,
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
|
||||
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
|
||||
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
|
||||
56E9FAD7221053DC00C703A8 /* SQL.swift */,
|
||||
569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */,
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */,
|
||||
@@ -1622,7 +1608,6 @@
|
||||
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
|
||||
56B7EE822863781300C0525F /* WALSnapshot.swift */,
|
||||
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
);
|
||||
path = Core;
|
||||
@@ -1851,9 +1836,8 @@
|
||||
DC3773EA19C8CBB3004FCF85 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = YES;
|
||||
LastSwiftUpdateCheck = 0730;
|
||||
LastUpgradeCheck = 2600;
|
||||
LastUpgradeCheck = 1400;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
56E5D7F81B4D422D00430942 = {
|
||||
@@ -2019,7 +2003,6 @@
|
||||
56677C15241D14450050755D /* FailureTestCase.swift in Sources */,
|
||||
5615B289222B17C000061C1C /* AssociationHasOneThroughDecodableRecordTests.swift in Sources */,
|
||||
56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */,
|
||||
568515A42E66C2A70082E9A1 /* RecordMappedOnMutableViewTests.swift in Sources */,
|
||||
5682D721239582AA004B58C4 /* DatabaseSuspensionTests.swift in Sources */,
|
||||
56D496601D81304E008276D7 /* FoundationNSUUIDTests.swift in Sources */,
|
||||
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */,
|
||||
@@ -2124,7 +2107,6 @@
|
||||
D263F40A26C613090038B07F /* DatabaseColumnEncodingStrategyTests.swift in Sources */,
|
||||
5653EAEE20944B4F00F46237 /* AssociationParallelDecodableRecordTests.swift in Sources */,
|
||||
56D496861D813147008276D7 /* UpdateStatementTests.swift in Sources */,
|
||||
56BCA2622E6C28F800E4F08D /* DatabaseSchemaSourceTests.swift in Sources */,
|
||||
56D4965D1D81304E008276D7 /* FoundationNSNumberTests.swift in Sources */,
|
||||
56B021C91D8C0D3900B239BB /* MutablePersistableRecordPersistenceConflictPolicyTests.swift in Sources */,
|
||||
56D496C11D81373A008276D7 /* DatabaseQueueBackupTests.swift in Sources */,
|
||||
@@ -2186,7 +2168,6 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56231A442DCF3A19007676E4 /* TableAlias.swift in Sources */,
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */,
|
||||
56158780288D875E00A67323 /* Optional.swift in Sources */,
|
||||
@@ -2195,7 +2176,6 @@
|
||||
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
|
||||
56AC93DF2E291C4700DB6C74 /* DispatchQueueActor.swift in Sources */,
|
||||
5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */,
|
||||
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
@@ -2219,7 +2199,6 @@
|
||||
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
562822FA2E631F2100B5A627 /* DatabaseSchemaSource.swift in Sources */,
|
||||
56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
|
||||
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
|
||||
@@ -2552,7 +2531,6 @@
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = 1;
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_MODULE_VERIFIER = YES;
|
||||
INFOPLIST_FILE = Support/Info.plist;
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
@@ -2560,7 +2538,6 @@
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
|
||||
SKIP_INSTALL = YES;
|
||||
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
|
||||
SUPPORTS_MACCATALYST = YES;
|
||||
@@ -2585,7 +2562,6 @@
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = 1;
|
||||
DYLIB_INSTALL_NAME_BASE = "@rpath";
|
||||
ENABLE_MODULE_VERIFIER = YES;
|
||||
INFOPLIST_FILE = Support/Info.plist;
|
||||
INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks";
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
@@ -2593,7 +2569,6 @@
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
MODULE_VERIFIER_SUPPORTED_LANGUAGE_STANDARDS = "gnu99 gnu++11";
|
||||
SKIP_INSTALL = YES;
|
||||
SUPPORTED_PLATFORMS = "watchsimulator watchos macosx iphonesimulator iphoneos driverkit appletvsimulator appletvos";
|
||||
SUPPORTS_MACCATALYST = YES;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2600"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
#if !canImport(Darwin)
|
||||
@preconcurrency
|
||||
@@ -90,7 +87,7 @@ public struct Configuration: Sendable {
|
||||
/// with the number of snapshots.
|
||||
///
|
||||
/// The default configuration label is nil.
|
||||
public var label: String?
|
||||
public var label: String? = nil
|
||||
|
||||
/// A boolean value indicating whether SQLite 3.29+ interprets
|
||||
/// double-quoted strings as string literals when they does not match any
|
||||
@@ -147,7 +144,7 @@ public struct Configuration: Sendable {
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter { $0.email == email }.fetchOne(db)
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// // By default, sensitive information is NOT printed
|
||||
/// // when an error occurs:
|
||||
@@ -176,7 +173,7 @@ public struct Configuration: Sendable {
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter { $0.email == email }.fetchOne(db)
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// // Sensitive information is printed in DEBUG builds:
|
||||
/// print(error)
|
||||
@@ -201,7 +198,7 @@ public struct Configuration: Sendable {
|
||||
|
||||
// MARK: - Managing SQLite Connections
|
||||
|
||||
private var setups: [@Sendable (DatabaseBase<some SQLiteAPI>) throws -> Void] = []
|
||||
private var setups: [@Sendable (Database) throws -> Void] = []
|
||||
|
||||
/// Defines a function to run whenever an SQLite connection is opened.
|
||||
///
|
||||
@@ -238,7 +235,7 @@ public struct Configuration: Sendable {
|
||||
///
|
||||
/// On newly created databases files, ``DatabasePool`` activates the WAL
|
||||
/// mode after the preparation functions have run.
|
||||
public mutating func prepareDatabase(_ setup: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> Void) {
|
||||
public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) {
|
||||
setups.append(setup)
|
||||
}
|
||||
|
||||
@@ -332,7 +329,7 @@ public struct Configuration: Sendable {
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
|
||||
/// If nil, GRDB picks a default one.
|
||||
var readonlyBusyMode: Database.BusyMode?
|
||||
var readonlyBusyMode: Database.BusyMode? = nil
|
||||
|
||||
/// The maximum number of concurrent reader connections.
|
||||
///
|
||||
@@ -390,7 +387,7 @@ public struct Configuration: Sendable {
|
||||
/// ``qos`` property.
|
||||
///
|
||||
/// The default is nil.
|
||||
public var targetQueue: DispatchQueue?
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
|
||||
/// The target dispatch queue for write database accesses.
|
||||
///
|
||||
@@ -398,7 +395,7 @@ public struct Configuration: Sendable {
|
||||
/// by ``targetQueue``.
|
||||
///
|
||||
/// The default is nil.
|
||||
public var writeTargetQueue: DispatchQueue?
|
||||
public var writeTargetQueue: DispatchQueue? = nil
|
||||
|
||||
#if os(iOS)
|
||||
/// A boolean value indicating whether the database connection releases
|
||||
@@ -424,22 +421,6 @@ public struct Configuration: Sendable {
|
||||
/// reveals that a lot of time is spent opening new SQLite connections.
|
||||
public var persistentReadOnlyConnections = false
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// A custom schema source.
|
||||
///
|
||||
/// The use case for a custom schema source is enabling GRDB features that
|
||||
/// would not work with the built-in schema introspection that is provided
|
||||
/// by SQLite. For example, a custom schema source can help record types
|
||||
/// that read or write in a database view.
|
||||
///
|
||||
/// The schema source is automatically disabled during database
|
||||
/// migrations performed by ``DatabaseMigrator``: those access the raw
|
||||
/// SQLite schema, unaltered. If a migration needs a schema source,
|
||||
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
|
||||
/// the body of a migration.
|
||||
public var schemaSource: (any DatabaseSchemaSource)?
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration.
|
||||
@@ -481,7 +462,7 @@ public struct Configuration: Sendable {
|
||||
return threadingMode.SQLiteOpenFlags | flags
|
||||
}
|
||||
|
||||
func setUp(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
func setUp(_ db: Database) throws {
|
||||
for f in setups {
|
||||
try f(db)
|
||||
}
|
||||
|
||||
+234
-406
File diff suppressed because it is too large.
Load diff
@@ -1,18 +1,15 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
extension DatabaseBase {
|
||||
extension Database {
|
||||
|
||||
// MARK: - Statements
|
||||
|
||||
@@ -390,7 +387,7 @@ extension SQLStatementCursor: Cursor {
|
||||
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
|
||||
|
||||
// Compile next statement
|
||||
var statementEnd: UnsafePointer<CChar>?
|
||||
var statementEnd: UnsafePointer<CChar>? = nil
|
||||
let statement = try Statement(
|
||||
database: database,
|
||||
statementStart: baseAddress + offset,
|
||||
@@ -434,10 +431,10 @@ extension SQLStatementCursor: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseBase {
|
||||
extension Database {
|
||||
/// Makes sure statement can be executed, and prepares database observation.
|
||||
@usableFromInline
|
||||
func statementWillExecute(_ statement: StatementBase<API>) throws {
|
||||
func statementWillExecute(_ statement: Statement) throws {
|
||||
// Aborted transactions prevent statement execution (see the
|
||||
// documentation of this method for more information).
|
||||
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
|
||||
@@ -458,7 +455,7 @@ extension DatabaseBase {
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
/// an empty transaction.
|
||||
@usableFromInline
|
||||
func statementDidExecute(_ statement: StatementBase<API>) throws {
|
||||
func statementDidExecute(_ statement: Statement) throws {
|
||||
if statement.invalidatesDatabaseSchemaCache {
|
||||
clearSchemaCache()
|
||||
}
|
||||
@@ -471,7 +468,7 @@ extension DatabaseBase {
|
||||
|
||||
/// Always throws an error
|
||||
@usableFromInline
|
||||
func statementDidFail(_ statement: StatementBase<API>, withResultCode resultCode: CInt) throws -> Never {
|
||||
func statementDidFail(_ statement: Statement, withResultCode resultCode: CInt) 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
|
||||
@@ -497,9 +494,11 @@ extension DatabaseBase {
|
||||
|
||||
switch ResultCode(rawValue: resultCode) {
|
||||
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
try suspensionMutex.load().checkCancellation()
|
||||
if suspensionMutex.load().isCancelled {
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
throw CancellationError()
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
@@ -534,15 +533,15 @@ extension DatabaseBase {
|
||||
}
|
||||
|
||||
/// A thread-unsafe statement cache
|
||||
struct StatementCache<API: SQLiteAPI> {
|
||||
unowned let db: DatabaseBase<API>
|
||||
private var statements: [String: StatementBase<API>] = [:]
|
||||
struct StatementCache {
|
||||
unowned let db: Database
|
||||
private var statements: [String: Statement] = [:]
|
||||
|
||||
init(database: DatabaseBase<API>) {
|
||||
init(database: Database) {
|
||||
self.db = database
|
||||
}
|
||||
|
||||
mutating func statement(_ sql: String) throws -> StatementBase<API> {
|
||||
mutating func statement(_ sql: String) throws -> Statement {
|
||||
if let statement = statements[sql] {
|
||||
return statement
|
||||
}
|
||||
@@ -562,11 +561,11 @@ struct StatementCache<API: SQLiteAPI> {
|
||||
statements = [:]
|
||||
}
|
||||
|
||||
mutating func remove(_ statement: StatementBase<API>) {
|
||||
mutating func remove(_ statement: Statement) {
|
||||
statements.removeFirst { $0.value === statement }
|
||||
}
|
||||
|
||||
mutating func removeAll(where shouldBeRemoved: (StatementBase<API>) -> Bool) {
|
||||
mutating func removeAll(where shouldBeRemoved: (Statement) -> Bool) {
|
||||
statements = statements.filter { (_, statement) in !shouldBeRemoved(statement) }
|
||||
}
|
||||
}
|
||||
+82
-233
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -116,11 +113,6 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``resumeNotification``
|
||||
/// - ``suspendNotification``
|
||||
///
|
||||
/// ### The Schema Source
|
||||
///
|
||||
/// - ``schemaSource``
|
||||
/// - ``withSchemaSource(_:execute:)``
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``add(tokenizer:)``
|
||||
@@ -129,7 +121,6 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``clearSchemaCache()``
|
||||
/// - ``logError``
|
||||
/// - ``releaseMemory()``
|
||||
/// - ``sqliteLibVersionNumber``
|
||||
/// - ``trace(options:_:)``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
@@ -142,7 +133,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``StorageClass``
|
||||
/// - ``TraceEvent``
|
||||
/// - ``TracingOptions``
|
||||
public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
public final class Database: CustomStringConvertible, CustomDebugStringConvertible {
|
||||
// The Database class is not thread-safe. An instance should always be
|
||||
// used through a SerializedDatabase.
|
||||
|
||||
@@ -177,7 +168,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
/// connection has been opened is an SQLite misuse, and has no effect.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/errlog.html>
|
||||
nonisolated(unsafe) public static var logError: LogErrorFunction? {
|
||||
nonisolated(unsafe) public static var logError: LogErrorFunction? = nil {
|
||||
didSet {
|
||||
if logError != nil {
|
||||
_registerErrorLogCallback { (_, code, message) in
|
||||
@@ -195,19 +186,6 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
/// The database configuration.
|
||||
public let configuration: Configuration
|
||||
|
||||
/// The current schema source.
|
||||
///
|
||||
/// By default, it is the ``Configuration/schemaSource``
|
||||
/// of ``configuration``. To modify the schema source,
|
||||
/// use ``withSchemaSource(_:execute:)``.
|
||||
///
|
||||
/// The schema source is automatically disabled (nil) during database
|
||||
/// migrations performed by ``DatabaseMigrator``: those access the raw
|
||||
/// SQLite schema, unaltered. If a migration needs a schema source,
|
||||
/// you may call ``Database/withSchemaSource(_:execute:)`` from within
|
||||
/// the body of a migration.
|
||||
public internal(set) var schemaSource: (any DatabaseSchemaSource)?
|
||||
|
||||
/// A description of this database connection.
|
||||
///
|
||||
/// The returned string is based on the ``Configuration/label``
|
||||
@@ -315,7 +293,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
///
|
||||
/// It is nil in read-only connections, because we do not report read-only
|
||||
/// transactions to transaction observers.
|
||||
private(set) var observationBroker: DatabaseObservationBroker<API>?
|
||||
private(set) var observationBroker: DatabaseObservationBroker?
|
||||
|
||||
/// The list of compile options used when building SQLite
|
||||
static func sqliteCompileOptions() throws -> Set<String> {
|
||||
@@ -324,21 +302,6 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// An integer equal to [`SQLITE_VERSION_NUMBER`](https://www.sqlite.org/c3ref/c_source_id.html).
|
||||
///
|
||||
/// This property returns the result of `sqlite3_libversion_number()`.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Prints, for example, "3048000"
|
||||
/// print(Database.sqliteLibVersionNumber)
|
||||
/// ```
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public static var sqliteLibVersionNumber: CInt {
|
||||
sqlite3_libversion_number()
|
||||
}
|
||||
|
||||
/// Whether the database region selected by statement execution is
|
||||
/// recorded into `selectedRegion` by `track(_:)`.
|
||||
///
|
||||
@@ -362,22 +325,10 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
|
||||
/// If true, the database access has been cancelled.
|
||||
var isCancelled: Bool
|
||||
|
||||
/// If true, the database throws an error when it is cancelled.
|
||||
var interruptsWhenCancelled: Bool
|
||||
|
||||
func checkCancellation() throws {
|
||||
if isCancelled, interruptsWhenCancelled {
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
let suspensionMutex = Mutex(Suspension(
|
||||
isSuspended: false,
|
||||
isCancelled: false,
|
||||
interruptsWhenCancelled: true))
|
||||
let suspensionMutex = Mutex(Suspension(isSuspended: false, isCancelled: false))
|
||||
|
||||
// MARK: - Transaction Date
|
||||
|
||||
@@ -463,7 +414,6 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.description = description
|
||||
self.configuration = configuration
|
||||
self.schemaSource = configuration.schemaSource
|
||||
self.path = path
|
||||
|
||||
// We do not report read-only transactions to transaction observers, so
|
||||
@@ -481,7 +431,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
|
||||
private static func openConnection(path: String, flags: CInt) throws -> SQLiteConnection {
|
||||
// See <https://www.sqlite.org/c3ref/open.html>
|
||||
var sqliteConnection: SQLiteConnection?
|
||||
var sqliteConnection: SQLiteConnection? = nil
|
||||
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// https://www.sqlite.org/c3ref/open.html
|
||||
@@ -828,7 +778,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
collationPointer,
|
||||
{ (collationPointer, length1, buffer1, length2, buffer2) in
|
||||
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
|
||||
return collation.xCompare(length1, buffer1.unsafelyUnwrapped, length2, buffer2.unsafelyUnwrapped)
|
||||
return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue)
|
||||
}, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
@@ -1171,9 +1121,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
|
||||
// See <https://www.sqlite.org/c3ref/interrupt.html>
|
||||
func interrupt() {
|
||||
if let sqliteConnection {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
|
||||
// MARK: - Database Suspension
|
||||
@@ -1247,31 +1195,22 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a closure that cancels the current database access.
|
||||
/// Most statements will throw `CancellationError`, until `uncancel()`
|
||||
/// is called.
|
||||
var cancel: @Sendable () -> Void {
|
||||
// Workaround the fact that SQLiteConnection is not Sendable.
|
||||
struct Connection: @unchecked Sendable {
|
||||
var sqliteConnection: SQLiteConnection?
|
||||
}
|
||||
let connection = Connection(sqliteConnection: sqliteConnection)
|
||||
|
||||
return { [suspensionMutex, connection] in
|
||||
let needsInterrupt = suspensionMutex.withLock { suspension in
|
||||
if suspension.isCancelled {
|
||||
return false
|
||||
}
|
||||
|
||||
suspension.isCancelled = true
|
||||
return suspension.interruptsWhenCancelled
|
||||
/// Cancels the current database access. All statements but ROLLBACK
|
||||
/// will throw `CancellationError`, until `uncancel()` is called.
|
||||
///
|
||||
/// This method can be called from any thread.
|
||||
func cancel() {
|
||||
let needsInterrupt = suspensionMutex.withLock { suspension in
|
||||
if suspension.isCancelled {
|
||||
return false
|
||||
}
|
||||
|
||||
if needsInterrupt {
|
||||
if let sqliteConnection = connection.sqliteConnection {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
}
|
||||
suspension.isCancelled = true
|
||||
return true
|
||||
}
|
||||
|
||||
if needsInterrupt {
|
||||
interrupt()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1282,24 +1221,6 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
}
|
||||
}
|
||||
|
||||
/// Within the given closure, Task cancellation does not interrupt
|
||||
/// database accesses.
|
||||
func ignoringCancellation<T>(_ value: () throws -> T) rethrows -> T {
|
||||
let previous = suspensionMutex.withLock {
|
||||
let previous = $0.interruptsWhenCancelled
|
||||
$0.interruptsWhenCancelled = false
|
||||
return previous
|
||||
}
|
||||
|
||||
defer {
|
||||
suspensionMutex.withLock {
|
||||
$0.interruptsWhenCancelled = previous
|
||||
}
|
||||
}
|
||||
|
||||
return try value()
|
||||
}
|
||||
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
private func journalMode() throws -> String {
|
||||
if let journalMode = journalModeCache {
|
||||
@@ -1308,7 +1229,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
|
||||
// Don't return String.fetchOne(self, sql: "PRAGMA journal_mode"), so
|
||||
// that we don't create an infinite loop in checkForSuspensionViolation(from:)
|
||||
var statement: SQLiteStatement?
|
||||
var statement: SQLiteStatement? = nil
|
||||
let sql = "PRAGMA journal_mode"
|
||||
sqlite3_prepare_v2(sqliteConnection, sql, -1, &statement, nil)
|
||||
defer { sqlite3_finalize(statement) }
|
||||
@@ -1351,17 +1272,6 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
return
|
||||
}
|
||||
|
||||
// Commits when read-only are just like rollbacks above.
|
||||
if statement.transactionEffect == .commitTransaction && isReadOnly {
|
||||
return
|
||||
}
|
||||
|
||||
// Suspension should not prevent adjusting the read-only mode.
|
||||
// See <https://github.com/groue/GRDB.swift/issues/1715>.
|
||||
if statement.isQueryOnlyPragma {
|
||||
return
|
||||
}
|
||||
|
||||
// How should we interrupt the statement?
|
||||
enum Interrupt {
|
||||
case abort // Rollback and throw SQLITE_ABORT
|
||||
@@ -1371,7 +1281,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
let interrupt: Interrupt? = try suspensionMutex.withLock { suspension in
|
||||
// Check for cancellation first, so that the only error that
|
||||
// a user sees when a Task is cancelled is CancellationError.
|
||||
if suspension.isCancelled, suspension.interruptsWhenCancelled {
|
||||
if suspension.isCancelled {
|
||||
return .cancel
|
||||
}
|
||||
|
||||
@@ -1491,7 +1401,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
/// either ``TransactionCompletion/commit`` or ``TransactionCompletion/rollback``.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
|
||||
/// error thrown by `operations`.
|
||||
public func inTransaction(_ kind: DatabaseTransactionKind? = nil, _ operations: () throws -> DatabaseTransactionCompletion) throws {
|
||||
public func inTransaction(_ kind: TransactionKind? = nil, _ operations: () throws -> TransactionCompletion) throws {
|
||||
// Begin transaction
|
||||
try beginTransaction(kind)
|
||||
|
||||
@@ -1505,7 +1415,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
// Now that transaction has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
var firstError: Error?
|
||||
var firstError: Error? = nil
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -1648,7 +1558,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
// Now that savepoint has begun, we'll rollback in case of error.
|
||||
// But we'll throw the first caught error, so that user knows
|
||||
// what happened.
|
||||
var firstError: Error?
|
||||
var firstError: Error? = nil
|
||||
let needsRollback: Bool
|
||||
do {
|
||||
let completion = try operations()
|
||||
@@ -1703,7 +1613,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
/// If nil, the transaction kind is DEFERRED when the current
|
||||
/// database access is read-only, and IMMEDIATE otherwise.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func beginTransaction(_ kind: DatabaseTransactionKind? = nil) throws {
|
||||
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
|
||||
// SQLite throws an error for non-deferred transactions when read-only.
|
||||
// We prefer immediate transactions for writes, so that write
|
||||
// transactions can not overlap. This reduces the opportunity for
|
||||
@@ -1766,7 +1676,7 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
if isInsideTransaction {
|
||||
try execute(sql: "ROLLBACK TRANSACTION")
|
||||
}
|
||||
assert(!isInsideTransaction)
|
||||
assert(sqlite3_get_autocommit(sqliteConnection) != 0)
|
||||
}
|
||||
|
||||
/// Commits a database transaction.
|
||||
@@ -1945,10 +1855,10 @@ public final class DatabaseBase<API: SQLiteAPI>: CustomStringConvertible, Custom
|
||||
// Explicit non-conformance to Sendable: `Database` must be used from a
|
||||
// serialized database access dispatch queue (see `SerializedDatabase`).
|
||||
@available(*, unavailable)
|
||||
extension DatabaseBase: Sendable { }
|
||||
extension Database: Sendable { }
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
extension DatabaseBase {
|
||||
extension Database {
|
||||
|
||||
// MARK: - Encryption
|
||||
|
||||
@@ -2021,35 +1931,7 @@ extension DatabaseBase {
|
||||
}
|
||||
#endif
|
||||
|
||||
extension DatabaseBase {
|
||||
/// Returns the count of changes executed by one statement execution.
|
||||
func countChanges<T>(_ count: inout Int, forTable tableName: String, updates: () throws -> T) throws -> T {
|
||||
// Database.changesCount calls sqlite3_changes(), whose documentation says:
|
||||
//
|
||||
// > https://sqlite.org/c3ref/changes.html
|
||||
// > Changes to a view that are intercepted by INSTEAD OF triggers are not counted.
|
||||
//
|
||||
// We want to support INSTEAD OF triggers, so we prefer to use
|
||||
// sqlite3_total_changes() for views.
|
||||
//
|
||||
// At the same time, FTS5 has sqlite3_total_changes() report changes
|
||||
// even when database is not changed (https://github.com/groue/GRDB.swift/issues/1820)
|
||||
//
|
||||
// Well, let's do our best:
|
||||
if try viewExists(tableName) {
|
||||
let prevCount = totalChangesCount
|
||||
let result = try updates()
|
||||
count = totalChangesCount - prevCount
|
||||
return result
|
||||
} else {
|
||||
let result = try updates()
|
||||
count = changesCount
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseBase {
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database-Related Types
|
||||
|
||||
@@ -2176,9 +2058,6 @@ extension DatabaseBase {
|
||||
/// That's the reason why it is recommended to store JSON as text.
|
||||
public static let jsonText = ColumnType(rawValue: "TEXT")
|
||||
|
||||
/// The `BLOB` column type, suitable for JSONB columns.
|
||||
public static let jsonb = ColumnType(rawValue: "BLOB")
|
||||
|
||||
/// The `INTEGER` column type.
|
||||
public static let integer = ColumnType(rawValue: "INTEGER")
|
||||
|
||||
@@ -2207,6 +2086,26 @@ extension DatabaseBase {
|
||||
public static let any = ColumnType(rawValue: "ANY")
|
||||
}
|
||||
|
||||
/// An SQLite conflict resolution.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
|
||||
public enum ConflictResolution: String, Sendable {
|
||||
/// The `ROLLBACK` conflict resolution.
|
||||
case rollback = "ROLLBACK"
|
||||
|
||||
/// The `ABORT` conflict resolution.
|
||||
case abort = "ABORT"
|
||||
|
||||
/// The `FAIL` conflict resolution.
|
||||
case fail = "FAIL"
|
||||
|
||||
/// The `IGNORE` conflict resolution.
|
||||
case ignore = "IGNORE"
|
||||
|
||||
/// The `REPLACE` conflict resolution.
|
||||
case replace = "REPLACE"
|
||||
}
|
||||
|
||||
/// A foreign key action.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>
|
||||
@@ -2393,6 +2292,29 @@ extension DatabaseBase {
|
||||
}
|
||||
}
|
||||
|
||||
/// A transaction commit, or rollback.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
|
||||
@frozen
|
||||
public enum TransactionCompletion: Sendable {
|
||||
case commit
|
||||
case rollback
|
||||
}
|
||||
|
||||
/// A transaction kind.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
|
||||
public enum TransactionKind: String, Sendable {
|
||||
/// The `DEFERRED` transaction kind.
|
||||
case deferred = "DEFERRED"
|
||||
|
||||
/// The `IMMEDIATE` transaction kind.
|
||||
case immediate = "IMMEDIATE"
|
||||
|
||||
/// The `EXCLUSIVE` transaction kind.
|
||||
case exclusive = "EXCLUSIVE"
|
||||
}
|
||||
|
||||
/// An SQLite threading mode. See <https://www.sqlite.org/threadsafe.html>.
|
||||
///
|
||||
/// - Note: Only the multi-thread mode (`SQLITE_OPEN_NOMUTEX`) is currently
|
||||
@@ -2416,79 +2338,6 @@ extension DatabaseBase {
|
||||
}
|
||||
}
|
||||
|
||||
#warning("TODO: export as DatabaseConflictResolution")
|
||||
/// An SQLite conflict resolution.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_conflict.html>
|
||||
public enum DatabaseConflictResolution: String, Sendable {
|
||||
/// The `ROLLBACK` conflict resolution.
|
||||
case rollback = "ROLLBACK"
|
||||
|
||||
/// The `ABORT` conflict resolution.
|
||||
case abort = "ABORT"
|
||||
|
||||
/// The `FAIL` conflict resolution.
|
||||
case fail = "FAIL"
|
||||
|
||||
/// The `IGNORE` conflict resolution.
|
||||
case ignore = "IGNORE"
|
||||
|
||||
/// The `REPLACE` conflict resolution.
|
||||
case replace = "REPLACE"
|
||||
}
|
||||
|
||||
#warning("TODO: export as Database.StorageClass")
|
||||
/// An SQLite storage class.
|
||||
///
|
||||
/// For more information, see
|
||||
/// [Datatypes In SQLite](https://www.sqlite.org/datatype3.html).
|
||||
public struct DatabaseStorageClass: RawRepresentable, Hashable, Sendable {
|
||||
/// The SQL for the storage class (`"INTEGER"`, `"REAL"`, etc.)
|
||||
public let rawValue: String
|
||||
|
||||
/// Creates an SQL storage class.
|
||||
public init(rawValue: String) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// The `INTEGER` storage class.
|
||||
public static let integer = StorageClass(rawValue: "INTEGER")
|
||||
|
||||
/// The `REAL` storage class.
|
||||
public static let real = StorageClass(rawValue: "REAL")
|
||||
|
||||
/// The `TEXT` storage class.
|
||||
public static let text = StorageClass(rawValue: "TEXT")
|
||||
|
||||
/// The `BLOB` storage class.
|
||||
public static let blob = StorageClass(rawValue: "BLOB")
|
||||
}
|
||||
|
||||
#warning("TODO: export as Database.TransactionCompletion")
|
||||
/// A transaction commit, or rollback.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
|
||||
@frozen
|
||||
public enum DatabaseTransactionCompletion: Sendable {
|
||||
case commit
|
||||
case rollback
|
||||
}
|
||||
|
||||
#warning("TODO: export as Database.TransactionKind")
|
||||
/// A transaction kind.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>.
|
||||
public enum DatabaseTransactionKind: String, Sendable {
|
||||
/// The `DEFERRED` transaction kind.
|
||||
case deferred = "DEFERRED"
|
||||
|
||||
/// The `IMMEDIATE` transaction kind.
|
||||
case immediate = "IMMEDIATE"
|
||||
|
||||
/// The `EXCLUSIVE` transaction kind.
|
||||
case exclusive = "EXCLUSIVE"
|
||||
}
|
||||
|
||||
// Explicit non-conformance to Sendable: a trace event contains transient
|
||||
// information.
|
||||
@available(*, unavailable)
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -56,21 +53,12 @@ public final class DatabaseCollation: Identifiable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xCompare` parameter of sqlite3_create_collation_v2
|
||||
/// <https://www.sqlite.org/c3ref/create_collation.html>
|
||||
typealias XCompare = @Sendable (
|
||||
_ length1: CInt,
|
||||
_ buffer1: UnsafeRawPointer,
|
||||
_ length2: CInt,
|
||||
_ buffer2: UnsafeRawPointer
|
||||
) -> CInt
|
||||
|
||||
/// The identifier of the collation.
|
||||
public var id: ID { ID(name: name) }
|
||||
|
||||
/// The name of the collation.
|
||||
public let name: String
|
||||
let xCompare: XCompare
|
||||
let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
|
||||
|
||||
/// Creates a collation.
|
||||
///
|
||||
@@ -87,16 +75,21 @@ public final class DatabaseCollation: Identifiable, Sendable {
|
||||
/// - parameters:
|
||||
/// - name: The collation name.
|
||||
/// - function: A function that compares two strings.
|
||||
public convenience init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
|
||||
self.init(name, xCompare: { (length1, buffer1, length2, buffer2) in
|
||||
let string1 = String(decoding: UnsafeRawBufferPointer(start: buffer1, count: Int(length1)), as: UTF8.self)
|
||||
let string2 = String(decoding: UnsafeRawBufferPointer(start: buffer2, count: Int(length2)), as: UTF8.self)
|
||||
return CInt(function(string1, string2).rawValue)
|
||||
})
|
||||
}
|
||||
|
||||
init(_ name: String, xCompare: @escaping XCompare) {
|
||||
public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) {
|
||||
self.name = name
|
||||
self.xCompare = xCompare
|
||||
self.function = { (length1, buffer1, length2, buffer2) in
|
||||
// Buffers are not C strings: they do not end with \0.
|
||||
let string1 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer1.unsafelyUnwrapped),
|
||||
length: Int(length1),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
let string2 = String(
|
||||
bytesNoCopy: UnsafeMutableRawPointer(mutating: buffer2.unsafelyUnwrapped),
|
||||
length: Int(length2),
|
||||
encoding: .utf8,
|
||||
freeWhenDone: false)!
|
||||
return function(string1, string2)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A custom SQL function or aggregate.
|
||||
///
|
||||
@@ -85,43 +82,20 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// such as `Int`, `String`, `Date`, etc. The array is guaranteed to
|
||||
/// have exactly `argumentCount` elements, provided `argumentCount` is
|
||||
/// not nil.
|
||||
public convenience init(
|
||||
public init(
|
||||
_ name: String,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.init(name, argumentCount: argumentCount, pure: pure) { (argc, argv, context) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv[index]!)
|
||||
}
|
||||
let result = try function(arguments)
|
||||
switch result?.databaseValue.storage ?? .null {
|
||||
case .null:
|
||||
sqlite3_result_null(context)
|
||||
case .int64(let int64):
|
||||
sqlite3_result_int64(context, int64)
|
||||
case .double(let double):
|
||||
sqlite3_result_double(context, double)
|
||||
case .string(let string):
|
||||
sqlite3_result_text(context, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(context, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init(
|
||||
_ name: String,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
xFunc: @escaping XFunc)
|
||||
{
|
||||
self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.isPure = pure
|
||||
self.kind = .function(xFunc)
|
||||
self.kind = .function { (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
DatabaseValue(sqliteValue: argv.unsafelyUnwrapped[index]!)
|
||||
}
|
||||
return try function(arguments)
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates an SQL aggregate function.
|
||||
@@ -199,20 +173,13 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// }
|
||||
/// return int * int
|
||||
/// }
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// try dbQueue.read { db in
|
||||
/// db.add(function: square)
|
||||
///
|
||||
/// // SELECT square(score) FROM player
|
||||
/// let squaredScores = let Player
|
||||
/// .select({ square($0.score) }, as: Int.self)
|
||||
/// .select(square(Column("score")), as: Int.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
@@ -237,7 +204,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See <https://sqlite.org/c3ref/create_function.html>
|
||||
func install(in db: DatabaseBase<some SQLiteAPI>) {
|
||||
func install(in db: Database) {
|
||||
// Retain the function definition
|
||||
let definition = kind.definition
|
||||
let definitionP = Unmanaged.passRetained(definition).toOpaque()
|
||||
@@ -264,7 +231,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
|
||||
/// Calls sqlite3_create_function_v2
|
||||
/// See <https://sqlite.org/c3ref/create_function.html>
|
||||
func uninstall(in db: DatabaseBase<some SQLiteAPI>) {
|
||||
func uninstall(in db: Database) {
|
||||
let code = sqlite3_create_function_v2(
|
||||
db.sqliteConnection,
|
||||
id.name,
|
||||
@@ -282,10 +249,11 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class FunctionDefinition {
|
||||
let xFunc: XFunc
|
||||
init(xFunc: @escaping XFunc)
|
||||
let compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
|
||||
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
|
||||
throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.xFunc = xFunc
|
||||
self.compute = compute
|
||||
}
|
||||
}
|
||||
|
||||
@@ -308,19 +276,11 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
typealias XFunc = @Sendable (
|
||||
_ argc: CInt,
|
||||
_ argv: UnsafeMutablePointer<OpaquePointer?>,
|
||||
_ context: OpaquePointer?
|
||||
) throws -> Void
|
||||
|
||||
/// A function kind: an "SQL function" or an "aggregate".
|
||||
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private enum Kind: Sendable {
|
||||
/// A regular function: SELECT f(1)
|
||||
case function(XFunc)
|
||||
case function(@Sendable (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
|
||||
|
||||
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
|
||||
case aggregate(@Sendable () -> any DatabaseAggregate)
|
||||
@@ -329,8 +289,8 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var definition: AnyObject {
|
||||
switch self {
|
||||
case .function(let xFunc):
|
||||
return FunctionDefinition(xFunc: xFunc)
|
||||
case .function(let compute):
|
||||
return FunctionDefinition(compute: compute)
|
||||
case .aggregate(let makeAggregate):
|
||||
return AggregateDefinition(makeAggregate: makeAggregate)
|
||||
}
|
||||
@@ -345,7 +305,9 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
.fromOpaque(sqlite3_user_data(sqliteContext))
|
||||
.takeUnretainedValue()
|
||||
do {
|
||||
try definition.xFunc(argc, argv.unsafelyUnwrapped, sqliteContext)
|
||||
try DatabaseFunction.report(
|
||||
result: definition.compute(argc, argv),
|
||||
in: sqliteContext)
|
||||
} catch {
|
||||
DatabaseFunction.report(error: error, in: sqliteContext)
|
||||
}
|
||||
@@ -495,7 +457,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
/// ```
|
||||
public protocol DatabaseAggregate: GRDBSendableMetatype {
|
||||
public protocol DatabaseAggregate {
|
||||
/// Creates an aggregate.
|
||||
///
|
||||
/// A new instance is created for each aggregation.
|
||||
|
||||
@@ -4,8 +4,8 @@ import Foundation
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
public final class DatabasePoolBase<API: SQLiteAPI> {
|
||||
private let writer: SerializedDatabase<API>
|
||||
public final class DatabasePool {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
/// The pool of reader connections.
|
||||
/// It is constant, until close() sets it to nil.
|
||||
@@ -143,9 +143,9 @@ public final class DatabasePoolBase<API: SQLiteAPI> {
|
||||
}
|
||||
|
||||
// @unchecked because of readerPool and suspensionObservers
|
||||
extension DatabasePoolBase: @unchecked Sendable { }
|
||||
extension DatabasePool: @unchecked Sendable { }
|
||||
|
||||
extension DatabasePoolBase {
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
@@ -263,7 +263,7 @@ extension DatabasePoolBase {
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabasePoolBase: DatabaseReaderBase {
|
||||
extension DatabasePool: DatabaseReader {
|
||||
|
||||
public func close() throws {
|
||||
try readerPool?.barrier {
|
||||
@@ -336,7 +336,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
@@ -352,34 +352,45 @@ extension DatabasePoolBase: DatabaseReaderBase {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
return try await readerPool.get { reader in
|
||||
try await reader.execute { db in
|
||||
defer {
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
}
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
@@ -392,14 +403,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
@@ -418,7 +422,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
@@ -432,22 +436,41 @@ extension DatabasePoolBase: DatabaseReaderBase {
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
return try await readerPool.get { reader in
|
||||
try await reader.execute { db in
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
@@ -475,7 +498,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync(value)
|
||||
} else if writer.onValidQueue {
|
||||
@@ -494,7 +517,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
|
||||
}
|
||||
|
||||
public func spawnConcurrentRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
asyncConcurrentRead(value)
|
||||
}
|
||||
@@ -537,7 +560,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
public func asyncConcurrentRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
@@ -561,14 +584,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
reader.async { db in
|
||||
defer {
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
@@ -684,15 +700,15 @@ extension DatabasePoolBase: DatabaseReaderBase {
|
||||
|
||||
// MARK: - WAL Snapshot Transactions
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
/// Returns a long-lived WAL snapshot transaction on a reader connection.
|
||||
func walSnapshotTransaction() throws -> WALSnapshotTransactionBase<API> {
|
||||
func walSnapshotTransaction() throws -> WALSnapshotTransaction {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
return try WALSnapshotTransactionBase(onReader: reader, release: { isInsideTransaction in
|
||||
return try WALSnapshotTransaction(onReader: reader, release: { isInsideTransaction in
|
||||
// Discard the connection if the transaction could not be
|
||||
// properly ended. If we'd reuse it, the next read would
|
||||
// fail because we'd fail starting a read transaction.
|
||||
@@ -705,7 +721,7 @@ extension DatabasePoolBase: DatabaseReaderBase {
|
||||
/// - important: The `completion` argument is executed in a serial
|
||||
/// dispatch queue, so make sure you use the transaction asynchronously.
|
||||
func asyncWALSnapshotTransaction(
|
||||
_ completion: @escaping @Sendable (Result<WALSnapshotTransactionBase<API>, Error>) -> Void
|
||||
_ completion: @escaping @Sendable (Result<WALSnapshotTransaction, Error>) -> Void
|
||||
) {
|
||||
guard let readerPool else {
|
||||
completion(.failure(DatabaseError.connectionIsClosed()))
|
||||
@@ -777,22 +793,22 @@ extension DatabasePoolBase: DatabaseReaderBase {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePoolBase: DatabaseWriterBase {
|
||||
extension DatabasePool: DatabaseWriter {
|
||||
// MARK: - Writing in Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(updates)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
@@ -802,37 +818,27 @@ extension DatabasePoolBase: DatabaseWriterBase {
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
// Pool.barrier does not support async calls (yet?).
|
||||
// So we perform cancellation checks just as in
|
||||
// the async version of SerializedDatabase.execute().
|
||||
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
|
||||
return try await withTaskCancellationHandler {
|
||||
try Task.checkCancellation()
|
||||
return try await readerPool.barrier {
|
||||
try Task.checkCancellation()
|
||||
return try writer.sync { db in
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
asyncBarrierWriteWithoutTransaction { dbResult in
|
||||
do {
|
||||
try dbAccess.checkCancellation()
|
||||
let db = try dbResult.get()
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
try updates(db)
|
||||
}
|
||||
cancelMutex.store(db.cancel)
|
||||
try Task.checkCancellation()
|
||||
return try updates(db)
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
} onCancel: {
|
||||
cancelMutex.withLock { $0?() }
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(
|
||||
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
guard let readerPool else {
|
||||
updates(.failure(DatabaseError.connectionIsClosed()))
|
||||
@@ -873,7 +879,7 @@ extension DatabasePoolBase: DatabaseWriterBase {
|
||||
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
|
||||
public func writeInTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (DatabaseBase<API>) throws -> Database.TransactionCompletion)
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
throws
|
||||
{
|
||||
try writer.sync { db in
|
||||
@@ -883,18 +889,18 @@ extension DatabasePoolBase: DatabaseWriterBase {
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
public func asyncWriteWithoutTransaction(
|
||||
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
|
||||
_ updates: @escaping @Sendable (Database) -> Void
|
||||
) {
|
||||
writer.async(updates)
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePoolBase {
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
@@ -950,7 +956,7 @@ extension DatabasePoolBase {
|
||||
purpose: "snapshot.\(databaseSnapshotCountMutex.increment())")
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
/// Creates a database snapshot that allows concurrent accesses to an
|
||||
/// unchanging database content, as it exists at the moment the snapshot
|
||||
/// is created.
|
||||
|
||||
@@ -4,8 +4,8 @@ import Foundation
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
public final class DatabaseQueueBase<API: SQLiteAPI> {
|
||||
private let writer: SerializedDatabase<API>
|
||||
public final class DatabaseQueue {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
/// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers.
|
||||
private var suspensionObservers: [NSObjectProtocol] = []
|
||||
@@ -124,9 +124,9 @@ public final class DatabaseQueueBase<API: SQLiteAPI> {
|
||||
}
|
||||
|
||||
// @unchecked because of suspensionObservers
|
||||
extension DatabaseQueueBase: @unchecked Sendable { }
|
||||
extension DatabaseQueue: @unchecked Sendable { }
|
||||
|
||||
extension DatabaseQueueBase {
|
||||
extension DatabaseQueue {
|
||||
|
||||
// MARK: - Memory management
|
||||
|
||||
@@ -183,7 +183,7 @@ extension DatabaseQueueBase {
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabaseQueueBase: DatabaseReaderBase {
|
||||
extension DatabaseQueue: DatabaseReader {
|
||||
public func close() throws {
|
||||
try writer.sync { try $0.close() }
|
||||
}
|
||||
@@ -225,7 +225,7 @@ extension DatabaseQueueBase: DatabaseReaderBase {
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try writer.sync { db in
|
||||
try db.isolated(readOnly: true) {
|
||||
try value(db)
|
||||
@@ -234,7 +234,7 @@ extension DatabaseQueueBase: DatabaseReaderBase {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute { db in
|
||||
try db.isolated(readOnly: true) {
|
||||
@@ -244,18 +244,12 @@ extension DatabaseQueueBase: DatabaseReaderBase {
|
||||
}
|
||||
|
||||
public func asyncRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
writer.async { db in
|
||||
defer {
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
@@ -273,28 +267,28 @@ extension DatabaseQueueBase: DatabaseReaderBase {
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(value)
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
writer.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try writer.reentrantSync(value)
|
||||
}
|
||||
|
||||
public func spawnConcurrentRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
@@ -302,14 +296,8 @@ extension DatabaseQueueBase: DatabaseReaderBase {
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
|
||||
defer {
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
@@ -349,7 +337,7 @@ extension DatabaseQueueBase: DatabaseReaderBase {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseQueueBase: DatabaseWriterBase {
|
||||
extension DatabaseQueue: DatabaseWriter {
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Wraps database operations inside a database transaction.
|
||||
@@ -381,7 +369,7 @@ extension DatabaseQueueBase: DatabaseWriterBase {
|
||||
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
|
||||
public func inTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (DatabaseBase<API>) throws -> Database.TransactionCompletion)
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
throws
|
||||
{
|
||||
try writer.sync { db in
|
||||
@@ -392,29 +380,29 @@ extension DatabaseQueueBase: DatabaseWriterBase {
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(updates)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(updates)
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(
|
||||
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
writer.async { updates(.success($0)) }
|
||||
}
|
||||
@@ -453,16 +441,16 @@ extension DatabaseQueueBase: DatabaseWriterBase {
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
public func inDatabase<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
public func inDatabase<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
public func asyncWriteWithoutTransaction(
|
||||
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
|
||||
_ updates: @escaping @Sendable (Database) -> Void
|
||||
) {
|
||||
writer.async(updates)
|
||||
}
|
||||
@@ -470,7 +458,7 @@ extension DatabaseQueueBase: DatabaseWriterBase {
|
||||
|
||||
// MARK: - Temp Copy
|
||||
|
||||
extension DatabaseQueueBase {
|
||||
extension DatabaseQueue {
|
||||
/// Returns a connection to an in-memory copy of the database at `path`.
|
||||
///
|
||||
/// Changes performed on the returned connection do not impact the
|
||||
|
||||
@@ -22,14 +22,14 @@ import Dispatch
|
||||
/// ### Reading from the Database
|
||||
///
|
||||
/// - ``read(_:)-3806d``
|
||||
/// - ``read(_:)-5mfwu``
|
||||
/// - ``read(_:)-4d1da``
|
||||
/// - ``readPublisher(receiveOn:value:)``
|
||||
/// - ``asyncRead(_:)``
|
||||
///
|
||||
/// ### Unsafe Methods
|
||||
///
|
||||
/// - ``unsafeRead(_:)-5i7tf``
|
||||
/// - ``unsafeRead(_:)-90w0p``
|
||||
/// - ``unsafeRead(_:)-5gsav``
|
||||
/// - ``unsafeReentrantRead(_:)``
|
||||
/// - ``asyncUnsafeRead(_:)``
|
||||
///
|
||||
@@ -52,8 +52,7 @@ import Dispatch
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyDatabaseReader``
|
||||
public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
|
||||
associatedtype API: SQLiteAPI
|
||||
public protocol DatabaseReader: AnyObject, Sendable {
|
||||
|
||||
/// The database configuration.
|
||||
var configuration: Configuration { get }
|
||||
@@ -187,7 +186,7 @@ public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
|
||||
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T
|
||||
func read<T>(_ value: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Executes read-only database operations, and returns their result after
|
||||
/// they have finished executing.
|
||||
@@ -216,7 +215,7 @@ public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
|
||||
/// database access, or the error thrown by `value`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func read<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules read-only database operations for execution, and
|
||||
@@ -246,7 +245,7 @@ public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the read access to the database.
|
||||
func asyncRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
)
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
@@ -285,7 +284,7 @@ public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
|
||||
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T
|
||||
func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
@@ -320,7 +319,7 @@ public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
|
||||
/// database access, or the error thrown by `value`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
@@ -355,7 +354,7 @@ public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the read access to the database.
|
||||
func asyncUnsafeRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
)
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
@@ -399,7 +398,7 @@ public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access.
|
||||
func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T
|
||||
func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T
|
||||
|
||||
|
||||
// MARK: - Value Observation
|
||||
@@ -418,7 +417,7 @@ public protocol DatabaseReaderBase<API>: AnyObject, Sendable {
|
||||
) -> AnyDatabaseCancellable
|
||||
}
|
||||
|
||||
extension DatabaseReaderBase {
|
||||
extension DatabaseReader {
|
||||
|
||||
// MARK: - Backup
|
||||
|
||||
@@ -500,7 +499,7 @@ extension DatabaseReaderBase {
|
||||
}
|
||||
|
||||
#if canImport(Combine)
|
||||
extension DatabaseReaderBase {
|
||||
extension DatabaseReader {
|
||||
// MARK: - Publishing Database Values
|
||||
|
||||
/// Returns a publisher that publishes one value and completes.
|
||||
@@ -532,7 +531,7 @@ extension DatabaseReaderBase {
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
public func readPublisher<Output>(
|
||||
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
|
||||
value: @escaping @Sendable (DatabaseBase<API>) throws -> Output
|
||||
value: @escaping @Sendable (Database) throws -> Output
|
||||
) -> DatabasePublishers.Read<Output> {
|
||||
OnDemandFuture { fulfill in
|
||||
self.asyncRead { dbResult in
|
||||
@@ -569,7 +568,7 @@ extension Publisher where Failure == Error {
|
||||
}
|
||||
#endif
|
||||
|
||||
extension DatabaseReaderBase {
|
||||
extension DatabaseReader {
|
||||
// MARK: - Value Observation Support
|
||||
|
||||
/// Adding an observation in a read-only database emits only the
|
||||
@@ -620,17 +619,17 @@ extension DatabaseReaderBase {
|
||||
///
|
||||
/// An instance of `AnyDatabaseReader` forwards its operations to an underlying
|
||||
/// base database reader.
|
||||
public final class AnyDatabaseReaderBase<API: SQLiteAPI> {
|
||||
private let base: any DatabaseReader<API>
|
||||
public final class AnyDatabaseReader {
|
||||
private let base: any DatabaseReader
|
||||
|
||||
/// Creates a new database reader that wraps and forwards operations
|
||||
/// to `base`.
|
||||
public init(_ base: any DatabaseReader<API>) {
|
||||
public init(_ base: any DatabaseReader) {
|
||||
self.base = base
|
||||
}
|
||||
}
|
||||
|
||||
extension AnyDatabaseReaderBase: DatabaseReaderBase {
|
||||
extension AnyDatabaseReader: DatabaseReader {
|
||||
public var configuration: Configuration {
|
||||
base.configuration
|
||||
}
|
||||
@@ -648,40 +647,40 @@ extension AnyDatabaseReaderBase: DatabaseReaderBase {
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.read(value)
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.read(value)
|
||||
}
|
||||
|
||||
public func asyncRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
base.asyncRead(value)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.unsafeRead(value)
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.unsafeRead(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
base.asyncUnsafeRead(value)
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.unsafeReentrantRead(value)
|
||||
}
|
||||
|
||||
@@ -736,20 +735,20 @@ extension DatabaseSnapshotReader {
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any ``DatabaseError`` that
|
||||
/// would happen while establishing the database access.
|
||||
public func reentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func reentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
// Reentrant reads are safe in a snapshot
|
||||
try unsafeReentrantRead(value)
|
||||
}
|
||||
|
||||
// There is no such thing as an unsafe access to a snapshot.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try read(value)
|
||||
}
|
||||
|
||||
// There is no such thing as an unsafe access to a snapshot.
|
||||
public func asyncUnsafeRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
asyncRead(value)
|
||||
}
|
||||
|
||||
@@ -163,7 +163,7 @@ public struct DatabaseRegion: Sendable {
|
||||
}
|
||||
|
||||
/// Returns a region suitable for database observation
|
||||
func observableRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
|
||||
func observableRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
// SQLite does not expose schema changes to the
|
||||
// TransactionObserver protocol. By removing internal SQLite tables from
|
||||
// the observed region, we optimize database observation.
|
||||
@@ -178,7 +178,7 @@ public struct DatabaseRegion: Sendable {
|
||||
/// Returns a region only made of actual tables with their canonical names.
|
||||
///
|
||||
/// This method removes views.
|
||||
func canonicalTables(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
|
||||
func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
guard let tableRegions else { return .fullDatabase }
|
||||
var region = DatabaseRegion()
|
||||
for (table, tableRegion) in tableRegions {
|
||||
@@ -237,7 +237,7 @@ extension DatabaseRegion {
|
||||
/// Returns an array of all event kinds that can impact this region.
|
||||
///
|
||||
/// - precondition: the region is canonical.
|
||||
func impactfulEventKinds(_ db: DatabaseBase<some SQLiteAPI>) throws -> [DatabaseEventKind] {
|
||||
func impactfulEventKinds(_ db: Database) throws -> [DatabaseEventKind] {
|
||||
if let tableRegions {
|
||||
return try tableRegions.flatMap { (table, tableRegion) -> [DatabaseEventKind] in
|
||||
let tableName = table.rawValue // canonical table name
|
||||
@@ -256,8 +256,8 @@ extension DatabaseRegion {
|
||||
}
|
||||
} else {
|
||||
// full database
|
||||
return try db.fetchSchemaIdentifiers().flatMap { schemaID in
|
||||
let schema = try db.schema(schemaID)
|
||||
return try db.schemaIdentifiers().flatMap { schemaIdentifier in
|
||||
let schema = try db.schema(schemaIdentifier)
|
||||
return try schema.objects
|
||||
.filter { $0.type == .table }
|
||||
.flatMap { table in
|
||||
@@ -420,7 +420,7 @@ public protocol DatabaseRegionConvertible: Sendable {
|
||||
/// Returns a database region.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
|
||||
func databaseRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
extension DatabaseRegionConvertible where Self == DatabaseRegion {
|
||||
@@ -430,16 +430,16 @@ extension DatabaseRegionConvertible where Self == DatabaseRegion {
|
||||
}
|
||||
|
||||
extension DatabaseRegion: DatabaseRegionConvertible {
|
||||
public func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased DatabaseRegionConvertible
|
||||
public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
|
||||
let _region: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
|
||||
let _region: @Sendable (Database) throws -> DatabaseRegion
|
||||
|
||||
public init(_ region: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion) {
|
||||
public init(_ region: @escaping @Sendable (Database) throws -> DatabaseRegion) {
|
||||
_region = region
|
||||
}
|
||||
|
||||
@@ -447,7 +447,7 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
|
||||
_region = { try region.databaseRegion($0) }
|
||||
}
|
||||
|
||||
public func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
try _region(db)
|
||||
}
|
||||
}
|
||||
@@ -461,7 +461,7 @@ extension DatabaseRegion {
|
||||
}
|
||||
}
|
||||
|
||||
static func union<API: SQLiteAPI>(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (DatabaseBase<API>) throws -> DatabaseRegion {
|
||||
static func union(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (Database) throws -> DatabaseRegion {
|
||||
return { db in
|
||||
try regions.reduce(into: DatabaseRegion()) { union, region in
|
||||
try union.formUnion(region.databaseRegion(db))
|
||||
|
||||
@@ -6,7 +6,7 @@ import Foundation
|
||||
public struct DatabaseRegionObservation: Sendable {
|
||||
/// A closure that is evaluated when the observation starts, and returns
|
||||
/// the observed database region.
|
||||
var observedRegion: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion
|
||||
var observedRegion: @Sendable (Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
extension DatabaseRegionObservation {
|
||||
@@ -83,11 +83,10 @@ extension DatabaseRegionObservation {
|
||||
/// - parameter onChange: The closure to execute when a transaction has
|
||||
/// modified the observed region.
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
@preconcurrency // For RxGRDB, see <https://github.com/RxSwiftCommunity/RxGRDB/issues/72#issuecomment-2631125658>
|
||||
public func start(
|
||||
in writer: any DatabaseWriter,
|
||||
onError: @escaping @Sendable (Error) -> Void,
|
||||
onChange: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) -> Void)
|
||||
onChange: @escaping @Sendable (Database) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
let stateMutex = Mutex(ObservationState.pending)
|
||||
@@ -146,12 +145,12 @@ extension DatabaseRegionObservation {
|
||||
}
|
||||
#endif
|
||||
|
||||
private class DatabaseRegionObserver: TransactionObserverBase {
|
||||
private class DatabaseRegionObserver: TransactionObserver {
|
||||
let region: DatabaseRegion
|
||||
let onChange: @Sendable (DatabaseBase<some SQLiteAPI>) -> Void
|
||||
let onChange: @Sendable (Database) -> Void
|
||||
var isChanged = false
|
||||
|
||||
init(region: DatabaseRegion, onChange: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) -> Void) {
|
||||
init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) {
|
||||
self.region = region
|
||||
self.onChange = onChange
|
||||
}
|
||||
@@ -172,14 +171,14 @@ private class DatabaseRegionObserver: TransactionObserverBase {
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>) {
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
guard isChanged else { return }
|
||||
isChanged = false
|
||||
|
||||
onChange(db)
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>) {
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
isChanged = false
|
||||
}
|
||||
}
|
||||
@@ -201,11 +200,7 @@ extension DatabasePublishers {
|
||||
self.observation = observation
|
||||
}
|
||||
|
||||
public func receive<S>(subscriber: S)
|
||||
where S: Subscriber & GRDBSendableMetatype,
|
||||
Failure == S.Failure,
|
||||
Output == S.Input
|
||||
{
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = DatabaseRegionSubscription(
|
||||
writer: writer,
|
||||
observation: observation,
|
||||
@@ -216,7 +211,7 @@ extension DatabasePublishers {
|
||||
|
||||
private class DatabaseRegionSubscription<Downstream>:
|
||||
Subscription, @unchecked Sendable
|
||||
where Downstream: Subscriber & GRDBSendableMetatype,
|
||||
where Downstream: Subscriber,
|
||||
Downstream.Failure == Error,
|
||||
Downstream.Input == Database
|
||||
{
|
||||
|
||||
@@ -1,218 +0,0 @@
|
||||
/// A type that provides information about the database schema.
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// The use case for a custom schema source is to enable GRDB features that
|
||||
/// would not work with the built-in schema introspection provided
|
||||
/// by SQLite.
|
||||
///
|
||||
/// For example, if your database schema contains a view and you wish to use
|
||||
/// GRDB features that need a primary key, such as the
|
||||
/// ``FetchableRecord/find(_:id:)`` record method, or the persistence
|
||||
/// methods of the ``PersistableRecord`` protocol, then use a schema source
|
||||
/// that implements the ``columnsForPrimaryKey(_:inView:)`` method. See
|
||||
/// <doc:ViewRecords> for a detailed guide about such views.
|
||||
///
|
||||
/// ## Enabling a Schema Source
|
||||
///
|
||||
/// To enable a schema source in a database connection, configure its
|
||||
/// ``Configuration/schemaSource``:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct MySchemaSource: DatabaseSchemaSource { ... }
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = MySchemaSource()
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
|
||||
/// ```
|
||||
///
|
||||
/// ## Schema Sources and Migrations
|
||||
///
|
||||
/// By default, schema sources are disabled during <doc:Migrations>. In
|
||||
/// migrations that need a schema source, you can use
|
||||
/// ``Database/withSchemaSource(_:execute:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// migrator.registerMigration("My migration") { db in
|
||||
/// // No schema source is enabled at this point.
|
||||
/// try db.withSchemaSource(MySchemaSource()) {
|
||||
/// // Here the provided schema source is in effect.
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Take care that **a good migration is a migration that is never
|
||||
/// modified once it has shipped**: check
|
||||
/// <doc:Migrations#Good-Practices-for-Defining-Migrations>.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Customizing the Database Schema
|
||||
///
|
||||
/// - ``columnsForPrimaryKey(_:inView:)``
|
||||
///
|
||||
/// ### Chaining Schema Sources
|
||||
///
|
||||
/// - ``then(_:)``
|
||||
public protocol DatabaseSchemaSource: Sendable {
|
||||
/// Returns the names of the columns for the primary key in the
|
||||
/// provided database view.
|
||||
///
|
||||
/// Return `nil` if no customization should happen. Return an empty
|
||||
/// array to specify that the view has no primary key. The default
|
||||
/// implementation returns `nil`.
|
||||
///
|
||||
/// In your implementation, make sure that the returned columns define
|
||||
/// a genuine **primary key**:
|
||||
///
|
||||
/// - All columns exist in the provided view.
|
||||
/// - The set of columns reliably identifies and distinguishes between
|
||||
/// each individual row in the view.
|
||||
/// - No column contains NULL values.
|
||||
///
|
||||
/// It is a programmer error with undefined consequences to miss
|
||||
/// those requirements.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A schema source that specifies that all views are identified by
|
||||
/// // their "id" column:
|
||||
/// struct MySchemaSource: DatabaseSchemaSource {
|
||||
/// func columnsForPrimaryKey(_ db: DatabaseBase<some SQLiteAPI>, inView view: DatabaseObjectID) {
|
||||
/// ["id"]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // A database connection configured with the schema source.
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = MySchemaSource()
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/db.sqlite", configuration: config)
|
||||
///
|
||||
/// // A record type that feeds from a view.
|
||||
/// struct Player: Decodable, Identifiable, FetchableRecord {
|
||||
/// static let databaseTableName = "playerView"
|
||||
/// var id: String
|
||||
/// var name: String
|
||||
/// }
|
||||
///
|
||||
/// // Thanks to the schema source, we can fetch players by id:
|
||||
/// let player = try dbQueue.read { db in
|
||||
/// try Player.find(db, id: "alice")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Schema Sources in Libraries
|
||||
///
|
||||
/// When you are developing a schema source for a library, some extra
|
||||
/// care is necessary whenever the database file is owned by the users
|
||||
/// of your library. Your users may define views for their own purposes,
|
||||
/// and your library knows nothing about the eventual primary key of
|
||||
/// those views.
|
||||
///
|
||||
/// In this case, make your schema source `public`, and have this method
|
||||
/// return `nil` for those unknown views. If needed, use the `db`
|
||||
/// argument and query the database schema with
|
||||
/// <doc:DatabaseSchemaIntrospection> methods.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A well-behaved schema source defined by a library is public
|
||||
/// // and returns nil for unknown views.
|
||||
/// public struct MyLibrarySchemaSource: DatabaseSchemaSource {
|
||||
/// public func columnsForPrimaryKey(_ db: DatabaseBase<some SQLiteAPI>, inView view: DatabaseObjectID) {
|
||||
/// if view.name == "playerView" {
|
||||
/// // This is a view managed by my library:
|
||||
/// return ["id"]
|
||||
/// } else if try db.tableExists(view.name + "MyLibrary") {
|
||||
/// // This is a view managed by my library:
|
||||
/// return ["uuid"]
|
||||
/// } else {
|
||||
/// // Not a view managed by my library:
|
||||
/// // don't mess with user's schema
|
||||
/// return nil
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// With such a setup, your user will be able to deal with their
|
||||
/// own views, by chaining your schema source with other ones
|
||||
/// (see ``DatabaseSchemaSource/then(_:)``):
|
||||
///
|
||||
/// ```swift
|
||||
/// // Application code
|
||||
/// import MyLibrary
|
||||
/// import GRDB
|
||||
///
|
||||
/// let myLibrarySchemaSource = MyLibrarySchemaSource()
|
||||
/// let customSchemaSource = TheirCustomSchemaSource()
|
||||
/// let schemaSource = myLibrarySchemaSource.then(customSchemaSource)
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = schemaSource
|
||||
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - db: A database connection.
|
||||
/// - view: The identifier of a database view.
|
||||
func columnsForPrimaryKey(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
inView view: DatabaseObjectID
|
||||
) throws -> [String]?
|
||||
}
|
||||
|
||||
extension DatabaseSchemaSource {
|
||||
public func columnsForPrimaryKey(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
inView view: DatabaseObjectID
|
||||
) throws -> [String]? {
|
||||
nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Combined2SchemaSource
|
||||
|
||||
extension DatabaseSchemaSource {
|
||||
/// Returns a schema source that queries `other` when this source does
|
||||
/// not perform a customization.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let schemaSource1 = SomeSchemaSource()
|
||||
/// let schemaSource2 = AnotherSchemaSource()
|
||||
/// let schemaSource = schemaSource1.then(schemaSource2)
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.schemaSource = schemaSource
|
||||
/// let dbQueue = try DatabaseQueue(path: "...", configuration: config)
|
||||
/// ```
|
||||
public func then(_ other: some DatabaseSchemaSource) -> some DatabaseSchemaSource {
|
||||
Chained2SchemaSource(first: self, second: other)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: move to parameter packs eventually. Parameter packs in generic types
|
||||
// are only available in macOS 14.0.0 or newer.
|
||||
// This schema source is designed to tame bad citizens that customize tables
|
||||
// and views they do not own (such as insufficienly robust schema sources
|
||||
// exposed by external libraries). We should NEVER MERGE the results of the
|
||||
// schema sources.
|
||||
struct Chained2SchemaSource<Source1, Source2>: DatabaseSchemaSource
|
||||
where Source1: DatabaseSchemaSource,
|
||||
Source2: DatabaseSchemaSource
|
||||
{
|
||||
var first: Source1
|
||||
var second: Source2
|
||||
|
||||
func columnsForPrimaryKey(_ db: DatabaseBase<some SQLiteAPI>, inView view: DatabaseObjectID) throws -> [String]? {
|
||||
if let result = try first.columnsForPrimaryKey(db, inView: view) { return result }
|
||||
if let result = try second.columnsForPrimaryKey(db, inView: view) { return result }
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -113,14 +113,7 @@ public final class DatabaseSnapshot {
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
reader.reentrantSync { db in
|
||||
// Commit or rollback, but make sure we leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,24 +147,24 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ block: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
|
||||
public func read<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
try reader.sync(block)
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await reader.execute(value)
|
||||
}
|
||||
|
||||
public func asyncRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
reader.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) rethrows -> T {
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) rethrows -> T {
|
||||
try reader.sync(value)
|
||||
}
|
||||
|
||||
@@ -180,18 +173,18 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
// `DatabaseSnapshotReader`, because of
|
||||
// <https://github.com/apple/swift/issues/74469>.
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await read(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
reader.async { value(.success($0)) }
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try reader.reentrantSync(value)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A database connection that allows concurrent accesses to an unchanging
|
||||
/// database content, as it existed at the moment the snapshot was created.
|
||||
@@ -132,7 +129,7 @@ public final class DatabaseSnapshotPool {
|
||||
/// - parameter configuration: A configuration. If nil, the configuration of
|
||||
/// `db` is used.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(_ db: DatabaseBase<some SQLiteAPI>, configuration: Configuration? = nil) throws {
|
||||
public init(_ db: Database, configuration: Configuration? = nil) throws {
|
||||
let path = db.path
|
||||
var configuration = Self.configure(configuration ?? db.configuration)
|
||||
|
||||
@@ -273,7 +270,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
@@ -297,29 +294,40 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let (reader, releaseReader) = try await readerPool.get()
|
||||
var readerCompletion: PoolCompletion?
|
||||
defer {
|
||||
// readerCompletion might be null in cancelled database accesses
|
||||
releaseReader(readerCompletion ?? .reuse)
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
readerPool.asyncGet { result in
|
||||
do {
|
||||
let (reader, releaseReader) = try result.get()
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
releaseReader(self.poolCompletion(db))
|
||||
}
|
||||
do {
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
try value(db)
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
}
|
||||
let (result, completion) = try await reader.execute { db in
|
||||
let result = Result { try value(db) }
|
||||
let completion = poolCompletion(db)
|
||||
return (result, completion)
|
||||
}
|
||||
readerCompletion = completion
|
||||
return try result.get()
|
||||
}
|
||||
|
||||
public func asyncRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<some SQLiteAPI>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError.connectionIsClosed()))
|
||||
@@ -345,12 +353,12 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
// `DatabaseSnapshotReader`, because of
|
||||
// <https://github.com/apple/swift/issues/74469>.
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await read(value)
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<some SQLiteAPI>) throws -> T) throws -> T {
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync { db in
|
||||
let result = try value(db)
|
||||
@@ -399,11 +407,11 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
private func poolCompletion(_ db: DatabaseBase<some SQLiteAPI>) -> PoolCompletion {
|
||||
private func poolCompletion(_ db: Database) -> PoolCompletion {
|
||||
snapshotIsLost(db) ? .discard : .reuse
|
||||
}
|
||||
|
||||
private func snapshotIsLost(_ db: DatabaseBase<some SQLiteAPI>) -> Bool {
|
||||
private func snapshotIsLost(_ db: Database) -> Bool {
|
||||
do {
|
||||
let currentSnapshot = try WALSnapshot(db)
|
||||
if currentSnapshot.compare(walSnapshot) == 0 {
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -162,7 +159,7 @@ public struct DatabaseValue: Hashable {
|
||||
}
|
||||
|
||||
/// Creates a `DatabaseValue` initialized from a raw SQLite statement pointer.
|
||||
public init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
storage = .null
|
||||
@@ -187,7 +184,7 @@ public struct DatabaseValue: Hashable {
|
||||
}
|
||||
|
||||
extension DatabaseValue: StatementBinding {
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
switch storage {
|
||||
case .null:
|
||||
return sqlite3_bind_null(sqliteStatement, index)
|
||||
|
||||
@@ -80,7 +80,7 @@ extension DatabaseValueConvertible {
|
||||
.databaseValue(databaseValue)
|
||||
}
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, at index: CInt) -> CInt {
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
databaseValue.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
|
||||
@@ -276,7 +276,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: A ``DatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: StatementBase<some SQLiteAPI>,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
@@ -307,7 +307,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An array.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: StatementBase<some SQLiteAPI>,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> [Self]
|
||||
@@ -341,7 +341,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ statement: StatementBase<some SQLiteAPI>,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Self?
|
||||
@@ -376,7 +376,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// - returns: A set.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: StatementBase<some SQLiteAPI>,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Set<Self>
|
||||
@@ -421,7 +421,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: A ``DatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -453,7 +453,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An array.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -488,7 +488,7 @@ extension DatabaseValueConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -522,7 +522,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// - returns: A set.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -541,20 +541,13 @@ extension DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -581,7 +574,7 @@ extension DatabaseValueConvertible {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A ``DatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> DatabaseValueCursor<Self> {
|
||||
public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> DatabaseValueCursor<Self> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchCursor(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -591,20 +584,13 @@ extension DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -622,7 +608,7 @@ extension DatabaseValueConvertible {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: An array.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> [Self] {
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -637,20 +623,13 @@ extension DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -666,7 +645,7 @@ extension DatabaseValueConvertible {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Self? {
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
return try fetchOne(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -678,20 +657,13 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -709,7 +681,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A set.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchSet(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -724,20 +696,13 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -762,7 +727,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A ``DatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseValueCursor<RowDecoder> {
|
||||
public func fetchCursor(_ db: Database) throws -> DatabaseValueCursor<RowDecoder> {
|
||||
try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
@@ -771,20 +736,13 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -800,7 +758,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> [RowDecoder] {
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
@@ -814,20 +772,13 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -841,7 +792,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowDecoder? {
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
@@ -857,8 +808,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -874,7 +825,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchSet(_ db: DatabaseBase<some SQLiteAPI>) throws -> Set<RowDecoder> {
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
try RowDecoder.fetchSet(db, self)
|
||||
}
|
||||
}
|
||||
@@ -22,18 +22,18 @@ import Dispatch
|
||||
/// ### Writing into the Database
|
||||
///
|
||||
/// - ``write(_:)-76inz``
|
||||
/// - ``write(_:)-4gnqx``
|
||||
/// - ``write(_:)-3db50``
|
||||
/// - ``writePublisher(receiveOn:updates:)``
|
||||
/// - ``writePublisher(receiveOn:updates:thenRead:)``
|
||||
/// - ``writeWithoutTransaction(_:)-4qh1w``
|
||||
/// - ``writeWithoutTransaction(_:)-18zhj``
|
||||
/// - ``writeWithoutTransaction(_:)-67mri``
|
||||
/// - ``asyncWrite(_:completion:)``
|
||||
/// - ``asyncWriteWithoutTransaction(_:)``
|
||||
///
|
||||
/// ### Exclusive Access to the Database
|
||||
///
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-280j1``
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-11q6c``
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-48d63``
|
||||
/// - ``asyncBarrierWriteWithoutTransaction(_:)``
|
||||
///
|
||||
/// ### Reading from the Latest Committed Database State
|
||||
@@ -61,7 +61,7 @@ import Dispatch
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyDatabaseWriter``
|
||||
public protocol DatabaseWriterBase: DatabaseReaderBase {
|
||||
public protocol DatabaseWriter: DatabaseReader {
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
@@ -98,7 +98,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T
|
||||
func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
@@ -130,7 +130,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
|
||||
/// database access, or the error thrown by `updates`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
@@ -171,7 +171,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T
|
||||
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
@@ -213,7 +213,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
|
||||
/// database access, or the error thrown by `updates`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
@@ -256,7 +256,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the barrier access to the database.
|
||||
func asyncBarrierWriteWithoutTransaction(
|
||||
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
)
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
@@ -290,7 +290,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
func asyncWriteWithoutTransaction(
|
||||
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
|
||||
_ updates: @escaping @Sendable (Database) -> Void
|
||||
)
|
||||
|
||||
/// Executes database operations, and returns their result after they have
|
||||
@@ -325,7 +325,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
|
||||
///
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - throws: The error thrown by `updates`.
|
||||
func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T
|
||||
func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@@ -374,7 +374,7 @@ public protocol DatabaseWriterBase: DatabaseReaderBase {
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the read access to the database.
|
||||
func spawnConcurrentRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
)
|
||||
}
|
||||
|
||||
@@ -413,7 +413,7 @@ extension DatabaseWriter {
|
||||
/// would happen while establishing the database access or committing
|
||||
/// the transaction.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func write<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func write<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
try writeWithoutTransaction { db in
|
||||
var result: T?
|
||||
try db.inTransaction {
|
||||
@@ -461,7 +461,7 @@ extension DatabaseWriter {
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
/// - parameter completion: A closure called with the transaction result.
|
||||
public func asyncWrite<T>(
|
||||
_ updates: @escaping @Sendable (DatabaseBase<API>) throws -> T,
|
||||
_ updates: @escaping @Sendable (Database) throws -> T,
|
||||
completion: @escaping @Sendable (Database, Result<T, Error>) -> Void
|
||||
) {
|
||||
asyncWriteWithoutTransaction { db in
|
||||
@@ -502,7 +502,7 @@ extension DatabaseWriter {
|
||||
/// is deallocated).
|
||||
public func add(
|
||||
transactionObserver: some TransactionObserver,
|
||||
extent: DatabaseTransactionObservationExtent = .observerLifetime)
|
||||
extent: Database.TransactionObservationExtent = .observerLifetime)
|
||||
{
|
||||
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
|
||||
}
|
||||
@@ -552,7 +552,7 @@ extension DatabaseWriter {
|
||||
// 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 || SQLITE_HAS_CODEC
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
@@ -640,7 +640,7 @@ extension DatabaseWriter {
|
||||
/// database access, or the error thrown by `updates`, or
|
||||
/// `CancellationError` if the task is cancelled.
|
||||
public func write<T: Sendable>(
|
||||
_ updates: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writeWithoutTransaction { db in
|
||||
var result: T?
|
||||
@@ -665,7 +665,7 @@ extension DatabaseWriter {
|
||||
try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") }
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// Creates a new database file at the specified path with a minimum
|
||||
/// amount of disk space.
|
||||
///
|
||||
@@ -733,7 +733,7 @@ extension DatabaseWriter {
|
||||
/// - parameter updates: A closure which accesses the database.
|
||||
public func writePublisher<Output>(
|
||||
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
|
||||
updates: @escaping @Sendable (DatabaseBase<API>) throws -> Output
|
||||
updates: @escaping @Sendable (Database) throws -> Output
|
||||
) -> DatabasePublishers.Write<Output> {
|
||||
OnDemandFuture { fulfill in
|
||||
self.asyncWrite(updates, completion: { _, result in
|
||||
@@ -796,7 +796,7 @@ extension DatabaseWriter {
|
||||
/// - parameter value: A closure which reads from the database.
|
||||
public func writePublisher<T: Sendable, Output>(
|
||||
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
|
||||
updates: @escaping @Sendable (DatabaseBase<API>) throws -> T,
|
||||
updates: @escaping @Sendable (Database) throws -> T,
|
||||
thenRead value: @escaping @Sendable (Database, T) throws -> Output
|
||||
) -> DatabasePublishers.Write<Output> {
|
||||
OnDemandFuture { fulfill in
|
||||
@@ -880,40 +880,40 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.read(value)
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.read(value)
|
||||
}
|
||||
|
||||
public func asyncRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
base.asyncRead(value)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.unsafeRead(value)
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.unsafeRead(value)
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
base.asyncUnsafeRead(value)
|
||||
}
|
||||
|
||||
public func unsafeReentrantRead<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.unsafeReentrantRead(value)
|
||||
}
|
||||
|
||||
@@ -931,45 +931,45 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
|
||||
extension AnyDatabaseWriter: DatabaseWriter {
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func writeWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try base.writeWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.writeWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
try base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(
|
||||
_ updates: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ updates: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
base.asyncBarrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func asyncWriteWithoutTransaction(
|
||||
_ updates: @escaping @Sendable (DatabaseBase<API>) -> Void
|
||||
_ updates: @escaping @Sendable (Database) -> Void
|
||||
) {
|
||||
base.asyncWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ updates: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try base.unsafeReentrantWrite(updates)
|
||||
}
|
||||
|
||||
public func spawnConcurrentRead(
|
||||
_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void
|
||||
_ value: @escaping @Sendable (Result<Database, Error>) -> Void
|
||||
) {
|
||||
base.spawnConcurrentRead(value)
|
||||
}
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import Dispatch
|
||||
|
||||
/// An actor that runs in a DispatchQueue.
|
||||
///
|
||||
/// Inspired by <https://forums.swift.org/t/using-dispatchqueue-as-actors-serial-executor-under-linux/75260/3>
|
||||
actor DispatchQueueActor {
|
||||
private let executor: DispatchQueueExecutor
|
||||
|
||||
/// - precondition: the queue is serial, or flags contains `.barrier`.
|
||||
init(queue: DispatchQueue, flags: DispatchWorkItemFlags = []) {
|
||||
self.executor = DispatchQueueExecutor(queue: queue, flags: flags)
|
||||
}
|
||||
|
||||
nonisolated var unownedExecutor: UnownedSerialExecutor {
|
||||
executor.asUnownedSerialExecutor()
|
||||
}
|
||||
|
||||
func execute<T>(_ work: () throws -> T) rethrows -> T {
|
||||
try work()
|
||||
}
|
||||
}
|
||||
|
||||
private final class DispatchQueueExecutor: SerialExecutor {
|
||||
private let queue: DispatchQueue
|
||||
private let flags: DispatchWorkItemFlags
|
||||
|
||||
init(queue: DispatchQueue, flags: DispatchWorkItemFlags) {
|
||||
self.queue = queue
|
||||
self.flags = flags
|
||||
}
|
||||
|
||||
func enqueue(_ job: UnownedJob) {
|
||||
queue.async(flags: flags) {
|
||||
job.runSynchronously(on: self.asUnownedSerialExecutor())
|
||||
}
|
||||
}
|
||||
|
||||
func asUnownedSerialExecutor() -> UnownedSerialExecutor {
|
||||
UnownedSerialExecutor(ordinary: self)
|
||||
}
|
||||
|
||||
func checkIsolated() {
|
||||
dispatchPrecondition(condition: .onQueue(queue))
|
||||
}
|
||||
}
|
||||
|
||||
#if os(Linux)
|
||||
extension DispatchQueueExecutor: @unchecked Sendable {}
|
||||
#endif
|
||||
@@ -87,20 +87,20 @@ public protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvert
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter singleResult: A hint that a single result row will be
|
||||
/// consumed.
|
||||
func makePreparedRequest<API>(_ db: DatabaseBase<API>, forSingleResult singleResult: Bool) throws -> PreparedRequestBase<API>
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
extension FetchRequest {
|
||||
/// Returns the database region that the request feeds from.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
public func databaseRegion(_ db: DatabaseBase<some SQLiteAPI>) throws -> DatabaseRegion {
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
try makePreparedRequest(db, forSingleResult: false).statement.databaseRegion
|
||||
}
|
||||
}
|
||||
@@ -123,28 +123,28 @@ typealias WillExecuteSupplementaryRequest = (_ request: AnyFetchRequest<Row>, _
|
||||
/// - parameter rows: The rows that are modified by the supplementary fetch.
|
||||
/// - parameter willExecuteSupplementaryRequest: A closure to execute before
|
||||
/// performing supplementary fetches.
|
||||
typealias SupplementaryFetch<API: SQLiteAPI> = (
|
||||
_ db: DatabaseBase<API>,
|
||||
typealias SupplementaryFetch = (
|
||||
_ db: Database,
|
||||
_ rows: [Row],
|
||||
_ willExecuteSupplementaryRequest: WillExecuteSupplementaryRequest?)
|
||||
throws -> Void
|
||||
|
||||
/// A `PreparedRequest` is a request that is ready to be executed.
|
||||
public struct PreparedRequestBase<API: SQLiteAPI> {
|
||||
public struct PreparedRequest {
|
||||
/// A prepared statement with bound parameters.
|
||||
public var statement: StatementBase<API>
|
||||
public var statement: Statement
|
||||
|
||||
/// An eventual adapter for rows fetched by the select statement.
|
||||
public var adapter: (any RowAdapter)?
|
||||
|
||||
/// A closure that performs supplementary fetches.
|
||||
/// Support for eager loading of hasMany associations.
|
||||
var supplementaryFetch: SupplementaryFetch<API>?
|
||||
var supplementaryFetch: SupplementaryFetch?
|
||||
|
||||
init(
|
||||
statement: StatementBase<API>,
|
||||
statement: Statement,
|
||||
adapter: (any RowAdapter)?,
|
||||
supplementaryFetch: SupplementaryFetch<API>? = nil)
|
||||
supplementaryFetch: SupplementaryFetch? = nil)
|
||||
{
|
||||
self.statement = statement
|
||||
self.adapter = adapter
|
||||
@@ -172,7 +172,7 @@ extension FetchRequest {
|
||||
/// - parameter adapter: A closure that accepts a database connection and
|
||||
/// returns a row adapter.
|
||||
public func adapted(
|
||||
_ adapter: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> any RowAdapter
|
||||
_ adapter: @escaping @Sendable (Database) throws -> any RowAdapter
|
||||
) -> AdaptedFetchRequest<Self> {
|
||||
AdaptedFetchRequest(self, adapter)
|
||||
}
|
||||
@@ -183,11 +183,11 @@ extension FetchRequest {
|
||||
/// See ``FetchRequest/adapted(_:)``.
|
||||
public struct AdaptedFetchRequest<Base: FetchRequest> {
|
||||
let base: Base
|
||||
let adapter: @Sendable (DatabaseBase<some SQLiteAPI>) throws -> any RowAdapter
|
||||
let adapter: @Sendable (Database) throws -> any RowAdapter
|
||||
|
||||
/// Creates an adapted request from a base request and a closure that builds
|
||||
/// a row adapter from a database connection.
|
||||
init(_ base: Base, _ adapter: @escaping @Sendable (DatabaseBase<some SQLiteAPI>) throws -> any RowAdapter) {
|
||||
init(_ base: Base, _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
}
|
||||
@@ -202,14 +202,14 @@ extension AdaptedFetchRequest: SQLSubqueryable {
|
||||
extension AdaptedFetchRequest: FetchRequest {
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try base.fetchCount(db)
|
||||
}
|
||||
|
||||
public func makePreparedRequest<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
public func makePreparedRequest(
|
||||
_ db: Database,
|
||||
forSingleResult singleResult: Bool = false)
|
||||
throws -> PreparedRequestBase<API>
|
||||
throws -> PreparedRequest
|
||||
{
|
||||
var preparedRequest = try base.makePreparedRequest(db, forSingleResult: singleResult)
|
||||
|
||||
@@ -262,14 +262,14 @@ extension AnyFetchRequest: SQLSubqueryable {
|
||||
}
|
||||
|
||||
extension AnyFetchRequest: FetchRequest {
|
||||
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try request.fetchCount(db)
|
||||
}
|
||||
|
||||
public func makePreparedRequest<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
public func makePreparedRequest(
|
||||
_ db: Database,
|
||||
forSingleResult singleResult: Bool = false)
|
||||
throws -> PreparedRequestBase<API>
|
||||
throws -> PreparedRequest
|
||||
{
|
||||
try request.makePreparedRequest(db, forSingleResult: singleResult)
|
||||
}
|
||||
@@ -283,11 +283,11 @@ private class FetchRequestEraser: FetchRequest, @unchecked Sendable {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
|
||||
func makePreparedRequest<API>(_ db: DatabaseBase<API>, forSingleResult singleResult: Bool) throws -> PreparedRequestBase<API> {
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
|
||||
func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
|
||||
func fetchCount(_ db: Database) throws -> Int {
|
||||
fatalError("subclass must override")
|
||||
}
|
||||
}
|
||||
@@ -303,11 +303,11 @@ private final class ConcreteFetchRequestEraser<Request: FetchRequest>: FetchRequ
|
||||
request.sqlSubquery
|
||||
}
|
||||
|
||||
override func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
|
||||
override func fetchCount(_ db: Database) throws -> Int {
|
||||
try request.fetchCount(db)
|
||||
}
|
||||
|
||||
override func makePreparedRequest<API>(_ db: DatabaseBase<API>, forSingleResult singleResult: Bool) throws -> PreparedRequestBase<API> {
|
||||
override func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest {
|
||||
try request.makePreparedRequest(db, forSingleResult: singleResult)
|
||||
}
|
||||
}
|
||||
+145
-417
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -55,8 +52,6 @@ import Foundation
|
||||
/// - ``subscript(_:)-9c1fw``
|
||||
/// - ``subscript(_:)-3jhwm``
|
||||
/// - ``subscript(_:)-7krrg``
|
||||
/// - ``decode(_:atIndex:)-33ykh``
|
||||
/// - ``decode(_:atIndex:)-3btwn``
|
||||
/// - ``withUnsafeData(atIndex:_:)``
|
||||
/// - ``dataNoCopy(atIndex:)``
|
||||
///
|
||||
@@ -66,8 +61,7 @@ import Foundation
|
||||
/// - ``subscript(_:)-4k8od``
|
||||
/// - ``subscript(_:)-9rbo7``
|
||||
/// - ``coalesce(_:)-359k7``
|
||||
/// - ``decode(_:forColumn:)-4i1o4``
|
||||
/// - ``decode(_:forColumn:)-4rhs4``
|
||||
/// - ``coalesce(_:)-6nbah``
|
||||
/// - ``withUnsafeData(named:_:)``
|
||||
/// - ``dataNoCopy(named:)``
|
||||
///
|
||||
@@ -76,9 +70,6 @@ import Foundation
|
||||
/// - ``subscript(_:)-9txgm``
|
||||
/// - ``subscript(_:)-2esg7``
|
||||
/// - ``subscript(_:)-wl9a``
|
||||
/// - ``coalesce(_:)-6nbah``
|
||||
/// - ``decode(_:forColumn:)-1ljuo``
|
||||
/// - ``decode(_:forColumn:)-47qeg``
|
||||
/// - ``withUnsafeData(at:_:)``
|
||||
/// - ``dataNoCopy(_:)``
|
||||
///
|
||||
@@ -93,10 +84,6 @@ import Foundation
|
||||
/// - ``subscript(_:)-8god3``
|
||||
/// - ``subscript(_:)-jwnx``
|
||||
/// - ``subscript(_:)-6ge6t``
|
||||
/// - ``decode(_:forKey:)-9bbd3``
|
||||
/// - ``decode(_:forKey:)-2w6lc``
|
||||
/// - ``decode(_:forKey:)-2soc2``
|
||||
/// - ``decodeIfPresent(_:forKey:)``
|
||||
/// - ``PrefetchedRowsView``
|
||||
/// - ``ScopesTreeView``
|
||||
/// - ``ScopesView``
|
||||
@@ -132,10 +119,6 @@ import Foundation
|
||||
///
|
||||
/// - ``RowAdapter``
|
||||
///
|
||||
/// ### Errors
|
||||
///
|
||||
/// - ``RowDecodingError``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``RowCursor``
|
||||
@@ -234,7 +217,7 @@ public final class Row {
|
||||
/// 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: StatementBase<some SQLiteAPI>) {
|
||||
init(statement: Statement) {
|
||||
self.statement = statement
|
||||
self.sqliteStatement = statement.sqliteStatement
|
||||
self.impl = StatementRowImpl(sqliteStatement: statement.sqliteStatement, statement: statement)
|
||||
@@ -243,7 +226,7 @@ public final class Row {
|
||||
|
||||
/// Creates a row that maps an SQLite statement. Further calls to
|
||||
/// sqlite3_step() modify the row.
|
||||
init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>) {
|
||||
init(sqliteStatement: SQLiteStatement) {
|
||||
self.statement = nil
|
||||
self.sqliteStatement = sqliteStatement
|
||||
self.impl = SQLiteStatementRowImpl(sqliteStatement: sqliteStatement)
|
||||
@@ -257,8 +240,8 @@ public final class Row {
|
||||
/// the values from the SQLite statement so that further iteration of the
|
||||
/// statement does not modify the row.
|
||||
convenience init(
|
||||
copiedFromSQLiteStatement sqliteStatement: SQLiteStatementBase<some SQLiteAPI>,
|
||||
statement: StatementBase<some SQLiteAPI>)
|
||||
copiedFromSQLiteStatement sqliteStatement: SQLiteStatement,
|
||||
statement: Statement)
|
||||
{
|
||||
self.init(impl: StatementCopyRowImpl(
|
||||
sqliteStatement: sqliteStatement,
|
||||
@@ -469,7 +452,7 @@ extension Row {
|
||||
/// ```
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
|
||||
try! decode(Value.self, forColumn: columnName)
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -506,7 +489,7 @@ extension Row {
|
||||
/// ```
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
|
||||
try! decode(Value.self, forColumn: columnName)
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the
|
||||
@@ -550,7 +533,7 @@ extension Row {
|
||||
/// ```
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: some ColumnExpression) -> Value {
|
||||
try! decode(Value.self, forColumn: column)
|
||||
try! decode(Value.self, forKey: column.name)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -590,7 +573,7 @@ extension Row {
|
||||
-> Value
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
try! decode(Value.self, forColumn: column)
|
||||
try! decode(Value.self, forKey: column.name)
|
||||
}
|
||||
|
||||
/// Calls the given closure with the `Data` at given index.
|
||||
@@ -756,13 +739,12 @@ extension Row {
|
||||
|
||||
// MARK: - Extracting Records
|
||||
|
||||
/// Returns the record associated to the given key.
|
||||
/// The record associated to the given scope.
|
||||
///
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
/// and ``JoinableRequest/including(optional:)`` request methods. The
|
||||
/// latter define row scopes named after the key of included
|
||||
/// associations between record types.
|
||||
/// Row scopes can be defined manually, with ``ScopeAdapter``.
|
||||
/// The ``JoinableRequest/including(required:)`` and
|
||||
/// ``JoinableRequest/including(optional:)`` request methods define scopes
|
||||
/// named after the key of included associations between record types.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
@@ -787,28 +769,26 @@ extension Row {
|
||||
/// let request = Book
|
||||
/// .including(required: Book.author
|
||||
/// .including(required: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// let bookRow = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author = row["author"]
|
||||
/// let country: Country = row["country"]
|
||||
/// let book = try Book(row: bookRow)
|
||||
/// let author: Author = bookRow["author"]
|
||||
/// let country: Country = bookRow["country"]
|
||||
/// ```
|
||||
///
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
/// See also: ``scopesTree``
|
||||
///
|
||||
/// - parameter scope: A scope identifier.
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
|
||||
try! decode(Record.self, forKey: scope)
|
||||
}
|
||||
|
||||
/// Returns the eventual record associated to the given key.
|
||||
/// The eventual record associated to the given scope.
|
||||
///
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
/// and ``JoinableRequest/including(optional:)`` request methods. The
|
||||
/// latter define row scopes named after the key of included
|
||||
/// associations between record types.
|
||||
/// Row scopes can be defined manually, with ``ScopeAdapter``.
|
||||
/// The ``JoinableRequest/including(required:)`` and
|
||||
/// ``JoinableRequest/including(optional:)`` request methods define scopes
|
||||
/// named after the key of included associations between record types.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
@@ -829,26 +809,25 @@ extension Row {
|
||||
///
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// // Fetch a book, with its eventual author, and the country of its author.
|
||||
/// // Fetch a book, with its author, and the country of its author.
|
||||
/// let request = Book
|
||||
/// .including(optional: Book.author
|
||||
/// .including(optional: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// let bookRow = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author? = row["author"]
|
||||
/// let country: Country? = row["country"]
|
||||
/// let book = try Book(row: bookRow)
|
||||
/// let author: Author? = bookRow["author"]
|
||||
/// let country: Country? = bookRow["country"]
|
||||
/// ```
|
||||
///
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
/// See also: ``scopesTree``
|
||||
///
|
||||
/// - parameter scope: A scope identifier.
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record? {
|
||||
try! decodeIfPresent(Record.self, forKey: scope)
|
||||
}
|
||||
|
||||
/// Returns a collection of prefetched records associated to the given
|
||||
/// A collection of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
@@ -864,10 +843,10 @@ extension Row {
|
||||
/// struct Book: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// let authorRow = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: [Book] = row["books"]
|
||||
/// let author = try Author(row: authorRow)
|
||||
/// let books: [Book] = author["books"]
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
@@ -882,8 +861,7 @@ extension Row {
|
||||
try! decode(Records.self, forKey: key)
|
||||
}
|
||||
|
||||
/// Returns the set of prefetched records associated to the given
|
||||
/// association key.
|
||||
/// A set prefetched records associated to the given association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
/// request method.
|
||||
@@ -898,10 +876,10 @@ extension Row {
|
||||
/// struct Book: TableRecord, FetchableRecord, Hashable { }
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// let authorRow = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: Set<Book> = row["books"]
|
||||
/// let author = try Author(row: authorRow)
|
||||
/// let books: Set<Book> = author["books"]
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
@@ -957,8 +935,7 @@ extension Row {
|
||||
/// // Prints [code:"US" name:"United States of America"]
|
||||
/// ```
|
||||
///
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
/// See also ``scopesTree``.
|
||||
public var scopes: ScopesView {
|
||||
impl.scopes(prefetchedRows: prefetchedRows)
|
||||
}
|
||||
@@ -1088,28 +1065,10 @@ extension Row {
|
||||
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
|
||||
/// rightmost column.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
|
||||
/// let score = try row.decode(Int.self, atIndex: 0) // 42
|
||||
/// let score: Int = try row.decode(atIndex: 0) // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
|
||||
/// let name = try row.decode(String.self, atIndex: 0) // "Alice"
|
||||
/// let name: String = try row.decode(atIndex: 0) // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
|
||||
/// let name: String? = try row.decode(atIndex: 0) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
/// If the SQLite value is NULL, or if the conversion fails, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible>(
|
||||
func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value
|
||||
@@ -1123,37 +1082,13 @@ extension Row {
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score = try row.decode(Int.self, forColumn: "score") // 42
|
||||
/// let score: Int = try row.decode(forColumn: "score") // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name = try row.decode(String.self, forColumn: "name") // "Alice"
|
||||
/// let name: String = try row.decode(forColumn: "name") // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: "name") // nil
|
||||
/// ```
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: "missing") // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
/// If the row does not contain the column, or if the SQLite value is NULL,
|
||||
/// or if the SQLite value can not be converted to `Value`, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible>(
|
||||
func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forColumn columnName: String)
|
||||
forKey columnName: String)
|
||||
throws -> Value
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
@@ -1165,47 +1100,6 @@ extension Row {
|
||||
}
|
||||
return try Value.decode(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score = try row.decode(Int.self, forColumn: Column("score")) // 42
|
||||
/// let score: Int = try row.decode(forColumn: Column("score")) // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name = try row.decode(String.self, forColumn: Column("name")) // "Alice"
|
||||
/// let name: String = try row.decode(forColumn: Column("name")) // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: Column("name")) // nil
|
||||
/// ```
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: Column("missing")) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forColumn column: some ColumnExpression)
|
||||
throws -> Value
|
||||
{
|
||||
try decode(type, forColumn: column.name)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods
|
||||
@@ -1220,29 +1114,11 @@ extension Row {
|
||||
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
|
||||
/// rightmost column.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
|
||||
/// let score = try row.decode(Int.self, atIndex: 0) // 42
|
||||
/// let score: Int = try row.decode(atIndex: 0) // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
|
||||
/// let name = try row.decode(String.self, atIndex: 0) // "Alice"
|
||||
/// let name: String = try row.decode(atIndex: 0) // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
|
||||
/// let name: String? = try row.decode(atIndex: 0) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
/// If the SQLite value is NULL, or if the conversion fails, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value
|
||||
@@ -1260,37 +1136,13 @@ extension Row {
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score = try row.decode(Int.self, forColumn: "score") // 42
|
||||
/// let score: Int = try row.decode(forColumn: "score") // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name = try row.decode(String.self, forColumn: "name") // "Alice"
|
||||
/// let name: String = try row.decode(forColumn: "name") // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: "name") // nil
|
||||
/// ```
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: "missing") // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
/// If the row does not contain the column, or if the SQLite value is NULL,
|
||||
/// or if the SQLite value can not be converted to `Value`, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forColumn columnName: String)
|
||||
forKey columnName: String)
|
||||
throws -> Value
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
@@ -1303,51 +1155,6 @@ extension Row {
|
||||
return try Value.fastDecode(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// ``StatementColumnConvertible``. It can trigger [SQLite built-in
|
||||
/// conversions](https://www.sqlite.org/datatype3.html).
|
||||
///
|
||||
/// Column name lookup is case-insensitive. When several columns exist with
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score = try row.decode(Int.self, forColumn: Column("score")) // 42
|
||||
/// let score: Int = try row.decode(forColumn: Column("score")) // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name = try row.decode(String.self, forColumn: Column("name")) // "Alice"
|
||||
/// let name: String = try row.decode(forColumn: Column("name")) // "Alice"
|
||||
/// ```
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: Column("name")) // nil
|
||||
/// ```
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String? = try row.decode(forColumn: Column("missing")) // nil
|
||||
/// ```
|
||||
///
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forColumn column: some ColumnExpression)
|
||||
throws -> Value
|
||||
{
|
||||
try decode(type, forColumn: column.name)
|
||||
}
|
||||
|
||||
// Support for fast decoding in scoped rows
|
||||
@usableFromInline
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
@@ -1380,51 +1187,37 @@ extension Row {
|
||||
// MARK: - Throwing Record Decoding Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the eventual record associated to the given key.
|
||||
///
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
/// and ``JoinableRequest/including(optional:)`` request methods. The
|
||||
/// latter define row scopes named after the key of included
|
||||
/// associations between record types.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
///
|
||||
/// The result is nil if the scope is not available, or contains only
|
||||
/// `NULL` values.
|
||||
/// Returns the eventual record associated with the given scope.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
/// let request = Book.including(optional: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let country = belongsTo(Country.self)
|
||||
/// }
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
/// let author: Author? = row["author"]
|
||||
/// print(author.name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// // Fetch a book, with its eventual author, and the country of its author.
|
||||
/// let request = Book
|
||||
/// .including(optional: Book.author
|
||||
/// .including(optional: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// Associated records stored in nested associations are available, too:
|
||||
///
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author? = try row.decode(forKey: "author")
|
||||
/// let country: Country? = try row.decode(forKey: "country")
|
||||
/// ```
|
||||
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// - parameter type: The decoded type.
|
||||
/// - parameter scope: A scope identifier.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decodeIfPresent<Record: FetchableRecord>(
|
||||
/// let country: Country? = row["country"]
|
||||
/// print(country.name)
|
||||
/// // Prints "United States"
|
||||
///
|
||||
/// Nil is returned if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
|
||||
func decodeIfPresent<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
throws -> Record?
|
||||
@@ -1435,48 +1228,37 @@ extension Row {
|
||||
return try Record(row: scopedRow)
|
||||
}
|
||||
|
||||
/// Returns the record associated to the given key.
|
||||
///
|
||||
/// The key is a row scope that was either defined manually, with
|
||||
/// ``ScopeAdapter``, or with the ``JoinableRequest/including(required:)``
|
||||
/// and ``JoinableRequest/including(optional:)`` request methods. The
|
||||
/// latter define row scopes named after the key of included
|
||||
/// associations between record types.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
/// Returns the record associated with the given scope.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
/// let request = Book.including(required: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let country = belongsTo(Country.self)
|
||||
/// }
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
/// let author: Author = row["author"]
|
||||
/// print(author.name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// // Fetch a book, with its author, and the country of its author.
|
||||
/// let request = Book
|
||||
/// .including(required: Book.author
|
||||
/// .including(required: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// Associated records stored in nested associations are available, too:
|
||||
///
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author = try row.decode(forKey: "author")
|
||||
/// let country: Country = try row.decode(forKey: "country")
|
||||
/// ```
|
||||
/// let request = Book.including(required: Book.author.including(required: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// - parameter type: The decoded type.
|
||||
/// - parameter scope: A scope identifier.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decode<Record: FetchableRecord>(
|
||||
/// let country: Country = row["country"]
|
||||
/// print(country.name)
|
||||
/// // Prints "United States"
|
||||
///
|
||||
/// A fatal error is raised if the scope is not available, or contains only
|
||||
/// null values.
|
||||
///
|
||||
/// See ``splittingRowAdapters(columnCounts:)`` for a sample code.
|
||||
func decode<Record: FetchableRecord>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
throws -> Record
|
||||
@@ -1518,34 +1300,20 @@ extension Row {
|
||||
// MARK: - Throwing Record RangeReplaceableCollection and Set Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns a collection of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
/// request method.
|
||||
/// Returns the records encoded in the given prefetched rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let books = hasMany(Book.self)
|
||||
/// }
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// struct Book: TableRecord, FetchableRecord { }
|
||||
/// try print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: [Book] = try row.decode(forKey: "books")
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
///
|
||||
/// - parameter type: The type of the decoded collection.
|
||||
/// - parameter key: An association key.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decode<Collection>(
|
||||
/// let books: [Book] = row["books"]
|
||||
/// print(books[0].title)
|
||||
/// // Prints "Moby-Dick"
|
||||
func decode<Collection>(
|
||||
_ type: Collection.Type = Collection.self,
|
||||
forKey key: String)
|
||||
throws -> Collection
|
||||
@@ -1553,7 +1321,6 @@ extension Row {
|
||||
Collection: RangeReplaceableCollection,
|
||||
Collection.Element: FetchableRecord
|
||||
{
|
||||
// TODO: test independently
|
||||
guard let rows = prefetchedRows[key] else {
|
||||
let availableKeys = prefetchedRows.keys
|
||||
if availableKeys.isEmpty {
|
||||
@@ -1584,39 +1351,24 @@ extension Row {
|
||||
return collection
|
||||
}
|
||||
|
||||
/// Returns the set of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
/// request method.
|
||||
/// Returns the set of records encoded in the given prefetched rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let books = hasMany(Book.self)
|
||||
/// }
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// struct Book: TableRecord, FetchableRecord, Hashable { }
|
||||
/// try print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: Set<Book> = try row.decode(forKey: "books")
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
///
|
||||
/// - parameter type: The type of the decoded set.
|
||||
/// - parameter key: An association key.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decode<Record: FetchableRecord & Hashable>(
|
||||
/// let books: Set<Book> = row["books"]
|
||||
/// print(books.first!.title)
|
||||
/// // Prints "Moby-Dick"
|
||||
func decode<Record: FetchableRecord & Hashable>(
|
||||
_ type: Set<Record>.Type = Set<Record>.self,
|
||||
forKey key: String)
|
||||
throws -> Set<Record>
|
||||
{
|
||||
// TODO: test independently
|
||||
guard let rows = prefetchedRows[key] else {
|
||||
let availableKeys = prefetchedRows.keys
|
||||
if availableKeys.isEmpty {
|
||||
@@ -1736,7 +1488,7 @@ extension Row {
|
||||
/// - returns: A ``RowCursor`` over fetched rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: StatementBase<some SQLiteAPI>,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> RowCursor
|
||||
@@ -1764,7 +1516,7 @@ extension Row {
|
||||
/// - returns: An array of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: StatementBase<some SQLiteAPI>,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> [Row]
|
||||
@@ -1793,7 +1545,7 @@ extension Row {
|
||||
/// - returns: A set of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: StatementBase<some SQLiteAPI>,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Set<Row>
|
||||
@@ -1822,7 +1574,7 @@ extension Row {
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ statement: StatementBase<some SQLiteAPI>,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Row?
|
||||
@@ -1877,7 +1629,7 @@ extension Row {
|
||||
/// - returns: A ``RowCursor`` over fetched rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -1906,7 +1658,7 @@ extension Row {
|
||||
/// - returns: An array of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -1935,7 +1687,7 @@ extension Row {
|
||||
/// - returns: A set of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -1964,7 +1716,7 @@ extension Row {
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -1983,17 +1735,11 @@ extension Row {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter { $0.lastName == lastName }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -2027,7 +1773,7 @@ extension Row {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A ``RowCursor`` over fetched rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> RowCursor {
|
||||
public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> RowCursor {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
precondition(request.supplementaryFetch == nil, "Not implemented: fetchCursor with supplementary fetch")
|
||||
return try fetchCursor(request.statement, adapter: request.adapter)
|
||||
@@ -2038,17 +1784,11 @@ extension Row {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter { $0.lastName == lastName }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -2064,7 +1804,7 @@ extension Row {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: An array of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> [Row] {
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
let rows = try fetchAll(request.statement, adapter: request.adapter)
|
||||
try request.supplementaryFetch?(db, rows, nil)
|
||||
@@ -2076,17 +1816,11 @@ extension Row {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter { $0.lastName == lastName }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -2102,7 +1836,7 @@ extension Row {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A set of rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Set<Row> {
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Row> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
if let supplementaryFetch = request.supplementaryFetch {
|
||||
let rows = try fetchAll(request.statement, adapter: request.adapter)
|
||||
@@ -2118,17 +1852,11 @@ extension Row {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter { $0.lastName == lastName }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -2144,7 +1872,7 @@ extension Row {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Row? {
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
guard let row = try fetchOne(request.statement, adapter: request.adapter) else {
|
||||
return nil
|
||||
@@ -2193,7 +1921,7 @@ extension FetchRequest<Row> {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A ``RowCursor`` over fetched rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowCursor {
|
||||
public func fetchCursor(_ db: Database) throws -> RowCursor {
|
||||
try Row.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
@@ -2214,7 +1942,7 @@ extension FetchRequest<Row> {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of fetched rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> [Row] {
|
||||
public func fetchAll(_ db: Database) throws -> [Row] {
|
||||
try Row.fetchAll(db, self)
|
||||
}
|
||||
|
||||
@@ -2235,7 +1963,7 @@ extension FetchRequest<Row> {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of fetched rows.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchSet(_ db: DatabaseBase<some SQLiteAPI>) throws -> Set<Row> {
|
||||
public func fetchSet(_ db: Database) throws -> Set<Row> {
|
||||
try Row.fetchSet(db, self)
|
||||
}
|
||||
|
||||
@@ -2256,7 +1984,7 @@ extension FetchRequest<Row> {
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional row.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: DatabaseBase<some SQLiteAPI>) throws -> Row? {
|
||||
public func fetchOne(_ db: Database) throws -> Row? {
|
||||
try Row.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A key that is used to decode a value in a row
|
||||
@usableFromInline
|
||||
@@ -26,21 +23,9 @@ enum RowKey: Hashable, Sendable {
|
||||
case prefetchKey(String)
|
||||
}
|
||||
|
||||
/// A decoding error thrown when decoding a database row.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// // RowDecodingError: could not decode String from database value NULL.
|
||||
/// let name = try row.decode(String.self, forColumn: "name")
|
||||
/// ```
|
||||
public struct RowDecodingError: Error {
|
||||
enum Impl {
|
||||
case keyNotFound(RowKey, Context)
|
||||
case valueMismatch(Any.Type, Context)
|
||||
}
|
||||
|
||||
/// A decoding error
|
||||
@usableFromInline
|
||||
enum RowDecodingError: Error {
|
||||
@usableFromInline
|
||||
struct Context: CustomDebugStringConvertible, Sendable {
|
||||
/// A description of what went wrong, for debugging purposes.
|
||||
@@ -70,19 +55,17 @@ public struct RowDecodingError: Error {
|
||||
}
|
||||
}
|
||||
|
||||
var impl: Impl
|
||||
case keyNotFound(RowKey, Context)
|
||||
case valueMismatch(Any.Type, Context)
|
||||
|
||||
var context: Context {
|
||||
switch impl {
|
||||
switch self {
|
||||
case .keyNotFound(_, let context),
|
||||
.valueMismatch(_, let context):
|
||||
return context
|
||||
}
|
||||
}
|
||||
|
||||
static func valueMismatch(_ type: Any.Type, _ context: Context) -> Self {
|
||||
self.init(impl: .valueMismatch(type, context))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
/// `could not decode <Type> from database value <value>` error message.
|
||||
static func valueMismatch(
|
||||
@@ -91,10 +74,11 @@ public struct RowDecodingError: Error {
|
||||
databaseValue: DatabaseValue)
|
||||
-> Self
|
||||
{
|
||||
let context = RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
could not decode \(type) from database value \(databaseValue)
|
||||
""")
|
||||
return self.init(impl: .valueMismatch(type, context))
|
||||
valueMismatch(
|
||||
type,
|
||||
RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
could not decode \(type) from database value \(databaseValue)
|
||||
"""))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
@@ -131,15 +115,11 @@ public struct RowDecodingError: Error {
|
||||
/// error message.
|
||||
@usableFromInline
|
||||
static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
|
||||
self.init(impl: .keyNotFound(
|
||||
keyNotFound(
|
||||
.columnName(columnName),
|
||||
RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
column not found: \(String(reflecting: columnName))
|
||||
""")))
|
||||
}
|
||||
|
||||
static func keyNotFound(_ rowKey: RowKey, _ context: Context) -> Self {
|
||||
self.init(impl: .keyNotFound(rowKey, context))
|
||||
"""))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,7 +167,8 @@ struct RowDecodingContext {
|
||||
}
|
||||
|
||||
extension RowDecodingError: CustomStringConvertible {
|
||||
public var description: String {
|
||||
@usableFromInline
|
||||
var description: String {
|
||||
let context = self.context
|
||||
let row = context.row
|
||||
var chunks: [String] = []
|
||||
|
||||
+3
-3
@@ -118,7 +118,7 @@ public struct SQL: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func qualified(with alias: TableAliasBase) -> Element {
|
||||
fileprivate func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .sql:
|
||||
// A raw SQL string can't be qualified with a table alias,
|
||||
@@ -181,7 +181,7 @@ public struct SQL: Sendable {
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A tuple made of a raw SQL string, and statement arguments.
|
||||
public func build(_ db: DatabaseBase<some SQLiteAPI>) throws -> (sql: String, arguments: StatementArguments) {
|
||||
public func build(_ db: Database) throws -> (sql: String, arguments: StatementArguments) {
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try self.sql(context)
|
||||
return (sql: sql, arguments: context.arguments)
|
||||
@@ -192,7 +192,7 @@ public struct SQL: Sendable {
|
||||
try elements.map { try $0.sql(context) }.joined()
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAliasBase) -> SQL {
|
||||
func qualified(with alias: TableAlias) -> SQL {
|
||||
SQL(elements: elements.map { $0.qualified(with: alias) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,14 +191,14 @@ extension SQLRequest: FetchRequest {
|
||||
.literal(sqlLiteral)
|
||||
}
|
||||
|
||||
public func fetchCount(_ db: DatabaseBase<some SQLiteAPI>) throws -> Int {
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try SQLRequest<Int>("SELECT COUNT(*) FROM (\(self))").fetchOne(db)!
|
||||
}
|
||||
|
||||
public func makePreparedRequest<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
public func makePreparedRequest(
|
||||
_ db: Database,
|
||||
forSingleResult singleResult: Bool = false)
|
||||
throws -> PreparedRequestBase<API>
|
||||
throws -> PreparedRequest
|
||||
{
|
||||
let context = SQLGenerationContext(db)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
public protocol SQLiteAPI {
|
||||
static var SQLITE_NULL: CInt { get }
|
||||
static var SQLITE_OK: CInt { get }
|
||||
|
||||
static func sqlite3_bind_double(_: OpaquePointer?, _: CInt, _: CDouble) -> CInt
|
||||
static func sqlite3_bind_int64(_: OpaquePointer?, _: CInt, _: Int64) -> CInt
|
||||
static func sqlite3_bind_null(_: OpaquePointer?, _: CInt) -> CInt
|
||||
static func sqlite3_bind_text(_: OpaquePointer?, _: CInt, _: UnsafePointer<CChar>?, _: CInt, _: (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt
|
||||
|
||||
static func sqlite3_column_double(_: OpaquePointer?, _ iCol: CInt) -> Double
|
||||
static func sqlite3_column_int64(_: OpaquePointer?, _ iCol: CInt) -> Int64
|
||||
static func sqlite3_column_text(_: OpaquePointer?, _ iCol: CInt) -> UnsafePointer<CChar>?
|
||||
static func sqlite3_column_type(_: OpaquePointer?, _ iCol: CInt) -> CInt
|
||||
|
||||
@discardableResult static func sqlite3_commit_hook(_: OpaquePointer?, _: (@convention(c) (UnsafeMutableRawPointer?) -> Int32)?, _: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?
|
||||
@discardableResult static func sqlite3_rollback_hook(_: OpaquePointer?, _: (@convention(c) (UnsafeMutableRawPointer?) -> Void)?, _: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?
|
||||
@discardableResult static func sqlite3_update_hook(_: OpaquePointer?, _: (@convention(c) (UnsafeMutableRawPointer?, Int32, UnsafePointer<CChar>?, UnsafePointer<CChar>?, Int64) -> Void)?, _: UnsafeMutableRawPointer?) -> UnsafeMutableRawPointer?
|
||||
}
|
||||
|
||||
public typealias sqlite3_destructor_type = @convention(c) (UnsafeMutableRawPointer?) -> Void
|
||||
@@ -59,7 +59,7 @@ final class SchedulingWatchdog: @unchecked Sendable {
|
||||
}
|
||||
|
||||
static func preconditionValidQueue(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
_ message: @autoclosure() -> String = "Database was not used on the correct thread.",
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
@@ -69,11 +69,11 @@ final class SchedulingWatchdog: @unchecked Sendable {
|
||||
|
||||
/// Returns whether the database argument can be used in the current
|
||||
/// dispatch queue.
|
||||
static func allows(_ db: DatabaseBase<some SQLiteAPI>) -> Bool {
|
||||
static func allows(_ db: Database) -> Bool {
|
||||
current?.allows(db) ?? false
|
||||
}
|
||||
|
||||
func allows(_ db: DatabaseBase<some SQLiteAPI>) -> Bool {
|
||||
func allows(_ db: Database) -> Bool {
|
||||
allowedDatabases.contains { $0 === db }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import Foundation
|
||||
|
||||
/// A class that serializes accesses to an SQLite connection.
|
||||
final class SerializedDatabaseBase<API: SQLiteAPI> {
|
||||
final class SerializedDatabase {
|
||||
/// The database connection
|
||||
private let db: DatabaseBase<API>
|
||||
|
||||
/// The actor that performs asynchronous accesses
|
||||
private let actor: DispatchQueueActor
|
||||
private let db: Database
|
||||
|
||||
/// The database configuration
|
||||
var configuration: Configuration { db.configuration }
|
||||
@@ -58,8 +55,6 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
|
||||
} else {
|
||||
self.queue = configuration.makeWriterDispatchQueue(label: identifier)
|
||||
}
|
||||
self.actor = DispatchQueueActor(queue: queue)
|
||||
|
||||
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
|
||||
try queue.sync {
|
||||
do {
|
||||
@@ -92,7 +87,7 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
|
||||
/// - parameter allowingLongLivedTransaction: When true, the
|
||||
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
|
||||
/// ignored until this method is called again with false.
|
||||
func sync<T>(allowingLongLivedTransaction: Bool, _ body: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
func sync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
|
||||
try sync { db in
|
||||
self.allowsUnsafeTransactions = allowingLongLivedTransaction
|
||||
return try body(db)
|
||||
@@ -103,7 +98,7 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
|
||||
/// have finished executing.
|
||||
///
|
||||
/// This method is not reentrant.
|
||||
func sync<T>(_ block: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
func sync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
// Three different cases:
|
||||
//
|
||||
// 1. A database is invoked from some queue like the main queue:
|
||||
@@ -153,7 +148,7 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
|
||||
/// - parameter allowingLongLivedTransaction: When true, the
|
||||
/// ``Configuration/allowsUnsafeTransactions`` configuration flag is
|
||||
/// ignored until this method is called again with false.
|
||||
func reentrantSync<T>(allowingLongLivedTransaction: Bool, _ body: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
func reentrantSync<T>(allowingLongLivedTransaction: Bool, _ body: (Database) throws -> T) rethrows -> T {
|
||||
try reentrantSync { db in
|
||||
self.allowsUnsafeTransactions = allowingLongLivedTransaction
|
||||
return try body(db)
|
||||
@@ -164,7 +159,7 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
|
||||
/// have finished executing.
|
||||
///
|
||||
/// This method is reentrant.
|
||||
func reentrantSync<T>(_ block: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
func reentrantSync<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
// Three different cases:
|
||||
//
|
||||
// 1. A database is invoked from some queue like the main queue:
|
||||
@@ -228,7 +223,7 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
|
||||
}
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
func async(_ block: @escaping @Sendable (DatabaseBase<API>) -> Void) {
|
||||
func async(_ block: @escaping @Sendable (Database) -> Void) {
|
||||
queue.async {
|
||||
block(self.db)
|
||||
self.preconditionNoUnsafeTransactionLeft(self.db)
|
||||
@@ -243,29 +238,27 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
|
||||
/// Executes the block in the current queue.
|
||||
///
|
||||
/// - precondition: the current dispatch queue is valid.
|
||||
func execute<T>(_ block: (DatabaseBase<API>) throws -> T) rethrows -> T {
|
||||
func execute<T>(_ block: (Database) throws -> T) rethrows -> T {
|
||||
preconditionValidQueue()
|
||||
return try block(db)
|
||||
}
|
||||
|
||||
/// Asynchrously executes the block.
|
||||
func execute<T: Sendable>(
|
||||
_ block: @Sendable (DatabaseBase<API>) throws -> T
|
||||
_ block: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
|
||||
return try await withTaskCancellationHandler {
|
||||
try await actor.execute {
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
preconditionNoUnsafeTransactionLeft(db)
|
||||
let dbAccess = CancellableDatabaseAccess()
|
||||
return try await dbAccess.withCancellableContinuation { continuation in
|
||||
self.async { db in
|
||||
do {
|
||||
let result = try dbAccess.inDatabase(db) {
|
||||
try block(db)
|
||||
}
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
cancelMutex.store(db.cancel)
|
||||
try Task.checkCancellation()
|
||||
return try block(db)
|
||||
}
|
||||
} onCancel: {
|
||||
cancelMutex.withLock { $0?() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,7 +288,7 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
|
||||
|
||||
/// Fatal error if a transaction has been left opened.
|
||||
private func preconditionNoUnsafeTransactionLeft(
|
||||
_ db: DatabaseBase<API>,
|
||||
_ db: Database,
|
||||
_ message: @autoclosure() -> String = "A transaction has been left opened at the end of a database access",
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
@@ -312,3 +305,108 @@ final class SerializedDatabaseBase<API: SQLiteAPI> {
|
||||
// It happens the job of SerializedDatabase is precisely to provide thread-safe
|
||||
// access to `Database`.
|
||||
extension SerializedDatabase: @unchecked Sendable { }
|
||||
|
||||
// MARK: - Task Cancellation Support
|
||||
|
||||
enum DatabaseAccessCancellationState: @unchecked Sendable {
|
||||
// @unchecked Sendable because database is only accessed from its
|
||||
// dispatch queue.
|
||||
case notConnected
|
||||
case connected(Database)
|
||||
case cancelled
|
||||
case expired
|
||||
}
|
||||
|
||||
typealias CancellableDatabaseAccess = Mutex<DatabaseAccessCancellationState>
|
||||
|
||||
/// Supports Task cancellation in async database accesses.
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbAccess = CancellableDatabaseAccess()
|
||||
/// return try dbAccess.withCancellableContinuation { continuation in
|
||||
/// asyncDatabaseAccess { db in
|
||||
/// do {
|
||||
/// let result = try dbAccess.inDatabase(db) {
|
||||
/// // Perform database operations
|
||||
/// }
|
||||
/// continuation.resume(returning: result)
|
||||
/// } catch {
|
||||
/// continuation.resume(throwing: error)
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
extension CancellableDatabaseAccess: DatabaseCancellable {
|
||||
convenience init() {
|
||||
self.init(.notConnected)
|
||||
}
|
||||
|
||||
func cancel() {
|
||||
withLock { state in
|
||||
switch state {
|
||||
case let .connected(db):
|
||||
db.cancel()
|
||||
state = .cancelled
|
||||
case .notConnected:
|
||||
state = .cancelled
|
||||
case .cancelled, .expired:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func withCancellableContinuation<Value>(
|
||||
_ fn: (UnsafeContinuation<Value, any Error>) -> Void
|
||||
) async throws -> Value {
|
||||
try await withTaskCancellationHandler {
|
||||
try checkCancellation()
|
||||
return try await withUnsafeThrowingContinuation { continuation in
|
||||
fn(continuation)
|
||||
}
|
||||
} onCancel: {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func checkCancellation() throws {
|
||||
try withLock { state in
|
||||
if case .cancelled = state {
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps a full database access with cancellation support. When this
|
||||
/// method returns, the database is NOT cancelled.
|
||||
func inDatabase<Value>(_ db: Database, execute work: () throws -> Value) throws -> Value {
|
||||
try withLock { state in
|
||||
switch state {
|
||||
case .connected, .expired:
|
||||
fatalError("Can't use a CancellableDatabaseAccess twice")
|
||||
case .notConnected:
|
||||
state = .connected(db)
|
||||
case .cancelled:
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
|
||||
return try throwingFirstError {
|
||||
try work()
|
||||
} finally: {
|
||||
let cancelled = withLock { state in
|
||||
if case .cancelled = state {
|
||||
db.uncancel()
|
||||
return true
|
||||
} else {
|
||||
state = .expired
|
||||
return false
|
||||
}
|
||||
}
|
||||
if cancelled {
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
-24
@@ -1,22 +1,16 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A raw SQLite statement, suitable for the SQLite C API.
|
||||
//public typealias SQLiteStatement = OpaquePointer
|
||||
public struct SQLiteStatementBase<API: SQLiteAPI> {
|
||||
public let rawValue: OpaquePointer
|
||||
}
|
||||
public typealias SQLiteStatement = OpaquePointer
|
||||
|
||||
extension String {
|
||||
/// SQL statements are separated by semicolons and white spaces.
|
||||
@@ -40,7 +34,7 @@ extension String {
|
||||
}
|
||||
}
|
||||
|
||||
public final class StatementBase<API: SQLiteAPI> {
|
||||
public final class Statement {
|
||||
enum TransactionEffect: Equatable {
|
||||
case beginTransaction
|
||||
case commitTransaction
|
||||
@@ -51,7 +45,7 @@ public final class StatementBase<API: SQLiteAPI> {
|
||||
}
|
||||
|
||||
/// The raw SQLite statement, suitable for the SQLite C API.
|
||||
public let sqliteStatement: SQLiteStatementBase<API>
|
||||
public let sqliteStatement: SQLiteStatement
|
||||
|
||||
/// The SQL query.
|
||||
public var sql: String {
|
||||
@@ -98,9 +92,6 @@ public final class StatementBase<API: SQLiteAPI> {
|
||||
/// The effects on the database (reported by `sqlite3_set_authorizer`).
|
||||
private(set) var authorizerEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
|
||||
private(set) var isQueryOnlyPragma = false
|
||||
|
||||
/// A boolean value indicating if the prepared statement makes no direct
|
||||
/// changes to the content of the database file.
|
||||
///
|
||||
@@ -147,7 +138,7 @@ public final class StatementBase<API: SQLiteAPI> {
|
||||
let authorizer = database.authorizer
|
||||
authorizer.reset()
|
||||
|
||||
var sqliteStatement: SQLiteStatement?
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
let code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, prepFlags,
|
||||
&sqliteStatement, statementEnd)
|
||||
@@ -169,7 +160,6 @@ public final class StatementBase<API: SQLiteAPI> {
|
||||
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
|
||||
self.transactionEffect = authorizer.transactionEffect
|
||||
self.authorizerEventKinds = authorizer.databaseEventKinds
|
||||
self.isQueryOnlyPragma = authorizer.isQueryOnlyPragma
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -842,11 +832,11 @@ public protocol StatementBinding {
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments.
|
||||
/// - returns: the code returned by the `sqlite3_bind_xxx` function.
|
||||
func bind(to sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, at index: CInt) -> CInt
|
||||
func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt
|
||||
}
|
||||
|
||||
/// Helper function for `withBinding(to:at:do:)` methods.
|
||||
func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatementBase<some SQLiteAPI>) throws {
|
||||
func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatement) throws {
|
||||
if code == SQLITE_OK { return }
|
||||
let message = String(cString: sqlite3_errmsg(sqlite3_db_handle(sqliteStatement)))
|
||||
let sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
#if canImport(string_h)
|
||||
import string_h
|
||||
@@ -44,9 +41,6 @@ final class StatementAuthorizer {
|
||||
/// savepoint statement.
|
||||
var transactionEffect: Statement.TransactionEffect?
|
||||
|
||||
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
|
||||
var isQueryOnlyPragma = false
|
||||
|
||||
private var isDropStatement = false
|
||||
|
||||
init(_ database: Database) {
|
||||
@@ -73,7 +67,6 @@ final class StatementAuthorizer {
|
||||
databaseEventKinds = []
|
||||
invalidatesDatabaseSchemaCache = false
|
||||
transactionEffect = nil
|
||||
isQueryOnlyPragma = false
|
||||
isDropStatement = false
|
||||
}
|
||||
|
||||
@@ -199,11 +192,6 @@ final class StatementAuthorizer {
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_PRAGMA:
|
||||
if let cString1 {
|
||||
isQueryOnlyPragma = sqlite3_stricmp(cString1, "query_only") == 0
|
||||
}
|
||||
return SQLITE_OK
|
||||
default:
|
||||
return SQLITE_OK
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// A type that can decode itself from the low-level C interface to
|
||||
/// SQLite results.
|
||||
@@ -92,10 +89,10 @@ public protocol StatementColumnConvertible {
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
/// - returns: A decoded value, or, if decoding is impossible, nil.
|
||||
static func fromStatement<API>(
|
||||
_ sqliteStatement: SQLiteStatementBase<API>,
|
||||
atUncheckedIndex index: CInt
|
||||
) -> Self?
|
||||
static func fromStatement(
|
||||
_ sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: CInt)
|
||||
-> Self?
|
||||
|
||||
/// Creates an instance from a raw SQLite statement pointer, if possible.
|
||||
///
|
||||
@@ -107,7 +104,7 @@ public protocol StatementColumnConvertible {
|
||||
///
|
||||
/// ```swift
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
/// public init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
|
||||
/// public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
/// self = sqlite3_column_int64(sqliteStatement, index)
|
||||
/// }
|
||||
/// }
|
||||
@@ -120,7 +117,7 @@ public protocol StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt)
|
||||
init?(sqliteStatement: SQLiteStatement, index: CInt)
|
||||
}
|
||||
|
||||
extension StatementColumnConvertible {
|
||||
@@ -128,10 +125,7 @@ extension StatementColumnConvertible {
|
||||
/// Default implementation fails on decoding NULL.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public static func fromStatement<API>(
|
||||
_ sqliteStatement: SQLiteStatementBase<API>,
|
||||
atUncheckedIndex index: CInt
|
||||
) -> Self? {
|
||||
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
@@ -301,7 +295,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: StatementBase<some SQLiteAPI>,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
@@ -332,7 +326,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: StatementBase<some SQLiteAPI>,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> [Self]
|
||||
@@ -366,7 +360,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ statement: StatementBase<some SQLiteAPI>,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Self?
|
||||
@@ -404,7 +398,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: StatementBase<some SQLiteAPI>,
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Set<Self>
|
||||
@@ -449,7 +443,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -481,7 +475,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -516,7 +510,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -550,7 +544,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
@@ -569,20 +563,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -609,7 +596,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest)
|
||||
public static func fetchCursor(_ db: Database, _ request: some FetchRequest)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
{
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
@@ -621,20 +608,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -652,7 +632,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchAll(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> [Self] {
|
||||
public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -667,20 +647,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -696,7 +669,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
/// - request: A fetch request.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchOne(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Self? {
|
||||
public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
return try fetchOne(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -708,20 +681,13 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .select(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -739,7 +705,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
/// - request: A fetch request.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public static func fetchSet(_ db: DatabaseBase<some SQLiteAPI>, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set<Self> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchSet(request.statement, adapter: request.adapter)
|
||||
}
|
||||
@@ -754,20 +720,13 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -792,7 +751,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A ``FastDatabaseValueCursor`` over fetched values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: DatabaseBase<some SQLiteAPI>) throws -> FastDatabaseValueCursor<RowDecoder> {
|
||||
public func fetchCursor(_ db: Database) throws -> FastDatabaseValueCursor<RowDecoder> {
|
||||
try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
@@ -801,20 +760,13 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -830,7 +782,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: DatabaseBase<some SQLiteAPI>) throws -> [RowDecoder] {
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder] {
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
@@ -844,20 +796,13 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -871,7 +816,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: DatabaseBase<some SQLiteAPI>) throws -> RowDecoder? {
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder? {
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
@@ -882,20 +827,13 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let lastName = Column("lastName")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -911,7 +849,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func fetchSet(_ db: DatabaseBase<some SQLiteAPI>) throws -> Set<RowDecoder> {
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder> {
|
||||
try RowDecoder.fetchSet(db, self)
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,17 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Data is convertible to and from DatabaseValue.
|
||||
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public init(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
self.init(bytes: bytes, count: count) // copy bytes
|
||||
@@ -49,7 +46,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
withUnsafeBytes {
|
||||
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -81,7 +78,7 @@ extension DatabaseDateComponents: StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -136,7 +133,7 @@ extension Date: StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_INTEGER, SQLITE_FLOAT:
|
||||
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index))
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
#if !os(Linux)
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -50,7 +47,7 @@ extension Decimal: DatabaseValueConvertible {
|
||||
extension Decimal: StatementColumnConvertible {
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_INTEGER:
|
||||
self.init(sqlite3_column_int64(sqliteStatement, index))
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -81,7 +78,7 @@ extension UUID: DatabaseValueConvertible {
|
||||
extension UUID: StatementColumnConvertible {
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_TEXT:
|
||||
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
|
||||
@@ -20,7 +20,7 @@ extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpress
|
||||
}
|
||||
|
||||
extension StatementBinding where Self: RawRepresentable, Self.RawValue: StatementBinding {
|
||||
public func bind(to sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, at index: CInt) -> CInt {
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
rawValue.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ extension StatementBinding where Self: RawRepresentable, Self.RawValue: Statemen
|
||||
extension StatementColumnConvertible where Self: RawRepresentable, Self.RawValue: StatementColumnConvertible {
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
guard let rawValue = RawValue(sqliteStatement: sqliteStatement, index: index) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension Optional: StatementBinding where Wrapped: StatementBinding {
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
switch self {
|
||||
case .none:
|
||||
return API.sqlite3_bind_null(sqliteStatement.rawValue, index)
|
||||
return sqlite3_bind_null(sqliteStatement, index)
|
||||
case let .some(value):
|
||||
return value.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
@@ -87,11 +84,11 @@ extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvert
|
||||
extension Optional: StatementColumnConvertible where Wrapped: StatementColumnConvertible {
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public static func fromStatement<API>(_ sqliteStatement: SQLiteStatementBase<API>, atUncheckedIndex index: CInt) -> Self? {
|
||||
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
|
||||
if let value = Wrapped.fromStatement(sqliteStatement, atUncheckedIndex: index) {
|
||||
// Valid value
|
||||
return value
|
||||
} else if API.sqlite3_column_type(sqliteStatement.rawValue, index) == API.SQLITE_NULL {
|
||||
} else if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
// NULL
|
||||
return .some(.none)
|
||||
} else {
|
||||
@@ -100,7 +97,7 @@ extension Optional: StatementColumnConvertible where Wrapped: StatementColumnCon
|
||||
}
|
||||
}
|
||||
|
||||
public init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
guard let value = Wrapped(sqliteStatement: sqliteStatement, index: index) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
// MARK: - Value Types
|
||||
|
||||
@@ -20,8 +17,8 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
self = API.sqlite3_column_int64(sqliteStatement.rawValue, index) != 0
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
self = sqlite3_column_int64(sqliteStatement, index) != 0
|
||||
}
|
||||
|
||||
/// Returns an INTEGER database value.
|
||||
@@ -102,8 +99,8 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, self ? 1 : 0)
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, self ? 1 : 0)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,8 +114,8 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = Int(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
@@ -141,8 +138,8 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,8 +153,8 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = Int8(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
@@ -180,8 +177,8 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int8(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -195,8 +192,8 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = Int16(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
@@ -219,8 +216,8 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int16(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -234,8 +231,8 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = Int32(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
@@ -258,8 +255,8 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { Int32(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -271,8 +268,8 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
self = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
self = sqlite3_column_int64(sqliteStatement, index)
|
||||
}
|
||||
|
||||
/// Returns an INTEGER database value.
|
||||
@@ -301,8 +298,8 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, self)
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -316,8 +313,8 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = UInt(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
@@ -340,8 +337,8 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -355,8 +352,8 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = UInt8(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
@@ -379,8 +376,8 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt8(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,8 +391,8 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = UInt16(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
@@ -418,8 +415,8 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt16(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -433,8 +430,8 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = UInt32(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
@@ -457,8 +454,8 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt32(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,8 +469,8 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
let int64 = API.sqlite3_column_int64(sqliteStatement.rawValue, index)
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = UInt64(exactly: int64) else { return nil }
|
||||
self = v
|
||||
}
|
||||
@@ -496,8 +493,8 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
Int64.fromDatabaseValue(dbValue).flatMap { UInt64(exactly: $0) }
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_int64(sqliteStatement.rawValue, index, Int64(self))
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_int64(sqliteStatement, index, Int64(self))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -509,8 +506,8 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
self = API.sqlite3_column_double(sqliteStatement.rawValue, index)
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
self = sqlite3_column_double(sqliteStatement, index)
|
||||
}
|
||||
|
||||
/// Returns a REAL database value.
|
||||
@@ -536,8 +533,8 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_double(sqliteStatement.rawValue, index, self)
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_double(sqliteStatement, index, self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -549,8 +546,8 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
self = Float(API.sqlite3_column_double(sqliteStatement.rawValue, index))
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
self = Float(sqlite3_column_double(sqliteStatement, index))
|
||||
}
|
||||
|
||||
/// Returns a REAL database value.
|
||||
@@ -576,8 +573,8 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_double(sqliteStatement.rawValue, index, Double(self))
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_double(sqliteStatement, index, Double(self))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -589,8 +586,8 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init<API>(sqliteStatement: SQLiteStatementBase<API>, index: CInt) {
|
||||
self = String(cString: API.sqlite3_column_text(sqliteStatement.rawValue, index)!)
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
self = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
}
|
||||
|
||||
/// Returns a TEXT database value.
|
||||
@@ -619,8 +616,8 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
public func bind<API>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt) -> CInt {
|
||||
API.sqlite3_bind_text(sqliteStatement.rawValue, index, self, -1, SQLITE_TRANSIENT)
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
sqlite3_bind_text(sqliteStatement, index, self, -1, SQLITE_TRANSIENT)
|
||||
}
|
||||
|
||||
/// Calls the given closure after binding a statement argument.
|
||||
@@ -630,9 +627,9 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameter sqliteStatement: An SQLite statement.
|
||||
/// - parameter index: 1-based index to statement arguments.
|
||||
/// - parameter body: The closure to execute when argument is bound.
|
||||
func withBinding<API, T>(to sqliteStatement: SQLiteStatementBase<API>, at index: CInt, do body: () throws -> T) throws -> T {
|
||||
func withBinding<T>(to sqliteStatement: SQLiteStatement, at index: CInt, do body: () throws -> T) throws -> T {
|
||||
try withCString {
|
||||
let code = API.sqlite3_bind_text(sqliteStatement.rawValue, index, $0, -1, nil /* SQLITE_STATIC */)
|
||||
let code = sqlite3_bind_text(sqliteStatement, index, $0, -1, nil /* SQLITE_STATIC */)
|
||||
try checkBindingSuccess(code: code, sqliteStatement: sqliteStatement)
|
||||
return try body()
|
||||
}
|
||||
@@ -653,7 +650,8 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/capitalized``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let request = Player.select { $0.name.capitalized }
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.capitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let capitalize =
|
||||
@@ -674,7 +672,8 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/lowercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let request = Player.select { $0.name.lowercased }
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.lowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let lowercase =
|
||||
@@ -695,7 +694,8 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/uppercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let request = Player.select { $0.name.uppercased }
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.uppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let uppercase =
|
||||
@@ -716,7 +716,8 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/localizedCapitalized``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let request = Player.select { $0.name.localizedCapitalized }
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let localizedCapitalize =
|
||||
@@ -738,7 +739,8 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/localizedLowercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let request = Player.select { $0.name.localizedLowercase }
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedLowercase)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let localizedLowercase =
|
||||
@@ -759,7 +761,8 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/localizedUppercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let request = Player.select { $0.name.localizedUppercase }
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedUppercase)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let localizedUppercase =
|
||||
|
||||
@@ -10,9 +10,7 @@ import Foundation
|
||||
///
|
||||
/// - ``DefaultTransactionClock``
|
||||
/// - ``CustomTransactionClock``
|
||||
public protocol TransactionClock<API>: Sendable {
|
||||
associatedtype API: SQLiteAPI
|
||||
|
||||
public protocol TransactionClock: Sendable {
|
||||
/// Returns the date of the current transaction.
|
||||
///
|
||||
/// This function is called whenever a transaction starts - precisely
|
||||
@@ -22,33 +20,31 @@ public protocol TransactionClock<API>: Sendable {
|
||||
/// called, and the database connection is not in a transaction.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/get_autocommit.html>
|
||||
func now(_ db: DatabaseBase<API>) throws -> Date
|
||||
func now(_ db: Database) throws -> Date
|
||||
}
|
||||
|
||||
#warning("TODO: expose a version with default api")
|
||||
//extension TransactionClock where Self == DefaultTransactionClock {
|
||||
// /// Returns the default clock.
|
||||
// public static var `default`: Self { DefaultTransactionClock() }
|
||||
//}
|
||||
extension TransactionClock where Self == DefaultTransactionClock {
|
||||
/// Returns the default clock.
|
||||
public static var `default`: Self { DefaultTransactionClock() }
|
||||
}
|
||||
|
||||
#warning("TODO: expose a version with default api")
|
||||
//extension TransactionClock where Self == CustomTransactionClock {
|
||||
// /// Returns a custom clock.
|
||||
// ///
|
||||
// /// The provided closure is called whenever a transaction starts - precisely
|
||||
// /// speaking, whenever the database connection leaves the auto-commit mode.
|
||||
// ///
|
||||
// /// It is also called when the ``Database/transactionDate`` property is
|
||||
// /// called, and the database connection is not in a transaction.
|
||||
// public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
|
||||
// CustomTransactionClock(now)
|
||||
// }
|
||||
//}
|
||||
extension TransactionClock where Self == CustomTransactionClock {
|
||||
/// Returns a custom clock.
|
||||
///
|
||||
/// The provided closure is called whenever a transaction starts - precisely
|
||||
/// speaking, whenever the database connection leaves the auto-commit mode.
|
||||
///
|
||||
/// It is also called when the ``Database/transactionDate`` property is
|
||||
/// called, and the database connection is not in a transaction.
|
||||
public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self {
|
||||
CustomTransactionClock(now)
|
||||
}
|
||||
}
|
||||
|
||||
/// The default transaction clock.
|
||||
public struct DefaultTransactionClock<API: SQLiteAPI>: TransactionClock {
|
||||
public struct DefaultTransactionClock: TransactionClock {
|
||||
/// Returns the start date of the current transaction.
|
||||
public func now(_ db: DatabaseBase<API>) throws -> Date {
|
||||
public func now(_ db: Database) throws -> Date {
|
||||
// An opportunity to fetch transaction time from the database when
|
||||
// SQLite supports the feature.
|
||||
Date()
|
||||
@@ -56,14 +52,14 @@ public struct DefaultTransactionClock<API: SQLiteAPI>: TransactionClock {
|
||||
}
|
||||
|
||||
/// A custom transaction clock.
|
||||
public struct CustomTransactionClock<API: SQLiteAPI>: TransactionClock {
|
||||
let _now: @Sendable (DatabaseBase<API>) throws -> Date
|
||||
public struct CustomTransactionClock: TransactionClock {
|
||||
let _now: @Sendable (Database) throws -> Date
|
||||
|
||||
public init(_ now: @escaping @Sendable (DatabaseBase<API>) throws -> Date) {
|
||||
public init(_ now: @escaping @Sendable (Database) throws -> Date) {
|
||||
self._now = now
|
||||
}
|
||||
|
||||
public func now(_ db: DatabaseBase<API>) throws -> Date {
|
||||
public func now(_ db: Database) throws -> Date {
|
||||
try _now(db)
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,13 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
extension DatabaseBase {
|
||||
extension Database {
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
@@ -33,8 +30,8 @@ extension DatabaseBase {
|
||||
/// the observer lifetime (observation lasts until observer
|
||||
/// is deallocated).
|
||||
public func add(
|
||||
transactionObserver: some TransactionObserverBase<API>,
|
||||
extent: DatabaseTransactionObservationExtent = .observerLifetime)
|
||||
transactionObserver: some TransactionObserver,
|
||||
extent: TransactionObservationExtent = .observerLifetime)
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
guard let observationBroker else { return }
|
||||
@@ -57,7 +54,7 @@ extension DatabaseBase {
|
||||
/// db.remove(transactionObserver: myObserver)
|
||||
/// }
|
||||
/// ```
|
||||
public func remove(transactionObserver: some TransactionObserverBase<API>) {
|
||||
public func remove(transactionObserver: some TransactionObserver) {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
guard let observationBroker else { return }
|
||||
|
||||
@@ -82,7 +79,7 @@ extension DatabaseBase {
|
||||
/// ```swift
|
||||
/// /// Inserts a region in the database, and start monitoring upon
|
||||
/// /// successful insertion.
|
||||
/// func startMonitoring(_ db: DatabaseBase<some SQLiteAPI>, region: CLRegion) throws {
|
||||
/// func startMonitoring(_ db: Database, region: CLRegion) throws {
|
||||
/// // Make sure database is inside a transaction
|
||||
/// try db.inSavepoint {
|
||||
///
|
||||
@@ -113,9 +110,34 @@ extension DatabaseBase {
|
||||
/// - parameter onCommit: A closure executed on transaction commit.
|
||||
/// - parameter onRollback: A closure executed on transaction rollback.
|
||||
public func afterNextTransaction(
|
||||
onCommit: @escaping @Sendable (DatabaseBase<API>) -> Void,
|
||||
onRollback: @escaping @Sendable (DatabaseBase<API>) -> Void = { _ in })
|
||||
onCommit: @escaping @Sendable (Database) -> Void,
|
||||
onRollback: @escaping @Sendable (Database) -> Void = { _ in })
|
||||
{
|
||||
class TransactionHandler: TransactionObserver {
|
||||
let onCommit: @Sendable (Database) -> Void
|
||||
let onRollback: @Sendable (Database) -> Void
|
||||
|
||||
init(
|
||||
onCommit: @escaping @Sendable (Database) -> Void,
|
||||
onRollback: @escaping @Sendable (Database) -> Void
|
||||
) {
|
||||
self.onCommit = onCommit
|
||||
self.onRollback = onRollback
|
||||
}
|
||||
|
||||
// Ignore changes
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false }
|
||||
func databaseDidChange(with event: DatabaseEvent) { }
|
||||
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
onCommit(db)
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
onRollback(db)
|
||||
}
|
||||
}
|
||||
|
||||
// We don't notify read-only transactions to transaction observers
|
||||
GRDBPrecondition(!isReadOnly, "Read-only transactions are not notified")
|
||||
|
||||
@@ -123,42 +145,16 @@ extension DatabaseBase {
|
||||
transactionObserver: TransactionHandler(onCommit: onCommit, onRollback: onRollback),
|
||||
extent: .nextTransaction)
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate class TransactionHandler<API: SQLiteAPI>: TransactionObserverBase {
|
||||
let onCommit: @Sendable (DatabaseBase<API>) -> Void
|
||||
let onRollback: @Sendable (DatabaseBase<API>) -> Void
|
||||
|
||||
init(
|
||||
onCommit: @escaping @Sendable (DatabaseBase<API>) -> Void,
|
||||
onRollback: @escaping @Sendable (DatabaseBase<API>) -> Void
|
||||
) {
|
||||
self.onCommit = onCommit
|
||||
self.onRollback = onRollback
|
||||
}
|
||||
|
||||
// Ignore changes
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false }
|
||||
func databaseDidChange(with event: DatabaseEvent) { }
|
||||
|
||||
func databaseDidCommit(_ db: DatabaseBase<API>) {
|
||||
onCommit(db)
|
||||
/// The extent of the observation performed by a ``TransactionObserver``.
|
||||
public enum TransactionObservationExtent: Sendable {
|
||||
/// Observation lasts until observer is deallocated.
|
||||
case observerLifetime
|
||||
/// Observation lasts until the next transaction.
|
||||
case nextTransaction
|
||||
/// Observation lasts until the database is closed.
|
||||
case databaseLifetime
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: DatabaseBase<API>) {
|
||||
onRollback(db)
|
||||
}
|
||||
}
|
||||
|
||||
#warning("TODO: export as Database.TransactionObservationExtent")
|
||||
/// The extent of the observation performed by a ``TransactionObserver``.
|
||||
public enum DatabaseTransactionObservationExtent: Sendable {
|
||||
/// Observation lasts until observer is deallocated.
|
||||
case observerLifetime
|
||||
/// Observation lasts until the next transaction.
|
||||
case nextTransaction
|
||||
/// Observation lasts until the database is closed.
|
||||
case databaseLifetime
|
||||
}
|
||||
|
||||
// MARK: - DatabaseObservationBroker
|
||||
@@ -171,8 +167,8 @@ public enum DatabaseTransactionObservationExtent: Sendable {
|
||||
/// func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool
|
||||
/// func databaseDidChange(with event: DatabaseEvent)
|
||||
/// func databaseWillCommit() throws
|
||||
/// func databaseDidCommit(_ db: DatabaseBase<some SQLiteAPI>)
|
||||
/// func databaseDidRollback(_ db: DatabaseBase<some SQLiteAPI>)
|
||||
/// func databaseDidCommit(_ db: Database)
|
||||
/// func databaseDidRollback(_ db: Database)
|
||||
/// }
|
||||
///
|
||||
/// First observer is added, and a transaction is started. At this point,
|
||||
@@ -245,8 +241,8 @@ public enum DatabaseTransactionObservationExtent: Sendable {
|
||||
///
|
||||
/// After the statement *has been executed*, the broker calls
|
||||
/// observer.databaseDidCommit().
|
||||
class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
private unowned let database: DatabaseBase<API>
|
||||
class DatabaseObservationBroker {
|
||||
private unowned let database: Database
|
||||
|
||||
/// The savepoint stack allows us to hold database event notifications until
|
||||
/// all savepoints are released. The goal is to only tell transaction
|
||||
@@ -259,10 +255,10 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
private var transactionCompletion = TransactionCompletion.none
|
||||
|
||||
/// The registered transaction observers.
|
||||
private var transactionObservations: [TransactionObservation<API>] = []
|
||||
private var transactionObservations: [TransactionObservation] = []
|
||||
|
||||
/// The observers for an individual statement execution.
|
||||
private var statementObservations: [StatementObservation<API>] = [] {
|
||||
private var statementObservations: [StatementObservation] = [] {
|
||||
didSet {
|
||||
let isEmpty = statementObservations.isEmpty
|
||||
if isEmpty != oldValue.isEmpty {
|
||||
@@ -276,22 +272,22 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
}
|
||||
}
|
||||
|
||||
init(_ database: DatabaseBase<API>) {
|
||||
init(_ database: Database) {
|
||||
self.database = database
|
||||
}
|
||||
|
||||
// MARK: - Transaction observers
|
||||
|
||||
func add(transactionObserver: some TransactionObserverBase<API>, extent: DatabaseTransactionObservationExtent) {
|
||||
func add(transactionObserver: some TransactionObserver, extent: Database.TransactionObservationExtent) {
|
||||
transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent))
|
||||
}
|
||||
|
||||
func remove(transactionObserver: some TransactionObserverBase<API>) {
|
||||
func remove(transactionObserver: some TransactionObserver) {
|
||||
transactionObservations.removeFirst { $0.isWrapping(transactionObserver) }
|
||||
}
|
||||
|
||||
/// Called from ``TransactionObserver/stopObservingDatabaseChangesUntilNextTransaction()``.
|
||||
func disableUntilNextTransaction(transactionObserver: some TransactionObserverBase<API>) {
|
||||
func disableUntilNextTransaction(transactionObserver: some TransactionObserver) {
|
||||
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) {
|
||||
observation.isEnabled = false
|
||||
statementObservations.removeFirst { $0.transactionObservation === observation }
|
||||
@@ -323,7 +319,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
}
|
||||
|
||||
/// Prepares observation of changes that are about to be performed by the statement.
|
||||
func statementWillExecute(_ statement: StatementBase<API>) {
|
||||
func statementWillExecute(_ statement: Statement) {
|
||||
if !database.isReadOnly && !transactionObservations.isEmpty {
|
||||
// As statement executes, it may trigger database changes that will
|
||||
// be notified to transaction observers. As a consequence, observers
|
||||
@@ -399,7 +395,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
|
||||
/// May throw the user-provided cancelled commit error, if a transaction
|
||||
/// observer has cancelled a transaction.
|
||||
func statementDidFail(_ statement: StatementBase<API>) throws {
|
||||
func statementDidFail(_ statement: Statement) throws {
|
||||
// Undo statementWillExecute
|
||||
statementObservations = []
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
@@ -426,7 +422,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
/// May throw the user-provided cancelled commit error, if the statement
|
||||
/// commits an empty transaction, and a transaction observer cancels this
|
||||
/// empty transaction.
|
||||
func statementDidExecute(_ statement: StatementBase<API>) throws {
|
||||
func statementDidExecute(_ statement: Statement) throws {
|
||||
// Undo statementWillExecute
|
||||
if transactionObservations.isEmpty == false {
|
||||
statementObservations = []
|
||||
@@ -553,12 +549,8 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
savepointStack.clear()
|
||||
|
||||
if !database.isReadOnly {
|
||||
// Observers must be able to access the database, even if the
|
||||
// task that has performed the commit is cancelled.
|
||||
database.ignoringCancellation {
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidCommit(database)
|
||||
}
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidCommit(database)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -621,13 +613,8 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
|
||||
if notifyTransactionObservers {
|
||||
assert(!database.isReadOnly, "Read-only transactions are not notified")
|
||||
|
||||
// Observers must be able to access the database, even if the
|
||||
// task that has performed the commit is cancelled.
|
||||
database.ignoringCancellation {
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidRollback(database)
|
||||
}
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidRollback(database)
|
||||
}
|
||||
}
|
||||
databaseDidEndTransaction()
|
||||
@@ -712,7 +699,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
func installCommitAndRollbackHooks() {
|
||||
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
|
||||
API.sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
|
||||
sqlite3_commit_hook(database.sqliteConnection, { brokerPointer in
|
||||
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
|
||||
do {
|
||||
try broker.databaseWillCommit()
|
||||
@@ -726,7 +713,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
}
|
||||
}, brokerPointer)
|
||||
|
||||
API.sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
|
||||
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
|
||||
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
|
||||
switch broker.transactionCompletion {
|
||||
case .cancelledCommit:
|
||||
@@ -742,7 +729,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
private func installUpdateHook() {
|
||||
let brokerPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
|
||||
API.sqlite3_update_hook(
|
||||
sqlite3_update_hook(
|
||||
database.sqliteConnection,
|
||||
{ (brokerPointer, updateKind, databaseNameCString, tableNameCString, rowID) in
|
||||
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
|
||||
@@ -775,7 +762,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
}
|
||||
|
||||
private func uninstallUpdateHook() {
|
||||
API.sqlite3_update_hook(database.sqliteConnection, nil, nil)
|
||||
sqlite3_update_hook(database.sqliteConnection, nil, nil)
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
sqlite3_preupdate_hook(database.sqliteConnection, nil, nil)
|
||||
#endif
|
||||
@@ -801,8 +788,7 @@ class DatabaseObservationBroker<API: SQLiteAPI> {
|
||||
|
||||
// MARK: - TransactionObserver
|
||||
|
||||
public protocol TransactionObserverBase<API>: AnyObject {
|
||||
associatedtype API: SQLiteAPI
|
||||
public protocol TransactionObserver: AnyObject {
|
||||
|
||||
/// Returns whether specific kinds of database changes should be notified
|
||||
/// to the observer.
|
||||
@@ -866,10 +852,10 @@ public protocol TransactionObserverBase<API>: AnyObject {
|
||||
func databaseWillCommit() throws
|
||||
|
||||
/// Called when a transaction has been committed on disk.
|
||||
func databaseDidCommit(_ db: DatabaseBase<API>)
|
||||
func databaseDidCommit(_ db: Database)
|
||||
|
||||
/// Called when a transaction has been rollbacked.
|
||||
func databaseDidRollback(_ db: DatabaseBase<API>)
|
||||
func databaseDidRollback(_ db: Database)
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// Called when the database is changed by an insert, update, or
|
||||
@@ -903,7 +889,7 @@ public protocol TransactionObserverBase<API>: AnyObject {
|
||||
#endif
|
||||
}
|
||||
|
||||
extension TransactionObserverBase {
|
||||
extension TransactionObserver {
|
||||
/// The default implementation does nothing.
|
||||
public func databaseWillCommit() throws { }
|
||||
|
||||
@@ -965,25 +951,22 @@ extension TransactionObserverBase {
|
||||
// MARK: - TransactionObservation
|
||||
|
||||
/// This class manages the observation extent of a transaction observer
|
||||
final class TransactionObservation<API: SQLiteAPI> {
|
||||
let extent: DatabaseTransactionObservationExtent
|
||||
final class TransactionObservation {
|
||||
let extent: Database.TransactionObservationExtent
|
||||
|
||||
/// A disabled observation is not interested in individual database changes.
|
||||
/// It is still interested in transactions commits & rollbacks.
|
||||
var isEnabled = true
|
||||
|
||||
private weak var weakObserver: (any TransactionObserverBase<API>)?
|
||||
private var strongObserver: (any TransactionObserverBase<API>)?
|
||||
private var observer: (any TransactionObserverBase<API>)? {
|
||||
if let strongObserver { return strongObserver }
|
||||
return weakObserver
|
||||
}
|
||||
private weak var weakObserver: (any TransactionObserver)?
|
||||
private var strongObserver: (any TransactionObserver)?
|
||||
private var observer: (any TransactionObserver)? { strongObserver ?? weakObserver }
|
||||
|
||||
fileprivate var isObserving: Bool {
|
||||
observer != nil
|
||||
}
|
||||
|
||||
init(observer: some TransactionObserverBase<API>, extent: DatabaseTransactionObservationExtent) {
|
||||
init(observer: some TransactionObserver, extent: Database.TransactionObservationExtent) {
|
||||
self.extent = extent
|
||||
switch extent {
|
||||
case .observerLifetime:
|
||||
@@ -996,7 +979,7 @@ final class TransactionObservation<API: SQLiteAPI> {
|
||||
}
|
||||
}
|
||||
|
||||
func isWrapping(_ observer: some TransactionObserverBase<API>) -> Bool {
|
||||
func isWrapping(_ observer: some TransactionObserver) -> Bool {
|
||||
self.observer === observer
|
||||
}
|
||||
|
||||
@@ -1025,7 +1008,7 @@ final class TransactionObservation<API: SQLiteAPI> {
|
||||
try observer?.databaseWillCommit()
|
||||
}
|
||||
|
||||
func databaseDidCommit(_ db: DatabaseBase<API>) {
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
switch extent {
|
||||
case .observerLifetime, .databaseLifetime:
|
||||
observer?.databaseDidCommit(db)
|
||||
@@ -1041,7 +1024,7 @@ final class TransactionObservation<API: SQLiteAPI> {
|
||||
}
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: DatabaseBase<API>) {
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
switch extent {
|
||||
case .observerLifetime, .databaseLifetime:
|
||||
observer?.databaseDidRollback(db)
|
||||
@@ -1060,8 +1043,8 @@ final class TransactionObservation<API: SQLiteAPI> {
|
||||
|
||||
/// The observation of one particular statement, by a particular
|
||||
/// transaction observer.
|
||||
struct StatementObservation<API: SQLiteAPI> {
|
||||
var transactionObservation: TransactionObservation<API>
|
||||
struct StatementObservation {
|
||||
var transactionObservation: TransactionObservation
|
||||
|
||||
/// A predicate that filters database events that should be notified.
|
||||
///
|
||||
@@ -1072,7 +1055,7 @@ struct StatementObservation<API: SQLiteAPI> {
|
||||
/// ```
|
||||
var tracksEvent: DatabaseEventPredicate
|
||||
|
||||
init(transactionObservation: TransactionObservation<API>, trackingEvents predicate: DatabaseEventPredicate) {
|
||||
init(transactionObservation: TransactionObservation, trackingEvents predicate: DatabaseEventPredicate) {
|
||||
self.transactionObservation = transactionObservation
|
||||
self.tracksEvent = predicate
|
||||
}
|
||||
@@ -1260,16 +1243,16 @@ private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
|
||||
|
||||
public struct DatabasePreUpdateEvent {
|
||||
|
||||
/// An event kind.
|
||||
public enum Kind: CInt, Sendable {
|
||||
/// An insertion event
|
||||
case insert = 18 // SQLITE_INSERT
|
||||
/// An event kind
|
||||
public enum Kind: CInt {
|
||||
/// SQLITE_INSERT
|
||||
case insert = 18
|
||||
|
||||
/// A deletion event
|
||||
case delete = 9 // SQLITE_DELETE
|
||||
/// SQLITE_DELETE
|
||||
case delete = 9
|
||||
|
||||
/// An update event
|
||||
case update = 23 // SQLITE_UPDATE
|
||||
/// SQLITE_UPDATE
|
||||
case update = 23
|
||||
}
|
||||
|
||||
/// The event kind
|
||||
@@ -1502,7 +1485,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
|
||||
sqlite_func: (_ connection: SQLiteConnection, _ column: CInt, _ value: inout SQLiteValue? ) -> CInt)
|
||||
-> DatabaseValue?
|
||||
{
|
||||
var value: SQLiteValue?
|
||||
var value: SQLiteValue? = nil
|
||||
guard sqlite_func(connection, column, &value) == SQLITE_OK else { return nil }
|
||||
if let value {
|
||||
return DatabaseValue(sqliteValue: value)
|
||||
|
||||
+23
-14
@@ -1,15 +1,12 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
/// An instance of WALSnapshot records the state of a WAL mode database for some
|
||||
/// specific point in history.
|
||||
@@ -19,18 +16,30 @@
|
||||
/// actual observation. This class has no other purpose, and is not intended to
|
||||
/// become public.
|
||||
///
|
||||
/// It does not work with SQLCipher, because SQLCipher does not support
|
||||
/// `SQLITE_ENABLE_SNAPSHOT` correctly: we have linker errors.
|
||||
/// See <https://github.com/ericsink/SQLitePCL.raw/issues/452>.
|
||||
///
|
||||
/// With custom SQLite builds, it only works if `SQLITE_ENABLE_SNAPSHOT`
|
||||
/// is defined.
|
||||
///
|
||||
/// With system SQLite, it works because the SDK exposes the C apis and
|
||||
/// since XCode 14.
|
||||
///
|
||||
/// Yes, this is an awfully complex logic.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
|
||||
final class WALSnapshot: @unchecked Sendable {
|
||||
// @unchecked because sqlite3_snapshot has no threading requirements.
|
||||
// <https://www.sqlite.org/c3ref/snapshot.html>
|
||||
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
|
||||
|
||||
init(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
init(_ db: Database) throws {
|
||||
var sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let code = withUnsafeMutablePointer(to: &sqliteSnapshot) {
|
||||
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
|
||||
}
|
||||
guard code == API.SQLITE_OK else {
|
||||
guard code == SQLITE_OK else {
|
||||
// <https://www.sqlite.org/c3ref/snapshot_get.html>
|
||||
//
|
||||
// > The following must be true for sqlite3_snapshot_get() to succeed. [...]
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
#if SQLITE_ENABLE_SNAPSHOT && !SQLITE_DISABLE_SNAPSHOT
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER)
|
||||
/// A long-live read-only WAL transaction.
|
||||
///
|
||||
/// `WALSnapshotTransaction` **takes ownership** of its reader
|
||||
/// `SerializedDatabase` (TODO: make it a move-only type eventually).
|
||||
final class WALSnapshotTransactionBase<API: SQLiteAPI>: @unchecked Sendable {
|
||||
final class WALSnapshotTransaction: @unchecked Sendable {
|
||||
// @unchecked because `databaseAccess` is protected by a mutex.
|
||||
|
||||
private struct DatabaseAccess {
|
||||
let reader: SerializedDatabaseBase<API>
|
||||
let reader: SerializedDatabase
|
||||
let release: @Sendable (_ isInsideTransaction: Bool) -> Void
|
||||
|
||||
// MUST be called only once
|
||||
@@ -15,13 +15,7 @@ final class WALSnapshotTransactionBase<API: SQLiteAPI>: @unchecked Sendable {
|
||||
// WALSnapshotTransaction may be deinitialized in the dispatch
|
||||
// queue of its reader: allow reentrancy.
|
||||
let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in
|
||||
// Commit or rollback, but try hard to leave the read-only transaction
|
||||
// (commit may fail with a CancellationError).
|
||||
do {
|
||||
try db.commit()
|
||||
} catch {
|
||||
try? db.rollback()
|
||||
}
|
||||
try? db.commit()
|
||||
return db.isInsideTransaction
|
||||
}
|
||||
release(isInsideTransaction)
|
||||
@@ -60,7 +54,7 @@ final class WALSnapshotTransactionBase<API: SQLiteAPI>: @unchecked Sendable {
|
||||
/// - parameter release: A closure to call when the read-only connection
|
||||
/// is no longer used.
|
||||
init(
|
||||
onReader reader: SerializedDatabaseBase<API>,
|
||||
onReader reader: SerializedDatabase,
|
||||
release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void)
|
||||
throws
|
||||
{
|
||||
@@ -90,7 +84,7 @@ final class WALSnapshotTransactionBase<API: SQLiteAPI>: @unchecked Sendable {
|
||||
|
||||
/// Executes database operations in the snapshot transaction, and
|
||||
/// returns their result after they have finished executing.
|
||||
func read<T>(_ value: (DatabaseBase<API>) throws -> T) throws -> T {
|
||||
func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try databaseAccessMutex.withLock { databaseAccess in
|
||||
guard let databaseAccess else {
|
||||
throw DatabaseError.snapshotIsLost()
|
||||
@@ -103,7 +97,7 @@ final class WALSnapshotTransactionBase<API: SQLiteAPI>: @unchecked Sendable {
|
||||
|
||||
/// Schedules database operations for execution, and
|
||||
/// returns immediately.
|
||||
func asyncRead(_ value: @escaping @Sendable (Result<DatabaseBase<API>, Error>) -> Void) {
|
||||
func asyncRead(_ value: @escaping @Sendable (Result<Database, Error>) -> Void) {
|
||||
databaseAccessMutex.withLock { databaseAccess in
|
||||
guard let databaseAccess else {
|
||||
value(.failure(DatabaseError.snapshotIsLost()))
|
||||
|
||||
@@ -4,11 +4,17 @@ GRDB helps your app deal with Swift and SQLite concurrency.
|
||||
|
||||
## Overview
|
||||
|
||||
If your app moves slow database jobs off the main thread, so that the user interface remains responsive, then this guide is for you. In the case of apps that share a database with other processes, such as an iOS app and its extensions, don't miss the dedicated <doc:DatabaseSharing> guide after this one.
|
||||
If your app moves slow database jobs off the main thread, so that the user interface remains responsive, then this guide is for you.
|
||||
|
||||
**In all cases, and first and foremost, follow the <doc:Concurrency#Concurrency-Rules> right from the start.**
|
||||
It is extended with three articles that focus on particular aspects of concurrency:
|
||||
|
||||
The other chapters cover, with more details, the fundamentals of SQLite concurrency, and how GRDB makes it manageable from your Swift code.
|
||||
- <doc:DatabaseSharing>: for apps that **share a database** with other processes, such as an iOS app and its extensions
|
||||
- <doc:SwiftConcurrency>: the relationships between GRDB and **Swift 6 Concurrency**
|
||||
- <doc:MainThread>: everything you have to known about GRDB and the main thread.
|
||||
|
||||
**In all cases, and first and foremost, follow the Concurrency-Rules, below, right from the start.**
|
||||
|
||||
The following chapters cover the fundamentals of SQLite concurrency, and how GRDB makes it manageable from your Swift code.
|
||||
|
||||
## Concurrency Rules
|
||||
|
||||
@@ -97,7 +103,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
See ``DatabaseReader/read(_:)-5mfwu`` and ``DatabaseWriter/write(_:)-4gnqx``.
|
||||
See ``DatabaseReader/read(_:)-4d1da`` and ``DatabaseWriter/write(_:)-3db50``.
|
||||
|
||||
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
|
||||
|
||||
@@ -322,7 +328,7 @@ Types that conform to ``TransactionObserver`` can also use those methods in thei
|
||||
|
||||
- <doc:SwiftConcurrency>
|
||||
- <doc:DatabaseSharing>
|
||||
|
||||
- <doc:MainThread>
|
||||
|
||||
[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
|
||||
[`SQLITE_BUSY`]: https://www.sqlite.org/rescode.html#busy
|
||||
|
||||
@@ -29,8 +29,6 @@ Get information about schema objects such as tables, columns, indexes, foreign k
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseSchemaID``
|
||||
- ``DatabaseObjectID``
|
||||
- ``ColumnInfo``
|
||||
- ``ForeignKeyInfo``
|
||||
- ``IndexInfo``
|
||||
|
||||
@@ -252,8 +252,8 @@ Unique constraints and unique indexes are somewhat different: don't miss the tip
|
||||
|
||||
- ``Database/alter(table:body:)``
|
||||
- ``Database/create(table:options:body:)``
|
||||
- ``Database/create(virtualTable:options:using:)``
|
||||
- ``Database/create(virtualTable:options:using:_:)``
|
||||
- ``Database/create(virtualTable:ifNotExists:using:)``
|
||||
- ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
- ``Database/drop(table:)``
|
||||
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
|
||||
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
|
||||
@@ -265,7 +265,6 @@ Unique constraints and unique indexes are somewhat different: don't miss the tip
|
||||
- ``TableDefinition``
|
||||
- ``TableOptions``
|
||||
- ``VirtualTableModule``
|
||||
- ``VirtualTableOptions``
|
||||
|
||||
### Database Views
|
||||
|
||||
@@ -289,5 +288,3 @@ Those are legacy interfaces that are preserved for backwards compatibility. Thei
|
||||
|
||||
- ``Database/create(index:on:columns:unique:ifNotExists:condition:)``
|
||||
- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)``
|
||||
- ``Database/create(virtualTable:ifNotExists:using:)``
|
||||
- ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
@@ -151,7 +151,7 @@ extension Player: FetchableRecord, MutablePersistableRecord {
|
||||
// Required because the primary key
|
||||
// is the hidden rowid column.
|
||||
static var databaseSelection: [any SQLSelectable] {
|
||||
[.allColumns, .rowID]
|
||||
[AllColumns(), Column.rowID]
|
||||
}
|
||||
|
||||
// Update id upon successful insertion
|
||||
@@ -262,11 +262,11 @@ try dbQueue.write { db in
|
||||
|
||||
// Use instead:
|
||||
let player = try Player
|
||||
.filter { $0.teamId == 42 && $0.position == 1 }
|
||||
.filter(Column("teamId") == 42 && Column("position") == 1)
|
||||
.fetchOne(db)
|
||||
|
||||
try Player
|
||||
.filter { $0.name == "Arthur" }
|
||||
.filter(Column("name") == "Arthur")
|
||||
.deleteAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -96,7 +96,6 @@ do {
|
||||
- ``persistentReadOnlyConnections``
|
||||
- ``prepareDatabase(_:)``
|
||||
- ``publicStatementArguments``
|
||||
- ``schemaSource``
|
||||
- ``transactionClock``
|
||||
- ``TransactionClock``
|
||||
|
||||
@@ -107,7 +106,3 @@ do {
|
||||
- ``writeQoS``
|
||||
- ``targetQueue``
|
||||
- ``writeTargetQueue``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``DatabaseSchemaSource``
|
||||
@@ -59,7 +59,7 @@ You can feed `DatabaseRegionObservation` with any type that conforms to the ``Da
|
||||
```swift
|
||||
// Observe the score column of the 'player' table
|
||||
let observation = DatabaseRegionObservation(
|
||||
tracking: Player.select(\.score))
|
||||
tracking: Player.select(Column("score")))
|
||||
|
||||
// Observe the 'score' column of the 'player' table
|
||||
let observation = DatabaseRegionObservation(
|
||||
|
||||
@@ -107,10 +107,10 @@ import GRDB
|
||||
import Tagged
|
||||
|
||||
// Add database support to Tagged values
|
||||
extension Tagged: @retroactive SQLExpressible where RawValue: SQLExpressible { }
|
||||
extension Tagged: @retroactive StatementBinding where RawValue: StatementBinding { }
|
||||
extension Tagged: @retroactive StatementColumnConvertible where RawValue: StatementColumnConvertible { }
|
||||
extension Tagged: @retroactive DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
|
||||
extension Tagged: SQLExpressible where RawValue: SQLExpressible { }
|
||||
extension Tagged: StatementBinding where RawValue: StatementBinding { }
|
||||
extension Tagged: StatementColumnConvertible where RawValue: StatementColumnConvertible { }
|
||||
extension Tagged: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
|
||||
```
|
||||
|
||||
This makes it possible to use `Tagged` values in all the expected places:
|
||||
@@ -128,7 +128,7 @@ For example:
|
||||
|
||||
```swift
|
||||
extension EvenInteger: StatementColumnConvertible {
|
||||
init?(sqliteStatement: SQLiteStatementBase<some SQLiteAPI>, index: CInt) {
|
||||
init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let value = Int(exactly: int64) else {
|
||||
return nil // Does not fit Int (probably a 32-bit architecture)
|
||||
|
||||
@@ -214,7 +214,7 @@ Consider a scenario where you'd like to get a specific Player's row, but only wh
|
||||
let observation = ValueObservation.tracking(
|
||||
// Define the tracked database region
|
||||
// (the score column of the player with id 1)
|
||||
region: Player.select(\.score).filter(id: 1),
|
||||
region: Player.select(Column("score")).filter(id: 1),
|
||||
// Define what to fetch upon such change to the tracked region
|
||||
// (the player with id 1)
|
||||
fetch: { db in try Player.fetchOne(db, id: 1) }
|
||||
@@ -263,10 +263,6 @@ You can filter out undesired duplicate notifications with the ``removeDuplicates
|
||||
|
||||
When needed, you can help GRDB optimize observations and reduce database contention:
|
||||
|
||||
> Important: **Keep your number of observations bounded.**
|
||||
>
|
||||
> In particular, do not observe independently all elements in a list. Instead, observe the whole list in a single observation.
|
||||
|
||||
> Tip: Stop observations when possible.
|
||||
>
|
||||
> For example, if a `UIViewController` needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`.
|
||||
|
||||
@@ -94,7 +94,6 @@ let players: [Player] = try dbQueue.read { db in
|
||||
- <doc:RecordRecommendedPractices>
|
||||
- <doc:RecordTimestamps>
|
||||
- <doc:SingleRowTables>
|
||||
- <doc:ViewRecords>
|
||||
|
||||
### Application Tools
|
||||
|
||||
|
||||
@@ -36,16 +36,10 @@ try db.create(table: "player") { t in
|
||||
> JSONColumn("address")["country"],
|
||||
> ])
|
||||
>
|
||||
> struct Player: FetchableRecord, TableRecord {
|
||||
> enum Columns {
|
||||
> static let address = JSONColumn("address")
|
||||
> }
|
||||
> }
|
||||
>
|
||||
> // SELECT * FROM player
|
||||
> // WHERE address ->> 'country' = 'DE'
|
||||
> let germanPlayers = try Player
|
||||
> .filter { $0.address["country"] == "DE" }
|
||||
> .filter(JSONColumn("address")["country"] == "DE")
|
||||
> .fetchAll(db)
|
||||
> ```
|
||||
|
||||
@@ -110,16 +104,10 @@ extension Team: FetchableRecord, PersistableRecord {
|
||||
> struct Address: Codable { ... }
|
||||
> extension Address: DatabaseValueConvertible {}
|
||||
>
|
||||
> struct Player: FetchableRecord, TableRecord {
|
||||
> enum Columns {
|
||||
> static let address = JSONColumn("address")
|
||||
> }
|
||||
> }
|
||||
>
|
||||
> // SELECT * FROM player
|
||||
> // WHERE address = '{"street": "...", "city": "...", "country": "..."}'
|
||||
> let players = try Player
|
||||
> .filter { $0.address == Address(...) }
|
||||
> .filter(JSONColumn("address") == Address(...))
|
||||
> .fetchAll(db)
|
||||
> ```
|
||||
>
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
# Using or Avoiding the Main Thread
|
||||
|
||||
Everything you have to known about GRDB and the main thread.
|
||||
|
||||
## Overview
|
||||
|
||||
**This guide describes the relationship between GRDB and the main thread.** It complements the <doc:Concurrency> guide, that you should read first.
|
||||
|
||||
Accessing the database from the main thread is handy. Graphical applications, for example, do not need to show a loading screen until values are fetched and ready for display. They do not need to spawn tasks or any other asynchronous constructs in response to user actions.
|
||||
|
||||
There are only two things one should think about when accessing the database from the main thread:
|
||||
- How long does it take to start the database access?
|
||||
- How long does it take to execute the database requests?
|
||||
|
||||
The first delay depends on *database contention*
|
||||
The first delay can be slowed down if the database is already busy
|
||||
|
||||
SQLite is very fast, and many database accesses are so fast that the user has no time to notice them. In a graphical application, performing fast database accesses from the main thread is handy, because the application does not need to show a loading screen until values are fetched and ready for display.
|
||||
|
||||
Other database accesses should be performed in a background thread, in order to avoid user interface freezes.
|
||||
|
||||
In the end, accessing the database on or off the main thread is a choice left to the application.
|
||||
|
||||
The database can be accessed from the main thread, or from a background thread, at the application convenience. In this guide we explain what you have to know when you intend to access the database from the main thread, or when you want to make sure a database access does not block the main thread. We will discuss plain database accesses (`read`, `write`), as well a database observation with ``ValueObservation``.
|
||||
|
||||
### Avoiding the Main Thread
|
||||
|
||||
To avoid performing database accesses from the main thread,
|
||||
|
||||
<!--@START_MENU_TOKEN@-->Text<!--@END_MENU_TOKEN@-->
|
||||
@@ -94,26 +94,6 @@ migrator.registerMigration("Create authors") { db in
|
||||
}
|
||||
```
|
||||
|
||||
#### How to Rename a Foreign Key
|
||||
|
||||
When a migration **renames a foreign key**, make sure the migration runs with `.immediate` foreign key checks, in order to avoid database integrity problems:
|
||||
|
||||
```swift
|
||||
// IMPORTANT: rename foreign keys with immediate foreign key checks.
|
||||
migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in
|
||||
try db.rename(table: "team", to: "guild")
|
||||
|
||||
try db.alter(table: "player") { t in
|
||||
// Rename a foreign key
|
||||
t.rename(column: "teamId", to: "guildId")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note: migrations that run with `.immediate` foreign key checks can not be used to recreated database tables, as described below. When needed, define two migrations instead of one.
|
||||
|
||||
#### How to Recreate a Database Table
|
||||
|
||||
When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table.
|
||||
|
||||
For example:
|
||||
@@ -133,39 +113,19 @@ migrator.registerMigration("Add NOT NULL check on author.name") { db in
|
||||
|
||||
The detailed sequence of operations for recreating a database table from a migration is:
|
||||
|
||||
1. When relevant, remember the format of all indexes, triggers, and views associated with table `X`. This information will be needed in steps 6 below. One way to do this is to run the following statement and examine the output in the console:
|
||||
1. When relevant, remember the format of all indexes, triggers, and views associated with table X. This information will be needed in steps 6 and 7 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`.
|
||||
|
||||
```swift
|
||||
try db.dumpSQL("SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'")
|
||||
```
|
||||
2. Use `CREATE TABLE` to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
|
||||
|
||||
2. Construct a new table `new_X` that is in the desired revised format of table `X`. Make sure that the name `new_X` does not collide with any existing table name, of course.
|
||||
3. Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`.
|
||||
|
||||
```swift
|
||||
try db.create(table: "new_X") { t in ... }
|
||||
```
|
||||
4. Drop the old table X: `DROP TABLE X`.
|
||||
|
||||
3. Transfer content from `X` into `new_X` using a statement like:
|
||||
5. Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`.
|
||||
|
||||
```swift
|
||||
try db.execute(sql: "INSERT INTO new_X SELECT ... FROM X")
|
||||
```
|
||||
6. When relevant, use `CREATE INDEX`, `CREATE TRIGGER`, and `CREATE VIEW` to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration.
|
||||
|
||||
4. Drop the old table `X`:
|
||||
|
||||
```swift
|
||||
try db.drop(table: "X")
|
||||
```
|
||||
|
||||
5. Change the name of `new_X` to `X` using:
|
||||
|
||||
```swift
|
||||
try db.rename(table: "new_X", to: "X")
|
||||
```
|
||||
|
||||
6. When relevant, reconstruct indexes, triggers, and views associated with table `X`.
|
||||
|
||||
7. If any views refer to table `X` in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
|
||||
7. If any views refer to table X in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
|
||||
|
||||
> Important: When recreating a table, be sure to follow the above procedure exactly, in the given order, or you might corrupt triggers, views, and foreign key constraints.
|
||||
>
|
||||
|
||||
@@ -214,7 +214,7 @@ extension Book.Kind: DatabaseValueConvertible { }
|
||||
|
||||
// Fetch all novels
|
||||
let novels = try dbQueue.read { db in
|
||||
try Book.filter { $0.kind == Book.Kind.novel }.fetchAll(db)
|
||||
try Book.filter(Column("kind") == Book.Kind.novel).fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -297,7 +297,7 @@ Once we have record types that are able to read and write in the database, we'd
|
||||
|
||||
### Columns
|
||||
|
||||
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration, with the name `Columns`, nested inside the record type. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
|
||||
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
|
||||
|
||||
```swift
|
||||
// HOW TO define columns for a Codable record
|
||||
@@ -310,15 +310,13 @@ extension Author {
|
||||
}
|
||||
```
|
||||
|
||||
For non-Codable record types, declare columns with their names:
|
||||
For other record types, declare a plain `String` enum that conforms to the ``ColumnExpression`` protocol:
|
||||
|
||||
```swift
|
||||
// HOW TO define columns for a non-Codable record
|
||||
extension Author {
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
static let countryCode = Column("countryCode")
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, countryCode
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -330,12 +328,12 @@ try dbQueue.read { db in
|
||||
// Fetch all authors, ordered by name,
|
||||
// in a localized case-insensitive fashion
|
||||
let sortedAuthors: [Author] = try Author.all()
|
||||
.order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
.fetchAll(db)
|
||||
|
||||
// Count French authors
|
||||
let frenchAuthorCount: Int = try Author.all()
|
||||
.filter { $0.countryCode == "FR" }
|
||||
.filter(Author.Columns.countryCode == "FR")
|
||||
.fetchCount(db)
|
||||
}
|
||||
```
|
||||
@@ -351,12 +349,13 @@ Define those methods in extensions of the ``DerivableRequest`` protocol, as belo
|
||||
extension DerivableRequest<Author> {
|
||||
/// Order authors by name, in a localized case-insensitive fashion
|
||||
func orderByName() -> Self {
|
||||
order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
let name = Author.Columns.name
|
||||
return order(name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// Filters authors from a country
|
||||
func filter(countryCode: String) -> Self {
|
||||
filter { $0.countryCode == countryCode }
|
||||
filter(Author.Columns.countryCode == countryCode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -364,12 +363,13 @@ extension DerivableRequest<Author> {
|
||||
extension DerivableRequest<Book> {
|
||||
/// Order books by title, in a localized case-insensitive fashion
|
||||
func orderByTitle() -> Self {
|
||||
order { $0.title.collating(.localizedCaseInsensitiveCompare) }
|
||||
let title = Book.Columns.title
|
||||
return order(title.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// Filters books by kind
|
||||
func filter(kind: Book.Kind) -> Self {
|
||||
filter { $0.kind == kind }
|
||||
filter(Book.Columns.kind == kind)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -393,16 +393,16 @@ Extensions to the `DerivableRequest` protocol can not change the type of request
|
||||
|
||||
```swift
|
||||
extension QueryInterfaceRequest<Author> {
|
||||
// Selects authors' name
|
||||
func selectName() -> QueryInterfaceRequest<String> {
|
||||
select(\.name)
|
||||
// Selects author ids
|
||||
func selectId() -> QueryInterfaceRequest<Int64> {
|
||||
selectPrimaryKey(as: Int64.self)
|
||||
}
|
||||
}
|
||||
|
||||
// The names of Japanese authors
|
||||
let names: Set<String> = try Author.all()
|
||||
// The ids of Japanese authors
|
||||
let ids: Set<Int64> = try Author.all()
|
||||
.filter(countryCode: "JP")
|
||||
.selectName()
|
||||
.selectId()
|
||||
.fetchSet(db)
|
||||
```
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ On insertion, the `Player` record should get fresh `creationDate` and `modificat
|
||||
extension Player: Encodable, MutablePersistableRecord {
|
||||
/// Sets both `creationDate` and `modificationDate` to the
|
||||
/// transaction date, if they are not set yet.
|
||||
mutating func willInsert(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
mutating func willInsert(_ db: Database) throws {
|
||||
if creationDate == nil {
|
||||
creationDate = try db.transactionDate
|
||||
}
|
||||
@@ -182,7 +182,7 @@ extension Player: Encodable, MutablePersistableRecord {
|
||||
|
||||
/// Sets both `creationDate` and `modificationDate` to the
|
||||
/// transaction date, if they are not set yet.
|
||||
mutating func willInsert(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
mutating func willInsert(_ db: Database) throws {
|
||||
if creationDate == nil {
|
||||
creationDate = try db.transactionDate
|
||||
}
|
||||
@@ -311,7 +311,7 @@ You can copy it in your application, or use it as an inspiration. Not all apps h
|
||||
extension Player {
|
||||
/// If the player has a non-nil primary key and a matching row in
|
||||
/// the database, the player is updated. Otherwise, it is inserted.
|
||||
mutating func saveWithTimestamp(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
mutating func saveWithTimestamp(_ db: Database) throws {
|
||||
// Test the presence of id first, so that we don't perform an
|
||||
// update that would surely throw RecordError.recordNotFound.
|
||||
if id == nil {
|
||||
@@ -332,7 +332,7 @@ The full implementation of `TimestampedRecord` follows:
|
||||
|
||||
```swift
|
||||
/// A record type that tracks its creation and modification dates. See
|
||||
/// <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps>
|
||||
/// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps>
|
||||
protocol TimestampedRecord: MutablePersistableRecord {
|
||||
var creationDate: Date? { get set }
|
||||
var modificationDate: Date? { get set }
|
||||
@@ -346,7 +346,7 @@ extension TimestampedRecord {
|
||||
/// `TimestampedRecord` types that customize the `willInsert`
|
||||
/// persistence callback should call `initializeTimestamps` from
|
||||
/// their implementation.
|
||||
mutating func willInsert(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
mutating func willInsert(_ db: Database) throws {
|
||||
try initializeTimestamps(db)
|
||||
}
|
||||
|
||||
@@ -356,7 +356,7 @@ extension TimestampedRecord {
|
||||
/// It is called automatically before insertion, if your type does not
|
||||
/// customize the `willInsert` persistence callback. If you customize
|
||||
/// this callback, call `initializeTimestamps` from your implementation.
|
||||
mutating func initializeTimestamps(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
mutating func initializeTimestamps(_ db: Database) throws {
|
||||
if creationDate == nil {
|
||||
creationDate = try db.transactionDate
|
||||
}
|
||||
@@ -370,7 +370,7 @@ extension TimestampedRecord {
|
||||
///
|
||||
/// - parameter modificationDate: The modification date. If nil, the
|
||||
/// transaction date is used.
|
||||
mutating func updateWithTimestamp(_ db: DatabaseBase<some SQLiteAPI>, modificationDate: Date? = nil) throws {
|
||||
mutating func updateWithTimestamp(_ db: Database, modificationDate: Date? = nil) throws {
|
||||
self.modificationDate = try modificationDate ?? db.transactionDate
|
||||
try update(db)
|
||||
}
|
||||
@@ -403,7 +403,7 @@ extension TimestampedRecord {
|
||||
/// - returns: Whether the record was changed and updated.
|
||||
@discardableResult
|
||||
mutating func updateChangesWithTimestamp(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
modificationDate: Date? = nil,
|
||||
modify: (inout Self) -> Void)
|
||||
throws -> Bool
|
||||
@@ -431,7 +431,7 @@ extension TimestampedRecord {
|
||||
///
|
||||
/// - parameter modificationDate: The modification date. If nil, the
|
||||
/// transaction date is used.
|
||||
mutating func touch(_ db: DatabaseBase<some SQLiteAPI>, modificationDate: Date? = nil) throws {
|
||||
mutating func touch(_ db: Database, modificationDate: Date? = nil) throws {
|
||||
try updateChanges(db) {
|
||||
$0.modificationDate = try modificationDate ?? db.transactionDate
|
||||
}
|
||||
|
||||
@@ -128,7 +128,7 @@ We have seen in the <doc:SingleRowTables#The-Single-Row-Table> section that by d
|
||||
|
||||
```swift
|
||||
// Customize the default PersistableRecord behavior
|
||||
func willUpdate(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws {
|
||||
func willUpdate(_ db: Database, columns: Set<String>) throws {
|
||||
// Insert the default configuration if it does not exist yet.
|
||||
if try !exists(db) {
|
||||
try AppConfiguration.default.insert(db)
|
||||
@@ -141,7 +141,7 @@ The standard GRDB method ``FetchableRecord/fetchOne(_:)`` returns an optional wh
|
||||
```swift
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func find(_ db: DatabaseBase<some SQLiteAPI>) throws -> AppConfiguration {
|
||||
static func find(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
@@ -233,7 +233,7 @@ extension AppConfiguration {
|
||||
// Database Access
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
// Customize the default PersistableRecord behavior
|
||||
func willUpdate(_ db: DatabaseBase<some SQLiteAPI>, columns: Set<String>) throws {
|
||||
func willUpdate(_ db: Database, columns: Set<String>) throws {
|
||||
// Insert the default configuration if it does not exist yet.
|
||||
if try !exists(db) {
|
||||
try AppConfiguration.default.insert(db)
|
||||
@@ -242,7 +242,7 @@ extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
|
||||
/// Returns the persisted configuration, or the default one if the
|
||||
/// database table is empty.
|
||||
static func find(_ db: DatabaseBase<some SQLiteAPI>) throws -> AppConfiguration {
|
||||
static func find(_ db: Database) throws -> AppConfiguration {
|
||||
try fetchOne(db) ?? .default
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ How to best integrate GRDB and Swift Concurrency
|
||||
|
||||
## Overview
|
||||
|
||||
**This guide describes the relationship between GRDB and Swift 6 Concurrency.** It complements the <doc:Concurrency> guide, that you should read first.
|
||||
|
||||
GRDB’s primary goal is to leverage SQLite’s concurrency features for the benefit of application developers. Swift 6 makes it possible to achieve this goal while ensuring data-race safety.
|
||||
|
||||
For example, the ``DatabasePool`` connection allows applications to fetch and display database values on screen, even while a background task is writing the results of a network request to disk.
|
||||
@@ -55,7 +57,7 @@ let count = try await writer.read { db in
|
||||
}
|
||||
|
||||
// Shorthand notation:
|
||||
// ⚠️ Converting non-sendable function value to '@Sendable (DatabaseBase<some SQLiteAPI>)
|
||||
// ⚠️ Converting non-sendable function value to '@Sendable (Database)
|
||||
// throws -> Int' may introduce data races.
|
||||
let count = try await writer.read(Player.fetchCount)
|
||||
```
|
||||
@@ -91,14 +93,8 @@ extension Player: FetchableRecord, PersistableRecord {
|
||||
// because non-'Sendable' type '[any SQLSelectable]'
|
||||
// may have shared mutable state
|
||||
static let databaseSelection: [any SQLSelectable] = [
|
||||
Columns.id, Columns.name, Columns.score
|
||||
Column("id"), Column("name"), Column("score")
|
||||
]
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
static let score = Column("score")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -107,7 +103,7 @@ extension Player: FetchableRecord, PersistableRecord {
|
||||
```swift
|
||||
extension Player: FetchableRecord, PersistableRecord {
|
||||
static var databaseSelection: [any SQLSelectable] {
|
||||
[Columns.id, Columns.name, Columns.score]
|
||||
[Column("id"), Column("name"), Column("score")]
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -229,11 +225,5 @@ Task {
|
||||
}
|
||||
```
|
||||
|
||||
## Topics
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``GRDBSendableMetatype``
|
||||
|
||||
[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
|
||||
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide/
|
||||
@@ -160,7 +160,7 @@ This restriction can be left with the ``Configuration/allowsUnsafeTransactions``
|
||||
It is possible to ask if a transaction is currently opened:
|
||||
|
||||
```swift
|
||||
func myCriticalMethod(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
func myCriticalMethod(_ db: Database) throws {
|
||||
precondition(db.isInsideTransaction, "This method requires a transaction")
|
||||
try ...
|
||||
}
|
||||
@@ -169,7 +169,7 @@ func myCriticalMethod(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
Yet, there is a better option than checking for transactions. Critical database sections should use savepoints, described below:
|
||||
|
||||
```swift
|
||||
func myCriticalMethod(_ db: DatabaseBase<some SQLiteAPI>) throws {
|
||||
func myCriticalMethod(_ db: Database) throws {
|
||||
try db.inSavepoint {
|
||||
// Here the database is guaranteed to be inside a transaction.
|
||||
try ...
|
||||
|
||||
@@ -1,383 +0,0 @@
|
||||
# View Records
|
||||
|
||||
Define record types that target database views.
|
||||
|
||||
## Overview
|
||||
|
||||
A record type targets a [database view] as soon as its ``TableRecord/databaseTableName-3tcw2`` is the name of a view.
|
||||
|
||||
With such a record, some GRDB features will work out of the box, and some will throw errors without extra configuration:
|
||||
|
||||
```swift
|
||||
// OK: Works out of the box
|
||||
let captains = try Captain.fetchAll(db)
|
||||
let captainCount = try Captain.fetchCount(db)
|
||||
|
||||
// KO: Requires extra configuration
|
||||
// SQLite error 1: database view captain has no primary key
|
||||
var bob = try Captain.find(db, id: "bob")
|
||||
bob.name = "Bobby"
|
||||
// SQLite error 1: cannot modify captain because it is a view
|
||||
try bob.update(db)
|
||||
```
|
||||
|
||||
This article explains how to solve those errors:
|
||||
|
||||
- How to provide a primary key to a view.
|
||||
- How to define INSTEAD OF triggers that insert, update, and delete through a database view.
|
||||
|
||||
> important: GRDB is impacted by some SQLite limitations regarding INSTEAD OF triggers:
|
||||
>
|
||||
> - **Auto-incremented primary keys are not supported.** To be precise, SQLite won't expose the rowid of rows inserted via an INSTEAD OF trigger, so GRDB won't know the id of newly inserted rows. This has various nefarious consequences—see for example the important notice in the ``MutablePersistableRecord/didInsert(_:)`` callback. For more information, check this [SQLite forum thread](https://sqlite.org/forum/forumpost/707e7ed932).
|
||||
> - **INSTEAD OF triggers and the RETURNING clause do not play well together.** Those are SQLite bugs. All GRDB record methods with `andFetch` in their name may return unexpected or wrong results, depending on the SQLite version. For example, the SQLite version that ships with iOS 18 has bugs, and even more in iOS 17. If you intend to use the `RETURNING` clause, it is recommended that you write tests and run them in various target operation systems.
|
||||
|
||||
## Preliminary Setup
|
||||
|
||||
To support this documentation, we need a database that contains a view. The sample code below uses <doc:Migrations> and <doc:DatabaseSchemaModifications> methods.
|
||||
|
||||
The database schema contains teams and players. Some players are the captain of their team. We enforce in the database schema that a given team can't have multiple captains:
|
||||
|
||||
```swift
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("Teams and players") { db in
|
||||
try db.create(table: "team") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
t.belongsTo("team", onDelete: .setNull)
|
||||
t.column("isCaptain", .boolean).notNull()
|
||||
}
|
||||
|
||||
// One unique captain per team
|
||||
try db.create(
|
||||
indexOn: "player", columns: ["teamId"],
|
||||
options: .unique,
|
||||
condition: Column("isCaptain"))
|
||||
}
|
||||
```
|
||||
|
||||
We define record types for the `team` and `player` tables, as described in <doc:RecordRecommendedPractices>:
|
||||
|
||||
```swift
|
||||
struct Team: Codable, Identifiable, FetchableRecord, PersistableRecord {
|
||||
var id: String
|
||||
var name: String
|
||||
}
|
||||
|
||||
struct Player: Codable, Identifiable, FetchableRecord, PersistableRecord {
|
||||
var id: String
|
||||
var name: String
|
||||
var teamId: String?
|
||||
var isCaptain: Bool
|
||||
}
|
||||
```
|
||||
|
||||
Let's define a view and a record type for captains. At this point, both the view and the record are read-only:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Read-only captains") { db in
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW captain AS
|
||||
SELECT id, name, teamId
|
||||
FROM player
|
||||
WHERE isCaptain AND teamId IS NOT NULL;
|
||||
""")
|
||||
}
|
||||
|
||||
struct Captain: Decodable, Identifiable, FetchableRecord {
|
||||
var id: String
|
||||
var name: String
|
||||
var teamId: String
|
||||
}
|
||||
```
|
||||
|
||||
✅ From now on, we can use the `Captain` record:
|
||||
|
||||
```swift
|
||||
let dbQueue = try DatabaseQueue()
|
||||
try migrator.migrate(dbQueue)
|
||||
try dbQueue.write { db in
|
||||
try Team(id: "red", name: "Red").insert(db)
|
||||
try Team(id: "blue", name: "Blue").insert(db)
|
||||
try Player(id: "alice", name: "Alice", teamId: "red", isCaptain: true).insert(db)
|
||||
try Player(id: "bob", name: "Bob", teamId: "blue", isCaptain: true).insert(db)
|
||||
try Player(id: "craig", name: "Craig", teamId: "blue", isCaptain: false).insert(db)
|
||||
|
||||
let captains = try Captain.fetchAll(db)
|
||||
// Prints:
|
||||
// Captain(id: "alice", name: "Alice", teamId: "red")
|
||||
// Captain(id: "bob", name: "Bob", teamId: "blue")
|
||||
print(captains)
|
||||
}
|
||||
```
|
||||
|
||||
## Specifying the primary key of a view
|
||||
|
||||
SQLite views do not have any primary key, so GRDB cannot introspect the database schema and automatically find the eventual primary key.
|
||||
|
||||
To instruct GRDB about the primary key, define a **schema source**, a type that conforms to ``DatabaseSchemaSource``. In this sample code, the schema only contains the "captain" view, so our schema source does not need to be very complicated. Check the documentation of the protocol for more detailed instructions:
|
||||
|
||||
```swift
|
||||
struct GameSchemaSource: DatabaseSchemaSource {
|
||||
/// Returns the names of the columns for the primary key in the
|
||||
/// provided database view.
|
||||
func columnsForPrimaryKey(_ db: DatabaseBase<some SQLiteAPI>, inView view: DatabaseObjectID) throws -> [String]? {
|
||||
["id"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
We configure the database connection with this schema source:
|
||||
|
||||
```swift
|
||||
var config = Configuration()
|
||||
config.schemaSource = GameSchemaSource()
|
||||
let dbQueue = try DatabaseQueue(configuration: config)
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
✅ We can now use the primary key of captains:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
// [Insert some teams and players...]
|
||||
let captains = try Captain.orderByPrimaryKey().fetchAll(db)
|
||||
let alice = try Captain.find(db, id: "alice")
|
||||
}
|
||||
```
|
||||
|
||||
## Associations between views
|
||||
|
||||
To define [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) between record types that target database views, the foreign key must be explicitly provided. We define the foreign key from `captain` to `team` with a column declared as recommended in <doc:RecordRecommendedPractices>:
|
||||
|
||||
```swift
|
||||
extension Captain {
|
||||
// Time to define some columns
|
||||
enum Columns {
|
||||
static let teamId = Column(CodingKeys.teamId)
|
||||
}
|
||||
|
||||
// The captain view has a foreign key to teams,
|
||||
// from the teamId column to the team primary key.
|
||||
// SQLite does not know about it, so we declare it explicitly:
|
||||
static let teamForeignKey = ForeignKey([Columns.teamId])
|
||||
|
||||
// A captain belongs to a team.
|
||||
static let team = belongsTo(Team.self, using: teamForeignKey)
|
||||
}
|
||||
|
||||
extension Team {
|
||||
// A team has a captain.
|
||||
static let captain = hasOne(Captain.self, using: Captain.teamForeignKey)
|
||||
}
|
||||
```
|
||||
|
||||
✅ We can now use those associations:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
// All teams with a captain
|
||||
let teamsWithCaptain: [Team] = try Team
|
||||
.joining(required: Team.captain)
|
||||
.fetchAll(db)
|
||||
|
||||
// All (captain, team) pairs
|
||||
struct CaptainWithTeam: Decodable, FetchableRecord {
|
||||
var captain: Captain
|
||||
var team: Team
|
||||
}
|
||||
let captainsWithTeam: [CaptainWithTeam] = try Captain
|
||||
.including(required: Captain.team)
|
||||
.asRequest(of: CaptainWithTeam.self)
|
||||
.fetchAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
## Inserting rows into a view
|
||||
|
||||
SQLite views are read-only unless we define an [INSTEAD OF trigger] that specifies which statements to run when we insert a row into a view.
|
||||
|
||||
INSTEAD OF triggers are very versatile, and applications can define the behavior that best fits their needs. In our sample code, inserting a captain will insert a player with the `isCaptain` flag set, and we'll also remove the `isCaptain` flag of the previous captain, if any:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Captain insert") { db in
|
||||
try db.execute(sql: """
|
||||
-- Insert trigger
|
||||
CREATE TRIGGER captain_insert
|
||||
INSTEAD OF INSERT ON captain
|
||||
BEGIN
|
||||
-- Remove previous captain
|
||||
UPDATE player SET isCaptain = 0
|
||||
WHERE teamId = NEW.teamId AND isCaptain;
|
||||
|
||||
-- Insert new captain
|
||||
INSERT INTO player(id, name, teamId, isCaptain)
|
||||
VALUES (NEW.id, NEW.name, NEW.teamId, 1);
|
||||
END;
|
||||
""")
|
||||
}
|
||||
|
||||
// Apply the new migration
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
Let's also give an `insert()` method to the Captain record, with the ``PersistableRecord`` protocol:
|
||||
|
||||
```swift
|
||||
extension Captain: Encodable, PersistableRecord { }
|
||||
```
|
||||
|
||||
- note: Remember that auto-incremented primary keys are not supported, as described at the beginning of this article. Our captain view is backed by the player table which has a string primary key, so we're fine.
|
||||
|
||||
✅ We can directly insert captains:
|
||||
|
||||
```swift
|
||||
try dbQueue.write {
|
||||
try Team(id: "green", name: "Green").insert(db)
|
||||
// Diane is the captain
|
||||
try Captain(id: "diane", name: "Diane", teamId: "green").insert(db)
|
||||
// Well, no: Eugene is the captain
|
||||
try Captain(id: "eugene", name: "Eugene", teamId: "green").insert(db)
|
||||
|
||||
// Prints:
|
||||
// team player captain
|
||||
// green|Green diane|Diane|green|0 eugene|Eugene|green
|
||||
// eugene|Eugene|green|1
|
||||
try db.dumpTables(["team", "player", "captain"])
|
||||
}
|
||||
```
|
||||
|
||||
## Updating rows in a view
|
||||
|
||||
Just like for inserts, an INSTEAD OF trigger can specify how to update rows in a view.
|
||||
|
||||
In our sample code, updating a captain will update the player with the same id, and remove the `isCaptain` flag from the previous captain of the team, if any:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Captain update") { db in
|
||||
try db.execute(sql: """
|
||||
-- Update trigger
|
||||
CREATE TRIGGER captain_update
|
||||
INSTEAD OF UPDATE ON captain
|
||||
BEGIN
|
||||
-- Remove previous captain
|
||||
UPDATE player SET isCaptain = 0
|
||||
WHERE teamId = NEW.teamId AND isCaptain AND id <> NEW.id;
|
||||
|
||||
-- Update captain
|
||||
UPDATE player SET name = NEW.name, teamId = NEW.teamId, isCaptain = 1
|
||||
WHERE id = NEW.id;
|
||||
END;
|
||||
""")
|
||||
}
|
||||
|
||||
// Apply the new migration
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
✅ Let's update captains:
|
||||
|
||||
```swift
|
||||
try dbQueue.write {
|
||||
try Team(id: "red", name: "Red").insert(db)
|
||||
try Team(id: "blue", name: "Blue").insert(db)
|
||||
try Captain(id: "alice", name: "Alice", teamId: "red").insert(db)
|
||||
|
||||
// Bob is the Blue captain.
|
||||
var bob = Captain(id: "bob", name: "Bob", teamId: "blue")
|
||||
try bob.insert(db)
|
||||
|
||||
// Bob is now Bobby, the Red captain.
|
||||
// Alice is no longer the Red captain.
|
||||
try bob.updateChanges(db) {
|
||||
$0.name = "Bobby"
|
||||
$0.teamId = "red"
|
||||
}
|
||||
|
||||
// Prints:
|
||||
// team player captain
|
||||
// blue|Blue alice|Alice|red|0 bob|Bobby|red
|
||||
// red|Red bob|Bobby|red|1
|
||||
try db.dumpTables(["team", "player", "captain"])
|
||||
}
|
||||
```
|
||||
|
||||
## Deleting rows from a view
|
||||
|
||||
The last missing INSTEAD OF trigger deals with deletes:
|
||||
|
||||
```swift
|
||||
migrator.registerMigration("Captain delete") { db in
|
||||
try db.execute(sql: """
|
||||
-- Delete trigger
|
||||
CREATE TRIGGER captain_delete
|
||||
INSTEAD OF DELETE ON captain
|
||||
BEGIN
|
||||
DELETE FROM player WHERE id = OLD.id;
|
||||
END;
|
||||
""")
|
||||
}
|
||||
|
||||
// Apply the new migration
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
✅ Let's delete some captains:
|
||||
|
||||
```swift
|
||||
try dbQueue.write {
|
||||
// Delete Alice
|
||||
try Captain.deleteOne(db, id: "alice")
|
||||
|
||||
// Delete Bob
|
||||
let bob = try Captain.find(db, id: "bob")
|
||||
try bob.delete(db)
|
||||
|
||||
// Delete all captains
|
||||
try Captain.deleteAll()
|
||||
}
|
||||
```
|
||||
|
||||
## Going further
|
||||
|
||||
To exercise the techniques described here, try to define record types for these other views:
|
||||
|
||||
- The `enrolledPlayer` view that only contains players that belong to a team:
|
||||
|
||||
```swift
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW enrolledPlayer AS
|
||||
SELECT id, name, teamId, isCaptain
|
||||
FROM player
|
||||
WHERE teamId IS NOT NULL;
|
||||
""")
|
||||
```
|
||||
|
||||
- The `teamWithCaptainId` view that contains a `captainId` column:
|
||||
|
||||
```swift
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW teamWithCaptainId AS
|
||||
SELECT team.id, team.name, player.id AS captainId
|
||||
FROM team
|
||||
JOIN player ON player.teamId = team.id AND player.isCaptain;
|
||||
""")
|
||||
```
|
||||
|
||||
- A refactored `captain` view whose primary key is the team id—this is valid, since the schema enforces that there's a single captain for each team:
|
||||
|
||||
```swift
|
||||
try db.execute(sql: """
|
||||
CREATE VIEW captain AS
|
||||
SELECT teamId, name
|
||||
FROM player
|
||||
WHERE isCaptain AND teamId IS NOT NULL;
|
||||
""")
|
||||
```
|
||||
|
||||
[database view]: https://www.sqlite.org/lang_createview.html
|
||||
[INSTEAD OF trigger]: https://sqlite.org/lang_createtrigger.html#instead_of_triggers
|
||||
@@ -2,7 +2,7 @@ import Foundation
|
||||
|
||||
// MARK: - Dump
|
||||
|
||||
extension DatabaseBase {
|
||||
extension Database {
|
||||
/// Prints the results of all statements in the provided SQL.
|
||||
///
|
||||
/// For example:
|
||||
@@ -183,7 +183,7 @@ extension DatabaseBase {
|
||||
|
||||
// MARK: -
|
||||
|
||||
extension DatabaseBase {
|
||||
extension Database {
|
||||
func _dumpStatements(
|
||||
_ statements: some Cursor<Statement>,
|
||||
format: some DumpFormat,
|
||||
@@ -317,16 +317,16 @@ extension DatabaseBase {
|
||||
}
|
||||
|
||||
private func ignoresObject(named name: String) throws -> Bool {
|
||||
if Self.isSQLiteInternalTable(name) { return true }
|
||||
if Self.isGRDBInternalTable(name) { return true }
|
||||
if Database.isSQLiteInternalTable(name) { return true }
|
||||
if Database.isGRDBInternalTable(name) { return true }
|
||||
if try isShadowTable(name) { return true }
|
||||
return false
|
||||
}
|
||||
|
||||
private func isShadowTable(_ tableName: String) throws -> Bool {
|
||||
#if GRDBCUSTOMSQLITE || SQLITE_HAS_CODEC
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Maybe SQLCipher is too old: check actual version
|
||||
if Database.sqliteLibVersionNumber >= 3037000 {
|
||||
if sqlite3_libversion_number() >= 3037000 {
|
||||
guard let table = try table(tableName) else {
|
||||
// Not a table
|
||||
return false
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
extension DatabaseReaderBase {
|
||||
extension DatabaseReader {
|
||||
/// Prints the results of all statements in the provided SQL.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -33,28 +33,26 @@
|
||||
/// - ``writeRow(_:statement:to:)``
|
||||
/// - ``finalize(_:statement:to:)``
|
||||
public protocol DumpFormat {
|
||||
#warning("TODO: incompatible with GRDB 7")
|
||||
/// Writes a row from the given statement.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - db: A connection to the database
|
||||
/// - statement: The iterated statement
|
||||
/// - stream: A stream for text output.
|
||||
mutating func writeRow<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
statement: StatementBase<API>,
|
||||
mutating func writeRow(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream) throws
|
||||
|
||||
#warning("TODO: incompatible with GRDB 7")
|
||||
/// All rows from the statement have been printed.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - db: A connection to the database
|
||||
/// - statement: The statement that was iterated.
|
||||
/// - stream: A stream for text output.
|
||||
mutating func finalize<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
statement: StatementBase<API>,
|
||||
mutating func finalize(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -61,9 +58,9 @@ public struct DebugDumpFormat: Sendable {
|
||||
}
|
||||
|
||||
extension DebugDumpFormat: DumpFormat {
|
||||
public mutating func writeRow<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
statement: StatementBase<API>,
|
||||
public mutating func writeRow(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
if firstRow {
|
||||
@@ -91,15 +88,15 @@ extension DebugDumpFormat: DumpFormat {
|
||||
stream.write("\n")
|
||||
}
|
||||
|
||||
public mutating func finalize<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
statement: StatementBase<API>,
|
||||
public mutating func finalize(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
firstRow = true
|
||||
}
|
||||
|
||||
private func formattedValue(_ db: DatabaseBase<some SQLiteAPI>, in sqliteStatement: SQLiteStatement, at index: CInt) -> String {
|
||||
private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) -> String {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
return nullValue
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -80,9 +77,9 @@ public struct JSONDumpFormat: Sendable {
|
||||
}
|
||||
|
||||
extension JSONDumpFormat: DumpFormat {
|
||||
public mutating func writeRow<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
statement: StatementBase<API>,
|
||||
public mutating func writeRow(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
throws {
|
||||
if firstRow {
|
||||
@@ -127,9 +124,9 @@ extension JSONDumpFormat: DumpFormat {
|
||||
stream.write("}")
|
||||
}
|
||||
|
||||
public mutating func finalize<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
statement: StatementBase<API>,
|
||||
public mutating func finalize(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
if firstRow {
|
||||
@@ -145,7 +142,7 @@ extension JSONDumpFormat: DumpFormat {
|
||||
firstRow = true
|
||||
}
|
||||
|
||||
private func formattedValue(_ db: DatabaseBase<some SQLiteAPI>, in sqliteStatement: SQLiteStatement, at index: CInt) throws -> String {
|
||||
private func formattedValue(_ db: Database, in sqliteStatement: SQLiteStatement, at index: CInt) throws -> String {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
return "null"
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -43,9 +40,9 @@ public struct LineDumpFormat: Sendable {
|
||||
}
|
||||
|
||||
extension LineDumpFormat: DumpFormat {
|
||||
public mutating func writeRow<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
statement: StatementBase<API>,
|
||||
public mutating func writeRow(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
var lines: [(column: String, value: String)] = []
|
||||
@@ -76,9 +73,9 @@ extension LineDumpFormat: DumpFormat {
|
||||
}
|
||||
}
|
||||
|
||||
public mutating func finalize<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
statement: StatementBase<API>,
|
||||
public mutating func finalize(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
if firstRow == false {
|
||||
@@ -88,7 +85,7 @@ extension LineDumpFormat: DumpFormat {
|
||||
}
|
||||
|
||||
func formattedValue(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
in sqliteStatement: SQLiteStatement,
|
||||
at index: CInt)
|
||||
-> String
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
//// Import C SQLite functions
|
||||
//#if GRDBCIPHER // CocoaPods (SQLCipher subspec)
|
||||
//import SQLCipher
|
||||
//#elseif GRDBFRAMEWORK // GRDB.xcodeproj or CocoaPods (standard subspec)
|
||||
//import SQLite3
|
||||
//#elseif GRDBCUSTOMSQLITE // GRDBCustom Framework
|
||||
//// #elseif SomeTrait
|
||||
//// import ...
|
||||
//#else // Default SPM trait must be the default. It impossible to detect from Xcode.
|
||||
//import GRDBSQLite
|
||||
//#endif
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import Foundation
|
||||
|
||||
@@ -58,9 +55,9 @@ public struct ListDumpFormat: Sendable {
|
||||
}
|
||||
|
||||
extension ListDumpFormat: DumpFormat {
|
||||
public mutating func writeRow<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
statement: StatementBase<API>,
|
||||
public mutating func writeRow(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
if firstRow {
|
||||
@@ -88,16 +85,16 @@ extension ListDumpFormat: DumpFormat {
|
||||
stream.write("\n")
|
||||
}
|
||||
|
||||
public mutating func finalize<API>(
|
||||
_ db: DatabaseBase<API>,
|
||||
statement: StatementBase<API>,
|
||||
public mutating func finalize(
|
||||
_ db: Database,
|
||||
statement: Statement,
|
||||
to stream: inout DumpStream)
|
||||
{
|
||||
firstRow = true
|
||||
}
|
||||
|
||||
func formattedValue(
|
||||
_ db: DatabaseBase<some SQLiteAPI>,
|
||||
_ db: Database,
|
||||
in sqliteStatement: SQLiteStatement,
|
||||
at index: CInt)
|
||||
-> String
|
||||
|
||||
Loaded 100 of 312 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user