mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
121
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63590ede60 | ||
|
|
6eba24d169 | ||
|
|
bd3ac9ef75 | ||
|
|
392137c357 | ||
|
|
b48a56ae03 | ||
|
|
bbd1eab402 | ||
|
|
53c9d12d29 | ||
|
|
9b09c5342e | ||
|
|
aed22fe0bc | ||
|
|
eec220b652 | ||
|
|
79a782038e | ||
|
|
618e72d153 | ||
|
|
824100990f | ||
|
|
c7205b172f | ||
|
|
49d14e6b66 | ||
|
|
54ed7ec611 | ||
|
|
68e17351ff | ||
|
|
494e697e94 | ||
|
|
87b236dfe0 | ||
|
|
ea6d8e0123 | ||
|
|
073209f1dc | ||
|
|
430530f5f1 | ||
|
|
a716915280 | ||
|
|
ef36727d9a | ||
|
|
78b2796f46 | ||
|
|
3535a42c53 | ||
|
|
5a4d9b5cb9 | ||
|
|
a64b09d121 | ||
|
|
287c4be82d | ||
|
|
32c9ba24ba | ||
|
|
0401d449bb | ||
|
|
4de97e6903 | ||
|
|
676636bae4 | ||
|
|
8e7cbf098f | ||
|
|
7250d759fe | ||
|
|
fe7b9955b1 | ||
|
|
6df8e2bd34 | ||
|
|
81cd33b71c | ||
|
|
2e2c0eaec1 | ||
|
|
ed17710694 | ||
|
|
0f68d8b684 | ||
|
|
367f8f7e37 | ||
|
|
831e79ee82 | ||
|
|
8b3f9c0936 | ||
|
|
950db13d46 | ||
|
|
0e664cf22e | ||
|
|
1e5602ca9d | ||
|
|
8147811ab4 | ||
|
|
4c9b0eb90e | ||
|
|
b63d75da21 | ||
|
|
5a3db29e21 | ||
|
|
fa0985eb01 | ||
|
|
495e76bb1a | ||
|
|
bbf39353b5 | ||
|
|
442b8b0589 | ||
|
|
2c85bc2cfc | ||
|
|
3f56bc8199 | ||
|
|
37ea21eb96 | ||
|
|
96c9eb5699 | ||
|
|
33103bb373 | ||
|
|
6b23181337 | ||
|
|
c5366f4a01 | ||
|
|
a642ac51aa | ||
|
|
d03208b33a | ||
|
|
a4132a00db | ||
|
|
61c7fdf81b | ||
|
|
ec40855466 | ||
|
|
1cca3686f5 | ||
|
|
1e354ba79c | ||
|
|
0ea5471b56 | ||
|
|
b2e808b9e4 | ||
|
|
ac0c085a4a | ||
|
|
9f9f0d37dd | ||
|
|
898e7b6abe | ||
|
|
0fb599812f | ||
|
|
77a4d17940 | ||
|
|
c865a847fd | ||
|
|
832bc1aa74 | ||
|
|
910ca2d0ce | ||
|
|
3ecb5c5455 | ||
|
|
84d25dfc9d | ||
|
|
5664c5a829 | ||
|
|
334a63aa4a | ||
|
|
7e506f6488 | ||
|
|
5341f139e5 | ||
|
|
917b7ecc90 | ||
|
|
c396fc20be | ||
|
|
73083c4f1b | ||
|
|
2c12f0a5e6 | ||
|
|
c97f633022 | ||
|
|
4315030af5 | ||
|
|
13b6c9d36b | ||
|
|
8aaeb253d2 | ||
|
|
a741fb38f0 | ||
|
|
2c49a69f43 | ||
|
|
d6b50b2c54 | ||
|
|
ad983f7971 | ||
|
|
7cd075bbdc | ||
|
|
0aa8498620 | ||
|
|
bccf312af6 | ||
|
|
5b4a86b5f7 | ||
|
|
68d12916e6 | ||
|
|
6a4f454464 | ||
|
|
a9fa2871aa | ||
|
|
8c5396898a | ||
|
|
dd14710c86 | ||
|
|
97c0c72702 | ||
|
|
a17d72e04c | ||
|
|
761b00f9bc | ||
|
|
ac3278a38b | ||
|
|
06c3ab0d16 | ||
|
|
f38619ada8 | ||
|
|
8cac458efc | ||
|
|
a13c1bec29 | ||
|
|
c6781f46d2 | ||
|
|
fd04831586 | ||
|
|
d7754fa79c | ||
|
|
5f2185a118 | ||
|
|
dc03b8a29e | ||
|
|
a0c1de55c4 | ||
|
|
d1f5a37520 |
No files matched your search
@@ -46,11 +46,11 @@ jobs:
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.1,name=iPhone 15 Pro"
|
||||
destination: "OS=18.1,name=iPhone 16 Pro"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_16.1.app"
|
||||
runsOn: macOS-14
|
||||
destination: "OS=18.0,name=Apple TV"
|
||||
destination: "OS=18.1,name=Apple TV"
|
||||
name: "tvOS"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
+101
-30
@@ -7,7 +7,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 7.x Releases
|
||||
|
||||
- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2)
|
||||
- `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)
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
@@ -131,11 +135,78 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
|
||||
- **New**: Bump custom SQLite builds to 3.46.1 by [@groue](https://github.com/groue) in [#1654](https://github.com/groue/GRDB.swift/pull/1654)
|
||||
|
||||
## 7.0.0-beta.5
|
||||
|
||||
Released October 13, 2024
|
||||
|
||||
- **Fixed**: Fix DatabaseMigrator.hasSchemaChanges failing for readonly connections by [@Jnosh](https://github.com/Jnosh) in [#1653](https://github.com/groue/GRDB.swift/pull/1653)
|
||||
- **Documentation Update**: Enhance the database schema documentation by [@groue](https://github.com/groue) in [#1652](https://github.com/groue/GRDB.swift/pull/1652)
|
||||
|
||||
## 7.0.0-beta.4
|
||||
|
||||
Released October 12, 2024
|
||||
|
||||
- **New**: Allow applications to handle DatabaseMigrator schema changes by [@groue](https://github.com/groue) in [#1651](https://github.com/groue/GRDB.swift/pull/1651)
|
||||
|
||||
## 7.0.0-beta.3
|
||||
|
||||
Released October 6, 2024
|
||||
|
||||
- **Fix**: use #if directives to conditionally @preconcurrency import the Dispatch module to enable building the package on linux by [@tayloraswift](https://github.com/tayloraswift) in [#1644](https://github.com/groue/GRDB.swift/pull/1644)
|
||||
- **New**: Add coalesce free function and Row method by [@philmitchell](https://github.com/philmitchell) in [#1645](https://github.com/groue/GRDB.swift/pull/1645)
|
||||
- **Documentation Update**: Add `DatabaseValueConvertible` tip for JSON columns by [@bok-](https://github.com/bok-) in [#1649](https://github.com/groue/GRDB.swift/pull/1649)
|
||||
|
||||
## 7.0.0-beta.2
|
||||
|
||||
Released September 29, 2024
|
||||
|
||||
- **Fix** Update .spi.yml by [@finestructure](https://github.com/finestructure) in [#1643](https://github.com/groue/GRDB.swift/pull/1643)
|
||||
- **Fix**: Update .spi.yml by [@finestructure](https://github.com/finestructure) in [#1643](https://github.com/groue/GRDB.swift/pull/1643)
|
||||
|
||||
## 7.0.0-beta
|
||||
|
||||
@@ -145,7 +216,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/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.
|
||||
|
||||
@@ -204,8 +275,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
|
||||
|
||||
@@ -230,7 +301,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
|
||||
@@ -257,7 +328,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
|
||||
|
||||
@@ -293,8 +364,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
|
||||
|
||||
@@ -318,14 +389,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
|
||||
@@ -342,7 +413,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
|
||||
@@ -377,7 +448,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
|
||||
@@ -404,8 +475,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
|
||||
|
||||
@@ -414,9 +485,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
|
||||
|
||||
@@ -424,7 +495,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
|
||||
|
||||
@@ -435,7 +506,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
|
||||
@@ -465,11 +536,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
|
||||
|
||||
@@ -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).
|
||||
@@ -130,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
|
||||
@@ -2963,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
|
||||
@@ -2998,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
|
||||
|
||||
+10
-10
@@ -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:
|
||||
|
||||
@@ -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
|
||||
@@ -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).
|
||||
@@ -3,9 +3,9 @@ Custom SQLite Builds
|
||||
|
||||
By default, GRDB uses the version of SQLite that ships with the target operating system.
|
||||
|
||||
**You can build GRDB with a custom build of [SQLite 3.44.0](https://www.sqlite.org/changes.html).**
|
||||
**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.
|
||||
|
||||
@@ -21,7 +21,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import os.log
|
||||
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 @@ final class 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()
|
||||
@@ -67,20 +67,17 @@ extension AppDatabase {
|
||||
|
||||
/// Returns a database configuration suited for `AppDatabase`.
|
||||
///
|
||||
/// SQL statements are logged if the `SQL_TRACE` environment variable
|
||||
/// is set.
|
||||
///
|
||||
/// - parameter base: A base configuration.
|
||||
static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
|
||||
var config = base
|
||||
|
||||
/// - parameter config: A base configuration.
|
||||
static func makeConfiguration(_ config: Configuration = Configuration()) -> Configuration {
|
||||
// var config = config
|
||||
//
|
||||
// Add custom SQL functions or collations, if needed:
|
||||
// config.prepareDatabase { db in
|
||||
// db.add(function: ...)
|
||||
// }
|
||||
|
||||
//
|
||||
// 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
|
||||
@@ -96,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
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@ private typealias Columns = Player.Columns
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
/// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices>
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -6,41 +6,36 @@ struct PlayerListModelTests {
|
||||
// MARK: - PlayerListModel.observePlayers tests
|
||||
|
||||
@Test(.timeLimit(.minutes(1)))
|
||||
@MainActor func observation_started_after_player_creation() async throws {
|
||||
// Given a PlayerListModel on a database that contains a player
|
||||
@MainActor func observation_grabs_current_database_state() async throws {
|
||||
// Given a PlayerListModel on a database that contains one player
|
||||
let appDatabase = try makeEmptyTestDatabase()
|
||||
var player = Player(name: "Arthur", score: 1000)
|
||||
try appDatabase.savePlayer(&player)
|
||||
let model = PlayerListModel(appDatabase: appDatabase)
|
||||
|
||||
// When we start observing the database
|
||||
// When the model starts observing the database
|
||||
model.observePlayers()
|
||||
|
||||
// Then the model eventually fetches the player.
|
||||
// We poll because we do not know when the model will update its players.
|
||||
await pollUntil {
|
||||
model.players.isEmpty == false
|
||||
}
|
||||
#expect(model.players == [player])
|
||||
// Then the model eventually has one player.
|
||||
try await pollUntil { model.players.count == 1 }
|
||||
}
|
||||
|
||||
@Test(.timeLimit(.minutes(1)))
|
||||
@MainActor func observation_started_before_player_creation() async throws {
|
||||
// Given a PlayerListModel that observes a empty database
|
||||
@MainActor func observation_grabs_database_changes() async throws {
|
||||
// Given a PlayerListModel that has one player
|
||||
let appDatabase = try makeEmptyTestDatabase()
|
||||
var player1 = Player(name: "Arthur", score: 1000)
|
||||
try appDatabase.savePlayer(&player1)
|
||||
let model = PlayerListModel(appDatabase: appDatabase)
|
||||
model.observePlayers()
|
||||
try await pollUntil { model.players.count == 1 }
|
||||
|
||||
// When we insert a player
|
||||
var player = Player(name: "Arthur", score: 1000)
|
||||
try appDatabase.savePlayer(&player)
|
||||
// When we insert a second player
|
||||
var player2 = Player(name: "Barbara", score: 800)
|
||||
try appDatabase.savePlayer(&player2)
|
||||
|
||||
// Then the model eventually fetches the player.
|
||||
// We poll because we do not know when the model will update its players.
|
||||
await pollUntil {
|
||||
model.players.isEmpty == false
|
||||
}
|
||||
#expect(model.players == [player])
|
||||
// Then the model eventually has two players.
|
||||
try await pollUntil { model.players.count == 2 }
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -68,14 +63,14 @@ struct PlayerListModelTests {
|
||||
}
|
||||
|
||||
/// Convenience method that loops until a condition is met.
|
||||
private func pollUntil(condition: @escaping @MainActor () async -> Bool) async {
|
||||
await confirmation { confirmation in
|
||||
private func pollUntil(condition: @escaping @MainActor () async -> Bool) async throws {
|
||||
try await confirmation { confirmation in
|
||||
while true {
|
||||
if await condition() {
|
||||
confirmation()
|
||||
return
|
||||
} else {
|
||||
await Task.yield()
|
||||
try await Task.sleep(for: .seconds(0.01))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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).
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ FTS5 Tokenizers
|
||||
|
||||
**[FTS5](https://www.sqlite.org/fts5.html) is an extensible full-text search engine.**
|
||||
|
||||
GRDB lets you define your own custom FST5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are:
|
||||
GRDB lets you define your own custom FTS5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are:
|
||||
|
||||
- Have "fi" match the ligature "fi" (U+FB01)
|
||||
- Have "first" match "1st"
|
||||
@@ -95,7 +95,7 @@ let documents = try Document.matching(pattern).fetchAll(db)
|
||||
|
||||
## FTS5Tokenizer
|
||||
|
||||
**FST5Tokenizer** is the protocol for all FTS5 tokenizers.
|
||||
**FTS5Tokenizer** is the protocol for all FTS5 tokenizers.
|
||||
|
||||
It only requires a tokenization method that matches the low-level `xTokenize` C function documented at https://www.sqlite.org/fts5.html#custom_tokenizers. We'll discuss it more when describing custom tokenizers.
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -82,7 +82,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
|
||||
|
||||
- **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables.
|
||||
|
||||
- See [FST3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
|
||||
- See [FTS3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
|
||||
|
||||
> **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).
|
||||
|
||||
@@ -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:using:)` method:
|
||||
Create tables with the `create(virtualTable:options: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,
|
||||
@@ -326,7 +326,7 @@ let documents = try Document.filter(Column("content").match(pattern)).fetchAll(d
|
||||
|
||||
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:using:)` method:
|
||||
Create FTS5 tables with the `create(virtualTable:options: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,
|
||||
@@ -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
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ 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)
|
||||
@@ -96,6 +97,53 @@ 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:
|
||||
@@ -114,7 +162,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:
|
||||
|
||||
@@ -221,14 +269,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/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
|
||||
@@ -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).
|
||||
@@ -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
|
||||
|
||||
@@ -497,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"))
|
||||
```
|
||||
|
||||
@@ -505,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"))
|
||||
@@ -607,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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '7.0.0-beta.2'
|
||||
s.version = '7.3.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -7,6 +7,9 @@ import SQLCipher
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
#if !canImport(Darwin)
|
||||
@preconcurrency
|
||||
#endif
|
||||
import Dispatch
|
||||
import Foundation
|
||||
|
||||
|
||||
+138
-21
@@ -96,7 +96,15 @@ extension Database {
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
/// Returns the current schema version.
|
||||
/// Returns the current schema version (`PRAGMA schema_version`).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let version = try dbQueue.read { db in
|
||||
/// try db.schemaVersion()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_schema_version>
|
||||
public func schemaVersion() throws -> Int32 {
|
||||
@@ -234,8 +242,19 @@ extension Database {
|
||||
|
||||
/// Returns whether a table exists
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
/// When `schemaName` is not specified, the result is true if any known
|
||||
/// schema contains the table.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// if try db.tableExists("player") { ... }
|
||||
/// if try db.tableExists("player", in: "main") { ... }
|
||||
/// if try db.tableExists("player", in: "temp") { ... }
|
||||
/// if try db.tableExists("player", in: "attached") { ... }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if the specified schema does not exist
|
||||
@@ -278,8 +297,19 @@ extension Database {
|
||||
/// Returns whether a view exists, in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
/// When `schemaName` is not specified, the result is true if any known
|
||||
/// schema contains the table.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// if try db.viewExists("player") { ... }
|
||||
/// if try db.viewExists("player", in: "main") { ... }
|
||||
/// if try db.viewExists("player", in: "temp") { ... }
|
||||
/// if try db.viewExists("player", in: "attached") { ... }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if the specified schema does not exist
|
||||
@@ -296,8 +326,19 @@ extension Database {
|
||||
/// Returns whether a trigger exists, in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
/// When `schemaName` is not specified, the result is true if any known
|
||||
/// schema contains the table.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// if try db.triggerExists("on_player_update") { ... }
|
||||
/// if try db.triggerExists("on_player_update", in: "main") { ... }
|
||||
/// if try db.triggerExists("on_player_update", in: "temp") { ... }
|
||||
/// if try db.triggerExists("on_player_update", in: "attached") { ... }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
|
||||
/// if the specified schema does not exist
|
||||
@@ -340,6 +381,15 @@ extension Database {
|
||||
/// table has no explicit primary key, the result is the hidden
|
||||
/// "rowid" column.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let primaryKey = try db.primaryKey("player")
|
||||
/// print(primaryKey.columns)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
@@ -359,6 +409,36 @@ extension Database {
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns the name of the single-column primary key.
|
||||
///
|
||||
/// A fatal error is raised if the primary key has several columns, or
|
||||
/// if `tableName` is the name of a database view.
|
||||
func filteringPrimaryKeyColumn(_ tableName: String) throws -> String {
|
||||
do {
|
||||
let primaryKey = try primaryKey(tableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"Filtering by primary key requires a single-column primary key in the table '\(tableName)'")
|
||||
return primaryKey.columns[0]
|
||||
} catch let error as DatabaseError {
|
||||
// Maybe the user tries to filter a view by primary key,
|
||||
// as in <https://github.com/groue/GRDB.swift/issues/1648>.
|
||||
// In this case, raise a fatalError because this is a
|
||||
// programmer error which is very likely to be detected
|
||||
// during development.
|
||||
if case .SQLITE_ERROR = error.resultCode,
|
||||
(try? viewExists(tableName)) == true
|
||||
{
|
||||
fatalError("""
|
||||
Filtering by primary key is not available on the database view '\(tableName)'. \
|
||||
Use `filter(Column("...") == value)` instead.
|
||||
""")
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns nil if table does not exist
|
||||
private func primaryKey(_ table: TableIdentifier) throws -> PrimaryKeyInfo? {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
@@ -499,14 +579,26 @@ extension Database {
|
||||
|
||||
/// The indexes on table named `tableName`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let indexes = db.indexes(in: "player")
|
||||
/// for index in indexes {
|
||||
/// print(index.columns)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Only indexes on columns are returned. Indexes on expressions are
|
||||
/// not returned.
|
||||
///
|
||||
/// SQLite does not define any index for INTEGER PRIMARY KEY columns: this
|
||||
/// method does not return any index that represents the primary key.
|
||||
/// SQLite does not define any index for INTEGER PRIMARY KEY columns:
|
||||
/// this method does not return any index that represents the
|
||||
/// primary key.
|
||||
///
|
||||
/// If you want to know if a set of columns uniquely identifies a row, because
|
||||
/// the columns contain the primary key or a unique index, use
|
||||
/// If you want to know if a set of columns uniquely identifies a row,
|
||||
/// because the columns contain the primary key or a unique index, use
|
||||
/// ``table(_:hasUniqueKey:)``.
|
||||
///
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
@@ -587,16 +679,19 @@ extension Database {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // One table with one primary key (id), and a unique index (a, b):
|
||||
/// //
|
||||
/// // > CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
|
||||
/// // > CREATE UNIQUE INDEX i ON t(a, b);
|
||||
/// try db.table("t", hasUniqueKey: ["id"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["a", "b"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["b", "a"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["c"]) // false
|
||||
/// try db.table("t", hasUniqueKey: ["id", "a"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true
|
||||
/// try dbQueue.read { db in
|
||||
/// // One table with one primary key (id)
|
||||
/// // and a unique index (a, b):
|
||||
/// //
|
||||
/// // > CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
|
||||
/// // > CREATE UNIQUE INDEX i ON t(a, b);
|
||||
/// try db.table("t", hasUniqueKey: ["id"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["a", "b"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["b", "a"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["c"]) // false
|
||||
/// try db.table("t", hasUniqueKey: ["id", "a"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true
|
||||
/// }
|
||||
/// ```
|
||||
public func table(
|
||||
_ tableName: String,
|
||||
@@ -610,6 +705,17 @@ extension Database {
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let foreignKeys = try db.foreignKeys(in: "player")
|
||||
/// for foreignKey in foreignKeys {
|
||||
/// print(foreignKey.destinationTable)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist, or if no such table or view
|
||||
/// with this name exists in the main or temp schema, or in an attached
|
||||
@@ -831,6 +937,17 @@ extension Database {
|
||||
/// When `schemaName` is not specified, known schemas are iterated in
|
||||
/// SQLite resolution order and the first matching result is returned.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let columns = try db.columns(in: "player")
|
||||
/// for column in columns {
|
||||
/// print(column.name)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
|
||||
/// the specified schema does not exist,or if no such table or view
|
||||
/// with this name exists in the main or temp schema, or in an attached
|
||||
|
||||
@@ -121,6 +121,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// - ``clearSchemaCache()``
|
||||
/// - ``logError``
|
||||
/// - ``releaseMemory()``
|
||||
/// - ``sqliteLibVersionNumber``
|
||||
/// - ``trace(options:_:)``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
@@ -302,6 +303,21 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// 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(_:)`.
|
||||
///
|
||||
@@ -1272,6 +1288,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
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
|
||||
@@ -2058,6 +2080,9 @@ extension Database {
|
||||
/// 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")
|
||||
|
||||
|
||||
@@ -83,6 +83,7 @@ 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,
|
||||
|
||||
@@ -60,6 +60,8 @@ import Foundation
|
||||
/// - ``subscript(_:)-3tp8o``
|
||||
/// - ``subscript(_:)-4k8od``
|
||||
/// - ``subscript(_:)-9rbo7``
|
||||
/// - ``coalesce(_:)-359k7``
|
||||
/// - ``coalesce(_:)-6nbah``
|
||||
/// - ``withUnsafeData(named:_:)``
|
||||
/// - ``dataNoCopy(named:)``
|
||||
///
|
||||
@@ -671,6 +673,53 @@ extension Row {
|
||||
public func dataNoCopy(_ column: some ColumnExpression) -> Data? {
|
||||
dataNoCopy(named: column.name)
|
||||
}
|
||||
|
||||
/// Returns the first non-null value, if any. Identical to SQL `COALESCE` function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name: String? = row.coalesce(["nickname", "name"])
|
||||
/// ```
|
||||
///
|
||||
/// Prefer `coalesce` to nil-coalescing row values, which does not
|
||||
/// return the expected value:
|
||||
///
|
||||
/// ```swift
|
||||
/// // INCORRECT
|
||||
/// let name: String? = row["nickname"] ?? row["name"]
|
||||
/// ```
|
||||
public func coalesce<T: DatabaseValueConvertible>(
|
||||
_ columns: some Collection<String>
|
||||
) -> T? {
|
||||
for column in columns {
|
||||
if let value = self[column] as T? {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// Returns the first non-null value, if any. Identical to SQL `COALESCE` function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name: String? = row.coalesce([Column("nickname"), Column("name")])
|
||||
/// ```
|
||||
///
|
||||
/// Prefer `coalesce` to nil-coalescing row values, which does not
|
||||
/// return the expected value:
|
||||
///
|
||||
/// ```swift
|
||||
/// // INCORRECT
|
||||
/// let name: String? = row[Column("nickname")] ?? row[Column("name")]
|
||||
/// ```
|
||||
public func coalesce<T: DatabaseValueConvertible>(
|
||||
_ columns: some Collection<any ColumnExpression>
|
||||
) -> T? {
|
||||
return coalesce(columns.lazy.map { $0.name })
|
||||
}
|
||||
}
|
||||
|
||||
extension Row {
|
||||
|
||||
@@ -172,6 +172,11 @@ public struct SQL: Sendable {
|
||||
self.init(elements: [.expression(expression.sqlExpression)])
|
||||
}
|
||||
|
||||
/// Creates an `SQL` literal from an SQL ordering term.
|
||||
public init(_ ordering: some SQLOrderingTerm) {
|
||||
self.init(elements: [.ordering(ordering.sqlOrdering)])
|
||||
}
|
||||
|
||||
/// Returns true if this literal generates an empty SQL string
|
||||
public var isEmpty: Bool {
|
||||
elements.allSatisfy(\.isEmpty)
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
#if !canImport(Darwin)
|
||||
@preconcurrency
|
||||
#endif
|
||||
import Dispatch
|
||||
|
||||
/// SchedulingWatchdog makes sure that databases connections are used on correct
|
||||
|
||||
@@ -92,6 +92,9 @@ public final class Statement {
|
||||
/// 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.
|
||||
///
|
||||
@@ -160,6 +163,7 @@ public final class Statement {
|
||||
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
|
||||
self.transactionEffect = authorizer.transactionEffect
|
||||
self.authorizerEventKinds = authorizer.databaseEventKinds
|
||||
self.isQueryOnlyPragma = authorizer.isQueryOnlyPragma
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -13,6 +13,8 @@ import string_h
|
||||
import Glibc
|
||||
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
|
||||
import Darwin
|
||||
#elseif os(Windows)
|
||||
import ucrt
|
||||
#endif
|
||||
|
||||
/// `StatementAuthorizer` provides information about compiled database
|
||||
@@ -39,6 +41,9 @@ 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) {
|
||||
@@ -65,6 +70,7 @@ final class StatementAuthorizer {
|
||||
databaseEventKinds = []
|
||||
invalidatesDatabaseSchemaCache = false
|
||||
transactionEffect = nil
|
||||
isQueryOnlyPragma = false
|
||||
isDropStatement = false
|
||||
}
|
||||
|
||||
@@ -190,6 +196,11 @@ 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,4 +1,4 @@
|
||||
#if !os(Linux)
|
||||
#if !os(Linux) && !os(Windows)
|
||||
import Foundation
|
||||
|
||||
private let integerRoundingBehavior = NSDecimalNumberHandler(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
#if !os(Linux) && !os(Windows)
|
||||
/// NSURL stores its absoluteString in the database.
|
||||
extension NSURL: DatabaseValueConvertible {
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import SQLite3
|
||||
|
||||
import Foundation
|
||||
|
||||
#if !os(Linux)
|
||||
#if !os(Linux) && !os(Windows)
|
||||
/// NSUUID adopts DatabaseValueConvertible
|
||||
extension NSUUID: DatabaseValueConvertible {
|
||||
/// Returns a BLOB database value containing the uuid bytes.
|
||||
|
||||
@@ -6,7 +6,7 @@ Define or query the database schema.
|
||||
|
||||
**GRDB supports all database schemas, and has no requirement.** Any existing SQLite database can be opened, and you are free to structure your new databases as you wish.
|
||||
|
||||
You perform modifications to the database schema with methods such as ``Database/create(table:options:body:)``, listed at the end of this page. For example:
|
||||
You perform modifications to the database schema with methods such as ``Database/create(table:options:body:)``, listed in <doc:DatabaseSchemaModifications>. For example:
|
||||
|
||||
```swift
|
||||
try db.create(table: "player") { t in
|
||||
@@ -16,408 +16,19 @@ try db.create(table: "player") { t in
|
||||
}
|
||||
```
|
||||
|
||||
When you plan to evolve the schema as new versions of your application ship, wrap all schema changes in <doc:Migrations>.
|
||||
|
||||
Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example).
|
||||
|
||||
When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See <doc:Migrations> for the detailed procedure.
|
||||
|
||||
## Database Schema Recommendations
|
||||
|
||||
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
|
||||
|
||||
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
|
||||
|
||||
For recommendations specific to JSON columns, see <doc:JSON>.
|
||||
|
||||
### Table names should be English, singular, and camelCased
|
||||
|
||||
Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
// table columns and constraints
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "players") { t in
|
||||
// table columns and constraints
|
||||
}
|
||||
```
|
||||
|
||||
☝️ **If table names follow a different naming convention**, record types (see <doc:QueryInterface>) will need explicit table names:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
// Required because table name is not 'player'
|
||||
static let databaseTableName = "players"
|
||||
}
|
||||
|
||||
extension PostalAddress: TableRecord {
|
||||
// Required because table name is not 'postalAddress'
|
||||
static let databaseTableName = "postal_address"
|
||||
}
|
||||
|
||||
extension Award: TableRecord {
|
||||
// Required because table name is not 'award'
|
||||
static let databaseTableName = "Auszeichnung"
|
||||
}
|
||||
```
|
||||
|
||||
[Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) will need explicit keys as well:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
// Explicit association key because the table name is not 'postalAddress'
|
||||
static let postalAddress = belongsTo(PostalAddress.self, key: "postalAddress")
|
||||
|
||||
// Explicit association key because the table name is not 'award'
|
||||
static let awards = hasMany(Award.self, key: "awards")
|
||||
}
|
||||
```
|
||||
|
||||
As in the above example, make sure to-one associations use singular keys, and to-many associations use plural keys.
|
||||
|
||||
### Column names should be camelCased
|
||||
|
||||
Again, make them look like Swift identifiers: `fullName`, `score`, `creationDate`:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("fullName", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
t.column("creationDate", .datetime).notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("full_name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
t.column("creation_date", .datetime).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
☝️ **If the column names follow a different naming convention**, `Codable` record types will need an explicit `CodingKeys` enum:
|
||||
|
||||
```swift
|
||||
struct Player: Decodable, FetchableRecord {
|
||||
var id: Int64
|
||||
var fullName: String
|
||||
var score: Int
|
||||
var creationDate: Date
|
||||
|
||||
// Required CodingKeys customization because
|
||||
// columns are not named like Swift properties
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, fullName = "full_name", score, creationDate = "creation_date"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Tables should have explicit primary keys
|
||||
|
||||
A primary key uniquely identifies a row in a table. It is defined on one or several columns:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
// Auto-incremented primary key
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "team") { t in
|
||||
// Single-column primary key
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "membership") { t in
|
||||
// Composite primary key
|
||||
t.primaryKey {
|
||||
t.belongsTo("player")
|
||||
t.belongsTo("team")
|
||||
}
|
||||
t.column("role", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
Primary keys support record fetching methods such as ``FetchableRecord/fetchOne(_:id:)``, and persistence methods such as ``MutablePersistableRecord/update(_:onConflict:)`` or ``MutablePersistableRecord/delete(_:)``.
|
||||
|
||||
See <doc:SingleRowTables> when you need to define a table that contains a single row.
|
||||
|
||||
☝️ **If the database table does not define any explicit primary key**, identifying specific rows in this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html) in the matching record types:
|
||||
|
||||
```swift
|
||||
// A table without any explicit primary key
|
||||
try db.create(table: "player") { t in
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
// The record type for the 'player' table'
|
||||
struct Player: Codable {
|
||||
// Uniquely identifies a player.
|
||||
var rowid: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
extension Player: FetchableRecord, MutablePersistableRecord {
|
||||
// Required because the primary key
|
||||
// is the hidden rowid column.
|
||||
static var databaseSelection: [any SQLSelectable] {
|
||||
[AllColumns(), Column.rowID]
|
||||
}
|
||||
|
||||
// Update id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
rowid = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
// SELECT *, rowid FROM player WHERE rowid = 1
|
||||
if let player = try Player.fetchOne(db, id: 1) {
|
||||
// DELETE FROM player WHERE rowid = 1
|
||||
let deleted = try player.delete(db)
|
||||
print(deleted) // true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Single-column primary keys should be named 'id'
|
||||
|
||||
This helps record types play well with the standard `Identifiable` protocol.
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("uuid", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
```
|
||||
☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need a custom `CodingKeys` enum, or an extra property:
|
||||
|
||||
```swift
|
||||
// Custom coding keys
|
||||
struct Player: Codable, Identifiable {
|
||||
var id: String
|
||||
var name: String
|
||||
|
||||
// Required CodingKeys customization because
|
||||
// columns are not named like Swift properties
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "uuid", name
|
||||
}
|
||||
}
|
||||
|
||||
// Extra property
|
||||
struct Player: Identifiable {
|
||||
var uuid: String
|
||||
var name: String
|
||||
|
||||
// Required because the primary key column is not 'id'
|
||||
var id: String { uuid }
|
||||
}
|
||||
```
|
||||
|
||||
### Unique keys should be supported by unique indexes
|
||||
|
||||
Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("team").notNull()
|
||||
t.column("position", .integer).notNull()
|
||||
// Players must have distinct names
|
||||
t.column("name", .text).unique()
|
||||
}
|
||||
|
||||
// One single player at any given position in a team
|
||||
try db.create(
|
||||
indexOn: "player",
|
||||
columns: ["teamId", "position"],
|
||||
options: .unique)
|
||||
```
|
||||
|
||||
> Tip: SQLite does not support deferred unique indexes, and this creates undesired churn when you need to temporarily break them. This may happen, for example, when you want to reorder player positions in our above example.
|
||||
>
|
||||
> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, take care that only actual indexes can be dropped. Unique constraints created inside the table body can not:
|
||||
>
|
||||
> ```swift
|
||||
> // Unique constraint on player(name) can not be dropped.
|
||||
> try db.create(table: "player") { t in
|
||||
> t.column("name", .text).unique()
|
||||
> }
|
||||
>
|
||||
> // Unique index on team(name) can be dropped.
|
||||
> try db.create(table: "team") { t in
|
||||
> t.column("name", .text)
|
||||
> }
|
||||
> try db.create(indexOn: "team", columns: ["name"], options: .unique)
|
||||
> ```
|
||||
>
|
||||
> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See <doc:Migrations> for the detailed procedure.
|
||||
|
||||
☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Fatal error: table player has no unique index on columns ...
|
||||
let player = try Player.fetchOne(db, key: ["teamId": 42, "position": 1])
|
||||
try Player.deleteOne(db, key: ["name": "Arthur"])
|
||||
|
||||
// Use instead:
|
||||
let player = try Player
|
||||
.filter(Column("teamId") == 42 && Column("position") == 1)
|
||||
.fetchOne(db)
|
||||
|
||||
try Player
|
||||
.filter(Column("name") == "Arthur")
|
||||
.deleteAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
### Relations between tables should be supported by foreign keys
|
||||
|
||||
[Foreign Keys](https://www.sqlite.org/foreignkeys.html) have SQLite enforce valid relationships between tables:
|
||||
|
||||
```swift
|
||||
try db.create(table: "team") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("color", .text).notNull()
|
||||
}
|
||||
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// A player must refer to an existing team
|
||||
t.belongsTo("team").notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// No foreign key
|
||||
t.column("teamId", .integer).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` for more information about the creation of foreign keys.
|
||||
|
||||
GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
static let team = belongsTo(Team.self)
|
||||
}
|
||||
|
||||
extension Team: TableRecord {
|
||||
static let players = hasMany(Player.self)
|
||||
}
|
||||
```
|
||||
|
||||
See [Associations and the Database Schema](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#associations-and-the-database-schema) for more precise recommendations.
|
||||
|
||||
☝️ **If a foreign key is not declared in the schema**, you will need to explicitly configure related associations:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
// Required configuration because the database does
|
||||
// not declare any foreign key from players to their team.
|
||||
static let teamForeignKey = ForeignKey(["teamId"])
|
||||
static let team = belongsTo(Team.self,
|
||||
using: teamForeignKey)
|
||||
}
|
||||
|
||||
extension Team: TableRecord {
|
||||
// Required configuration because the database does
|
||||
// not declare any foreign key from players to their team.
|
||||
static let players = hasMany(Player.self,
|
||||
using: Player.teamForeignKey)
|
||||
}
|
||||
```
|
||||
Most applications modify the database schema as new versions ship: it is recommended to wrap all schema changes in <doc:Migrations>.
|
||||
|
||||
## Topics
|
||||
|
||||
### Database Tables
|
||||
### Define the database schema
|
||||
|
||||
- ``Database/alter(table:body:)``
|
||||
- ``Database/create(table:options:body:)``
|
||||
- ``Database/create(virtualTable:ifNotExists:using:)``
|
||||
- ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
- ``Database/drop(table:)``
|
||||
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
|
||||
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
|
||||
- ``Database/rename(table:to:)``
|
||||
- ``Database/ColumnType``
|
||||
- ``Database/ConflictResolution``
|
||||
- ``Database/ForeignKeyAction``
|
||||
- ``TableAlteration``
|
||||
- ``TableDefinition``
|
||||
- ``TableOptions``
|
||||
- ``VirtualTableModule``
|
||||
- <doc:DatabaseSchemaModifications>
|
||||
- <doc:DatabaseSchemaRecommendations>
|
||||
|
||||
### Database Views
|
||||
### Introspect the database schema
|
||||
|
||||
- ``Database/create(view:options:columns:as:)``
|
||||
- ``Database/create(view:options:columns:asLiteral:)``
|
||||
- ``Database/drop(view:)``
|
||||
- ``ViewOptions``
|
||||
- <doc:DatabaseSchemaIntrospection>
|
||||
|
||||
### Database Indexes
|
||||
### Check the database schema
|
||||
|
||||
- ``Database/create(indexOn:columns:options:condition:)``
|
||||
- ``Database/create(index:on:columns:options:condition:)``
|
||||
- ``Database/create(index:on:expressions:options:condition:)``
|
||||
- ``Database/drop(indexOn:columns:)``
|
||||
- ``Database/drop(index:)``
|
||||
- ``IndexOptions``
|
||||
|
||||
### Querying the Database Schema
|
||||
|
||||
- ``Database/columns(in:in:)``
|
||||
- ``Database/foreignKeys(on:in:)``
|
||||
- ``Database/indexes(on:in:)``
|
||||
- ``Database/isGRDBInternalTable(_:)``
|
||||
- ``Database/isSQLiteInternalTable(_:)``
|
||||
- ``Database/primaryKey(_:in:)``
|
||||
- ``Database/schemaVersion()``
|
||||
- ``Database/table(_:hasUniqueKey:)``
|
||||
- ``Database/tableExists(_:in:)``
|
||||
- ``Database/triggerExists(_:in:)``
|
||||
- ``Database/viewExists(_:in:)``
|
||||
- ``ColumnInfo``
|
||||
- ``ForeignKeyInfo``
|
||||
- ``IndexInfo``
|
||||
- ``PrimaryKeyInfo``
|
||||
|
||||
### Integrity Checks
|
||||
|
||||
- ``Database/checkForeignKeys()``
|
||||
- ``Database/checkForeignKeys(in:in:)``
|
||||
- ``Database/foreignKeyViolations()``
|
||||
- ``Database/foreignKeyViolations(in:in:)``
|
||||
- ``ForeignKeyViolation``
|
||||
|
||||
### Sunsetted Methods
|
||||
|
||||
Those are legacy interfaces that are preserved for backwards compatibility. Their use is not recommended.
|
||||
|
||||
- ``Database/create(index:on:columns:unique:ifNotExists:condition:)``
|
||||
- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)``
|
||||
- <doc:DatabaseSchemaIntegrityChecks>
|
||||
@@ -0,0 +1,13 @@
|
||||
# Integrity Checks
|
||||
|
||||
Perform integrity checks of the database content
|
||||
|
||||
## Topics
|
||||
|
||||
### Integrity Checks
|
||||
|
||||
- ``Database/checkForeignKeys()``
|
||||
- ``Database/checkForeignKeys(in:in:)``
|
||||
- ``Database/foreignKeyViolations()``
|
||||
- ``Database/foreignKeyViolations(in:in:)``
|
||||
- ``ForeignKeyViolation``
|
||||
@@ -0,0 +1,35 @@
|
||||
# Database Schema Introspection
|
||||
|
||||
Get information about schema objects such as tables, columns, indexes, foreign keys, etc.
|
||||
|
||||
## Topics
|
||||
|
||||
### Querying the Schema Version
|
||||
|
||||
- ``Database/schemaVersion()``
|
||||
|
||||
### Existence Checks
|
||||
|
||||
- ``Database/tableExists(_:in:)``
|
||||
- ``Database/triggerExists(_:in:)``
|
||||
- ``Database/viewExists(_:in:)``
|
||||
|
||||
### Table Structure
|
||||
|
||||
- ``Database/columns(in:in:)``
|
||||
- ``Database/foreignKeys(on:in:)``
|
||||
- ``Database/indexes(on:in:)``
|
||||
- ``Database/primaryKey(_:in:)``
|
||||
- ``Database/table(_:hasUniqueKey:)``
|
||||
|
||||
### Reserved Tables
|
||||
|
||||
- ``Database/isGRDBInternalTable(_:)``
|
||||
- ``Database/isSQLiteInternalTable(_:)``
|
||||
|
||||
### Supporting Types
|
||||
|
||||
- ``ColumnInfo``
|
||||
- ``ForeignKeyInfo``
|
||||
- ``IndexInfo``
|
||||
- ``PrimaryKeyInfo``
|
||||
@@ -0,0 +1,293 @@
|
||||
# Modifying the Database Schema
|
||||
|
||||
How to modify the database schema
|
||||
|
||||
## Overview
|
||||
|
||||
For modifying the database schema, prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example).
|
||||
|
||||
When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See <doc:Migrations> for the detailed procedure.
|
||||
|
||||
## Create Tables
|
||||
|
||||
The ``Database/create(table:options:body:)`` method covers nearly all SQLite table creation features. For virtual tables, see [Full-Text Search](https://github.com/groue/GRDB.swift/blob/master/Documentation/FullTextSearch.md), or use raw SQL.
|
||||
|
||||
```swift
|
||||
// CREATE TABLE place (
|
||||
// id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
// title TEXT,
|
||||
// favorite BOOLEAN NOT NULL DEFAULT 0,
|
||||
// latitude DOUBLE NOT NULL,
|
||||
// longitude DOUBLE NOT NULL
|
||||
// )
|
||||
try db.create(table: "place") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("title", .text)
|
||||
t.column("favorite", .boolean).notNull().defaults(to: false)
|
||||
t.column("longitude", .double).notNull()
|
||||
t.column("latitude", .double).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
**Configure table creation**
|
||||
|
||||
```swift
|
||||
// CREATE TABLE player ( ... )
|
||||
try db.create(table: "player") { t in ... }
|
||||
|
||||
// CREATE TEMPORARY TABLE player IF NOT EXISTS (
|
||||
try db.create(table: "player", options: [.temporary, .ifNotExists]) { t in ... }
|
||||
```
|
||||
|
||||
Reference: ``TableOptions``
|
||||
|
||||
**Add regular columns** with their name and eventual type (`text`, `integer`, `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime`, `any`, and `json`) - see [SQLite data types](https://www.sqlite.org/datatype3.html) and <doc:JSON>:
|
||||
|
||||
```swift
|
||||
// CREATE TABLE player (
|
||||
// score,
|
||||
// name TEXT,
|
||||
// creationDate DATETIME,
|
||||
// address TEXT,
|
||||
try db.create(table: "player") { t in
|
||||
t.column("score")
|
||||
t.column("name", .text)
|
||||
t.column("creationDate", .datetime)
|
||||
t.column("address", .json)
|
||||
```
|
||||
|
||||
Reference: ``TableDefinition/column(_:_:)``
|
||||
|
||||
Define **not null** columns, and set **default values**:
|
||||
|
||||
```swift
|
||||
// email TEXT NOT NULL,
|
||||
t.column("email", .text).notNull()
|
||||
|
||||
// name TEXT NOT NULL DEFAULT 'Anonymous',
|
||||
t.column("name", .text).notNull().defaults(to: "Anonymous")
|
||||
```
|
||||
|
||||
Reference: ``ColumnDefinition``
|
||||
|
||||
**Define primary, unique, or foreign keys**. When defining a foreign key, the referenced column is the primary key of the referenced table (unless you specify otherwise):
|
||||
|
||||
```swift
|
||||
// id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
|
||||
// uuid TEXT PRIMARY KEY NOT NULL,
|
||||
t.primaryKey("uuid", .text)
|
||||
|
||||
// teamName TEXT NOT NULL,
|
||||
// position INTEGER NOT NULL,
|
||||
// PRIMARY KEY (teamName, position),
|
||||
t.primaryKey {
|
||||
t.column("teamName", .text)
|
||||
t.column("position", .integer)
|
||||
}
|
||||
|
||||
// email TEXT UNIQUE,
|
||||
t.column("email", .text).unique()
|
||||
|
||||
// teamId TEXT REFERENCES team(id) ON DELETE CASCADE,
|
||||
// countryCode TEXT REFERENCES country(code) NOT NULL,
|
||||
t.belongsTo("team", onDelete: .cascade)
|
||||
t.belongsTo("country").notNull()
|
||||
```
|
||||
|
||||
Reference: ``TableDefinition``, ``ColumnDefinition/unique(onConflict:)``
|
||||
|
||||
**Create an index** on a column
|
||||
|
||||
```swift
|
||||
t.column("score", .integer).indexed()
|
||||
```
|
||||
|
||||
Reference: ``ColumnDefinition``
|
||||
|
||||
For extra index options, see <doc:DatabaseSchemaModifications#Create-Indexes> below.
|
||||
|
||||
**Perform integrity checks** on individual columns, and SQLite will only let conforming rows in. In the example below, the `$0` closure variable is a column which lets you build any SQL expression.
|
||||
|
||||
```swift
|
||||
// name TEXT CHECK (LENGTH(name) > 0)
|
||||
// score INTEGER CHECK (score > 0)
|
||||
t.column("name", .text).check { length($0) > 0 }
|
||||
t.column("score", .integer).check(sql: "score > 0")
|
||||
```
|
||||
|
||||
Reference: ``ColumnDefinition``
|
||||
|
||||
Columns can also be defined with a raw sql String, or an [SQL literal](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md#sql-literal) in which you can safely embed raw values without any risk of syntax errors or SQL injection:
|
||||
|
||||
```swift
|
||||
t.column(sql: "name TEXT")
|
||||
|
||||
let defaultName: String = ...
|
||||
t.column(literal: "name TEXT DEFAULT \(defaultName)")
|
||||
```
|
||||
|
||||
Reference: ``TableDefinition``
|
||||
|
||||
Other **table constraints** can involve several columns:
|
||||
|
||||
```swift
|
||||
// PRIMARY KEY (a, b),
|
||||
t.primaryKey(["a", "b"])
|
||||
|
||||
// UNIQUE (a, b) ON CONFLICT REPLACE,
|
||||
t.uniqueKey(["a", "b"], onConflict: .replace)
|
||||
|
||||
// FOREIGN KEY (a, b) REFERENCES parents(c, d),
|
||||
t.foreignKey(["a", "b"], references: "parents")
|
||||
|
||||
// CHECK (a + b < 10),
|
||||
t.check(Column("a") + Column("b") < 10)
|
||||
|
||||
// CHECK (a + b < 10)
|
||||
t.check(sql: "a + b < 10")
|
||||
|
||||
// Raw SQL constraints
|
||||
t.constraint(sql: "CHECK (a + b < 10)")
|
||||
t.constraint(literal: "CHECK (a + b < \(10))")
|
||||
```
|
||||
|
||||
Reference: ``TableDefinition``
|
||||
|
||||
**Generated columns**:
|
||||
|
||||
```swift
|
||||
t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
|
||||
t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"))
|
||||
}
|
||||
```
|
||||
|
||||
Reference: ``ColumnDefinition``
|
||||
|
||||
## Modify Tables
|
||||
|
||||
SQLite lets you modify existing tables:
|
||||
|
||||
```swift
|
||||
// ALTER TABLE referer RENAME TO referrer
|
||||
try db.rename(table: "referer", to: "referrer")
|
||||
|
||||
// ALTER TABLE player ADD COLUMN hasBonus BOOLEAN
|
||||
// ALTER TABLE player RENAME COLUMN url TO homeURL
|
||||
// ALTER TABLE player DROP COLUMN score
|
||||
try db.alter(table: "player") { t in
|
||||
t.add(column: "hasBonus", .boolean)
|
||||
t.rename(column: "url", to: "homeURL")
|
||||
t.drop(column: "score")
|
||||
}
|
||||
```
|
||||
|
||||
Reference: ``TableAlteration``
|
||||
|
||||
> Note: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See <doc:Migrations#Defining-the-Database-Schema-from-a-Migration> for more information.
|
||||
|
||||
## Drop Tables
|
||||
|
||||
Drop tables with the ``Database/drop(table:)`` method:
|
||||
|
||||
```swift
|
||||
try db.drop(table: "obsolete")
|
||||
```
|
||||
|
||||
## Create Indexes
|
||||
|
||||
Create an index on a column:
|
||||
|
||||
```swift
|
||||
try db.create(table: "player") { t in
|
||||
t.column("email", .text).unique()
|
||||
t.column("score", .integer).indexed()
|
||||
}
|
||||
```
|
||||
|
||||
Create indexes on an existing table:
|
||||
|
||||
```swift
|
||||
// CREATE INDEX index_player_on_email ON player(email)
|
||||
try db.create(indexOn: "player", columns: ["email"])
|
||||
|
||||
// CREATE UNIQUE INDEX index_player_on_email ON player(email)
|
||||
try db.create(indexOn: "player", columns: ["email"], options: .unique)
|
||||
```
|
||||
|
||||
Create indexes with a specific collation:
|
||||
|
||||
```swift
|
||||
// CREATE INDEX index_player_on_email ON player(email COLLATE NOCASE)
|
||||
try db.create(
|
||||
index: "index_player_on_email",
|
||||
on: "player",
|
||||
expressions: [Column("email").collating(.nocase)])
|
||||
```
|
||||
|
||||
Create indexes on expressions:
|
||||
|
||||
```swift
|
||||
// CREATE INDEX index_player_on_total_score ON player(score+bonus)
|
||||
try db.create(
|
||||
index: "index_player_on_total_score",
|
||||
on: "player",
|
||||
expressions: [Column("score") + Column("bonus")])
|
||||
|
||||
// CREATE INDEX index_player_on_country ON player(address ->> 'country')
|
||||
try db.create(
|
||||
index: "index_player_on_country",
|
||||
on: "player",
|
||||
expressions: [
|
||||
JSONColumn("address")["country"],
|
||||
])
|
||||
```
|
||||
|
||||
Unique constraints and unique indexes are somewhat different: don't miss the tip in <doc:DatabaseSchemaRecommendations/Unique-keys-should-be-supported-by-unique-indexes> below.
|
||||
|
||||
## Topics
|
||||
|
||||
### Database Tables
|
||||
|
||||
- ``Database/alter(table:body:)``
|
||||
- ``Database/create(table:options:body:)``
|
||||
- ``Database/create(virtualTable:options:using:)``
|
||||
- ``Database/create(virtualTable:options:using:_:)``
|
||||
- ``Database/drop(table:)``
|
||||
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
|
||||
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
|
||||
- ``Database/rename(table:to:)``
|
||||
- ``Database/ColumnType``
|
||||
- ``Database/ConflictResolution``
|
||||
- ``Database/ForeignKeyAction``
|
||||
- ``TableAlteration``
|
||||
- ``TableDefinition``
|
||||
- ``TableOptions``
|
||||
- ``VirtualTableModule``
|
||||
- ``VirtualTableOptions``
|
||||
|
||||
### Database Views
|
||||
|
||||
- ``Database/create(view:options:columns:as:)``
|
||||
- ``Database/create(view:options:columns:asLiteral:)``
|
||||
- ``Database/drop(view:)``
|
||||
- ``ViewOptions``
|
||||
|
||||
### Database Indexes
|
||||
|
||||
- ``Database/create(indexOn:columns:options:condition:)``
|
||||
- ``Database/create(index:on:columns:options:condition:)``
|
||||
- ``Database/create(index:on:expressions:options:condition:)``
|
||||
- ``Database/drop(indexOn:columns:)``
|
||||
- ``Database/drop(index:)``
|
||||
- ``IndexOptions``
|
||||
|
||||
### Sunsetted Methods
|
||||
|
||||
Those are legacy interfaces that are preserved for backwards compatibility. Their use is not recommended.
|
||||
|
||||
- ``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:_:)``
|
||||
@@ -0,0 +1,334 @@
|
||||
# Database Schema Recommendations
|
||||
|
||||
Recommendations for an ideal integration of the database schema with GRDB
|
||||
|
||||
## Overview
|
||||
|
||||
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
|
||||
|
||||
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
|
||||
|
||||
For recommendations specific to JSON columns, see <doc:JSON>.
|
||||
|
||||
## Table names should be English, singular, and camelCased
|
||||
|
||||
Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
// table columns and constraints
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "players") { t in
|
||||
// table columns and constraints
|
||||
}
|
||||
```
|
||||
|
||||
☝️ **If table names follow a different naming convention**, record types (see <doc:QueryInterface>) will need explicit table names:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
// Required because table name is not 'player'
|
||||
static let databaseTableName = "players"
|
||||
}
|
||||
|
||||
extension PostalAddress: TableRecord {
|
||||
// Required because table name is not 'postalAddress'
|
||||
static let databaseTableName = "postal_address"
|
||||
}
|
||||
|
||||
extension Award: TableRecord {
|
||||
// Required because table name is not 'award'
|
||||
static let databaseTableName = "Auszeichnung"
|
||||
}
|
||||
```
|
||||
|
||||
[Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) will need explicit keys as well:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
// Explicit association key because the table name is not 'postalAddress'
|
||||
static let postalAddress = belongsTo(PostalAddress.self, key: "postalAddress")
|
||||
|
||||
// Explicit association key because the table name is not 'award'
|
||||
static let awards = hasMany(Award.self, key: "awards")
|
||||
}
|
||||
```
|
||||
|
||||
As in the above example, make sure to-one associations use singular keys, and to-many associations use plural keys.
|
||||
|
||||
## Column names should be camelCased
|
||||
|
||||
Again, make them look like Swift identifiers: `fullName`, `score`, `creationDate`:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("fullName", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
t.column("creationDate", .datetime).notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("full_name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
t.column("creation_date", .datetime).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
☝️ **If the column names follow a different naming convention**, `Codable` record types will need an explicit `CodingKeys` enum:
|
||||
|
||||
```swift
|
||||
struct Player: Decodable, FetchableRecord {
|
||||
var id: Int64
|
||||
var fullName: String
|
||||
var score: Int
|
||||
var creationDate: Date
|
||||
|
||||
// Required CodingKeys customization because
|
||||
// columns are not named like Swift properties
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id, fullName = "full_name", score, creationDate = "creation_date"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Tables should have explicit primary keys
|
||||
|
||||
A primary key uniquely identifies a row in a table. It is defined on one or several columns:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
// Auto-incremented primary key
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "team") { t in
|
||||
// Single-column primary key
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
try db.create(table: "membership") { t in
|
||||
// Composite primary key
|
||||
t.primaryKey {
|
||||
t.belongsTo("player")
|
||||
t.belongsTo("team")
|
||||
}
|
||||
t.column("role", .text).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
Primary keys support record fetching methods such as ``FetchableRecord/fetchOne(_:id:)``, and persistence methods such as ``MutablePersistableRecord/update(_:onConflict:)`` or ``MutablePersistableRecord/delete(_:)``.
|
||||
|
||||
See <doc:SingleRowTables> when you need to define a table that contains a single row.
|
||||
|
||||
☝️ **If the database table does not define any explicit primary key**, identifying specific rows in this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html) in the matching record types:
|
||||
|
||||
```swift
|
||||
// A table without any explicit primary key
|
||||
try db.create(table: "player") { t in
|
||||
t.column("name", .text).notNull()
|
||||
t.column("score", .integer).notNull()
|
||||
}
|
||||
|
||||
// The record type for the 'player' table'
|
||||
struct Player: Codable {
|
||||
// Uniquely identifies a player.
|
||||
var rowid: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
}
|
||||
|
||||
extension Player: FetchableRecord, MutablePersistableRecord {
|
||||
// Required because the primary key
|
||||
// is the hidden rowid column.
|
||||
static var databaseSelection: [any SQLSelectable] {
|
||||
[.allColumns, .rowID]
|
||||
}
|
||||
|
||||
// Update id upon successful insertion
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
rowid = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
// SELECT *, rowid FROM player WHERE rowid = 1
|
||||
if let player = try Player.fetchOne(db, id: 1) {
|
||||
// DELETE FROM player WHERE rowid = 1
|
||||
let deleted = try player.delete(db)
|
||||
print(deleted) // true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Single-column primary keys should be named 'id'
|
||||
|
||||
This helps record types play well with the standard `Identifiable` protocol.
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("id", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.primaryKey("uuid", .text)
|
||||
t.column("name", .text).notNull()
|
||||
}
|
||||
```
|
||||
☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need a custom `CodingKeys` enum, or an extra property:
|
||||
|
||||
```swift
|
||||
// Custom coding keys
|
||||
struct Player: Codable, Identifiable {
|
||||
var id: String
|
||||
var name: String
|
||||
|
||||
// Required CodingKeys customization because
|
||||
// columns are not named like Swift properties
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "uuid", name
|
||||
}
|
||||
}
|
||||
|
||||
// Extra property
|
||||
struct Player: Identifiable {
|
||||
var uuid: String
|
||||
var name: String
|
||||
|
||||
// Required because the primary key column is not 'id'
|
||||
var id: String { uuid }
|
||||
}
|
||||
```
|
||||
|
||||
## Unique keys should be supported by unique indexes
|
||||
|
||||
Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
|
||||
|
||||
```swift
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.belongsTo("team").notNull()
|
||||
t.column("position", .integer).notNull()
|
||||
// Players must have distinct names
|
||||
t.column("name", .text).unique()
|
||||
}
|
||||
|
||||
// One single player at any given position in a team
|
||||
try db.create(
|
||||
indexOn: "player",
|
||||
columns: ["teamId", "position"],
|
||||
options: .unique)
|
||||
```
|
||||
|
||||
> Tip: SQLite does not support deferred unique indexes, and this creates undesired churn when you need to temporarily break them. This may happen, for example, when you want to reorder player positions in our above example.
|
||||
>
|
||||
> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, take care that only actual indexes can be dropped. Unique constraints created inside the table body can not:
|
||||
>
|
||||
> ```swift
|
||||
> // Unique constraint on player(name) can not be dropped.
|
||||
> try db.create(table: "player") { t in
|
||||
> t.column("name", .text).unique()
|
||||
> }
|
||||
>
|
||||
> // Unique index on team(name) can be dropped.
|
||||
> try db.create(table: "team") { t in
|
||||
> t.column("name", .text)
|
||||
> }
|
||||
> try db.create(indexOn: "team", columns: ["name"], options: .unique)
|
||||
> ```
|
||||
>
|
||||
> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See <doc:Migrations> for the detailed procedure.
|
||||
|
||||
☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
// Fatal error: table player has no unique index on columns ...
|
||||
let player = try Player.fetchOne(db, key: ["teamId": 42, "position": 1])
|
||||
try Player.deleteOne(db, key: ["name": "Arthur"])
|
||||
|
||||
// Use instead:
|
||||
let player = try Player
|
||||
.filter(Column("teamId") == 42 && Column("position") == 1)
|
||||
.fetchOne(db)
|
||||
|
||||
try Player
|
||||
.filter(Column("name") == "Arthur")
|
||||
.deleteAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
## Relations between tables should be supported by foreign keys
|
||||
|
||||
[Foreign Keys](https://www.sqlite.org/foreignkeys.html) have SQLite enforce valid relationships between tables:
|
||||
|
||||
```swift
|
||||
try db.create(table: "team") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("color", .text).notNull()
|
||||
}
|
||||
|
||||
// RECOMMENDED
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// A player must refer to an existing team
|
||||
t.belongsTo("team").notNull()
|
||||
}
|
||||
|
||||
// REQUIRES EXTRA CONFIGURATION
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text).notNull()
|
||||
// No foreign key
|
||||
t.column("teamId", .integer).notNull()
|
||||
}
|
||||
```
|
||||
|
||||
See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` for more information about the creation of foreign keys.
|
||||
|
||||
GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
static let team = belongsTo(Team.self)
|
||||
}
|
||||
|
||||
extension Team: TableRecord {
|
||||
static let players = hasMany(Player.self)
|
||||
}
|
||||
```
|
||||
|
||||
See [Associations and the Database Schema](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#associations-and-the-database-schema) for more precise recommendations.
|
||||
|
||||
☝️ **If a foreign key is not declared in the schema**, you will need to explicitly configure related associations:
|
||||
|
||||
```swift
|
||||
extension Player: TableRecord {
|
||||
// Required configuration because the database does
|
||||
// not declare any foreign key from players to their team.
|
||||
static let teamForeignKey = ForeignKey(["teamId"])
|
||||
static let team = belongsTo(Team.self,
|
||||
using: teamForeignKey)
|
||||
}
|
||||
|
||||
extension Team: TableRecord {
|
||||
// Required configuration because the database does
|
||||
// not declare any foreign key from players to their team.
|
||||
static let players = hasMany(Player.self,
|
||||
using: Player.teamForeignKey)
|
||||
}
|
||||
```
|
||||
@@ -107,10 +107,10 @@ import GRDB
|
||||
import Tagged
|
||||
|
||||
// Add database support to Tagged values
|
||||
extension Tagged: SQLExpressible where RawValue: SQLExpressible { }
|
||||
extension Tagged: StatementBinding where RawValue: StatementBinding { }
|
||||
extension Tagged: StatementColumnConvertible where RawValue: StatementColumnConvertible { }
|
||||
extension Tagged: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
|
||||
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 { }
|
||||
```
|
||||
|
||||
This makes it possible to use `Tagged` values in all the expected places:
|
||||
|
||||
@@ -27,8 +27,8 @@ try db.create(table: "player") { t in
|
||||
> Tip: When an application performs queries on values embedded inside JSON columns, indexes can help performance:
|
||||
>
|
||||
> ```swift
|
||||
> // CREATE INDEX "player_on_country"
|
||||
> // ON "player"("address" ->> 'country')
|
||||
> // CREATE INDEX player_on_country
|
||||
> // ON player(address ->> 'country')
|
||||
> try db.create(
|
||||
> index: "player_on_country",
|
||||
> on: "player",
|
||||
@@ -37,7 +37,7 @@ try db.create(table: "player") { t in
|
||||
> ])
|
||||
>
|
||||
> // SELECT * FROM player
|
||||
> // WHERE "address" ->> 'country' = 'DE'
|
||||
> // WHERE address ->> 'country' = 'DE'
|
||||
> let germanPlayers = try Player
|
||||
> .filter(JSONColumn("address")["country"] == "DE")
|
||||
> .fetchAll(db)
|
||||
@@ -98,6 +98,21 @@ extension Team: FetchableRecord, PersistableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
> Tip: Conform your `Codable` property to `DatabaseValueConvertible` if you want to be able to filter on specific values of it:
|
||||
>
|
||||
> ```swift
|
||||
> struct Address: Codable { ... }
|
||||
> extension Address: DatabaseValueConvertible {}
|
||||
>
|
||||
> // SELECT * FROM player
|
||||
> // WHERE address = '{"street": "...", "city": "...", "country": "..."}'
|
||||
> let players = try Player
|
||||
> .filter(JSONColumn("address") == Address(...))
|
||||
> .fetchAll(db)
|
||||
> ```
|
||||
>
|
||||
> Take care that SQLite will compare strings, not JSON objects: white-space and key ordering matter. For this comparison to succeed, make sure that the database contains values that are formatted exactly like a serialized `Address`.
|
||||
|
||||
## Manipulate JSON values at the database level
|
||||
|
||||
[SQLite JSON functions and operators](https://www.sqlite.org/json1.html) are available starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+.
|
||||
|
||||
@@ -39,7 +39,7 @@ migrator.registerMigration("createLibrary") { db in
|
||||
try migrator.migrate(dbQueue)
|
||||
```
|
||||
|
||||
1. Our database tables follow the <doc:DatabaseSchema#Database-Schema-Recommendations>: table names are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
|
||||
1. Our database tables follow the <doc:DatabaseSchemaRecommendations>: table names are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
|
||||
2. Each author has a unique id.
|
||||
3. An author must have a name.
|
||||
4. The country of an author is not always known.
|
||||
@@ -393,16 +393,16 @@ Extensions to the `DerivableRequest` protocol can not change the type of request
|
||||
|
||||
```swift
|
||||
extension QueryInterfaceRequest<Author> {
|
||||
// Selects author ids
|
||||
func selectId() -> QueryInterfaceRequest<Int64> {
|
||||
selectPrimaryKey(as: Int64.self)
|
||||
// Selects authors' name
|
||||
func selectName() -> QueryInterfaceRequest<String> {
|
||||
select(Author.Columns.name)
|
||||
}
|
||||
}
|
||||
|
||||
// The ids of Japanese authors
|
||||
let ids: Set<Int64> = try Author.all()
|
||||
// The names of Japanese authors
|
||||
let names: Set<String> = try Author.all()
|
||||
.filter(countryCode: "JP")
|
||||
.selectId()
|
||||
.selectName()
|
||||
.fetchSet(db)
|
||||
```
|
||||
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -39,11 +39,73 @@ All safety guarantees of Swift 6 are enforced during database accesses. They are
|
||||
|
||||
The following sections describe, with more details, how GRDB interacts with Swift Concurrency.
|
||||
|
||||
- <doc:SwiftConcurrency#Non-Sendable-Record-Types>
|
||||
- <doc:SwiftConcurrency#Shorthand-Closure-Notation>
|
||||
- <doc:SwiftConcurrency#Non-Sendable-Configuration-of-Record-Types>
|
||||
- <doc:SwiftConcurrency#Non-Sendable-Record-Types>
|
||||
- <doc:SwiftConcurrency#Choosing-between-Synchronous-and-Asynchronous-Database-Accesses>
|
||||
|
||||
### Shorthand Closure Notation
|
||||
|
||||
In the Swift 5 language mode, the compiler emits a warning when a database access is written with the shorthand closure notation:
|
||||
|
||||
```swift
|
||||
// Standard closure:
|
||||
let count = try await writer.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
// Shorthand notation:
|
||||
// ⚠️ Converting non-sendable function value to '@Sendable (Database)
|
||||
// throws -> Int' may introduce data races.
|
||||
let count = try await writer.read(Player.fetchCount)
|
||||
```
|
||||
|
||||
**You can remove this warning** by enabling [SE-0418: Inferring `Sendable` for methods and key path literals](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md), as below:
|
||||
|
||||
- **Using Xcode**
|
||||
|
||||
Set `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` to `YES` in the build settings of your target.
|
||||
|
||||
- **In a SwiftPM package manifest**
|
||||
|
||||
Enable the `InferSendableFromCaptures` upcoming feature:
|
||||
|
||||
```swift
|
||||
.target(
|
||||
name: "MyTarget",
|
||||
swiftSettings: [
|
||||
.enableUpcomingFeature("InferSendableFromCaptures")
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
This language feature is not enabled by default, because it can potentially [affect source compatibility](https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/sourcecompatibility#Inferring-Sendable-for-methods-and-key-path-literals).
|
||||
|
||||
### Non-Sendable Configuration of Record Types
|
||||
|
||||
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when a record type specifies which columns it fetches from the database, with the ``TableRecord/databaseSelection-7iphs`` static property:
|
||||
|
||||
```swift
|
||||
extension Player: FetchableRecord, PersistableRecord {
|
||||
// ❌ Static property 'databaseSelection' is not concurrency-safe
|
||||
// because non-'Sendable' type '[any SQLSelectable]'
|
||||
// may have shared mutable state
|
||||
static let databaseSelection: [any SQLSelectable] = [
|
||||
Column("id"), Column("name"), Column("score")
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**To fix this error**, replace the stored property with a computed property:
|
||||
|
||||
```swift
|
||||
extension Player: FetchableRecord, PersistableRecord {
|
||||
static var databaseSelection: [any SQLSelectable] {
|
||||
[Column("id"), Column("name"), Column("score")]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Non-Sendable Record Types
|
||||
|
||||
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when the application reads, writes, or observes a non-[`Sendable`](https://developer.apple.com/documentation/swift/sendable) type.
|
||||
@@ -128,97 +190,6 @@ You do not need to perform this refactoring right away: you can compile your app
|
||||
|
||||
Yes. Classes that can not be modified, made of constant `let` properties, are Sendable. Those immutable classes will not make it easy to modify the database, though.
|
||||
|
||||
#### FAQ: Why this Sendable requirement?
|
||||
|
||||
**GRDB needs new features in the Swift language and the SDKs in order to deal with non-Sendable types.**
|
||||
|
||||
[SE-0430: `sending` parameter and result values](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0430-transferring-parameters-and-results.md) looks like the language feature we need, but:
|
||||
|
||||
- `DispatchQueue.async` does not accept a `sending` closure. GRDB needs this in order to accept non-Sendable records to be sent to the database, as below:
|
||||
|
||||
```swift
|
||||
let nonSendableRecord: Player
|
||||
try await writer.write { db in
|
||||
try nonSendableRecord.insert(db)
|
||||
}
|
||||
```
|
||||
|
||||
Please [file a feedback](http://feedbackassistant.apple.com) for requesting this DispatchQueue improvement. The more the merrier. I personally filed FB15270949.
|
||||
|
||||
- Database access methods taint the values they fetch. In the code below, the rules of [SE-0414: Region based Isolation](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0414-region-based-isolation.md) have the compiler refuse that the fetched player is sent back to the caller:
|
||||
|
||||
```swift
|
||||
let player = try await writer.read { db in
|
||||
try Player.fetchOne(db, id: 42)
|
||||
}
|
||||
```
|
||||
|
||||
Strictly speaking, the compiler diagnostic is correct: one could copy the non-Sendable `db` argument into the fetched `Player` instance, making it unsuitable for later use. In practice, nobody does that. Copying `db` is a programmer error, and GRDB promptly raises a fatal error whenever a `db` copy would be improperly used. But there is no way to tell the compiler about this practice.
|
||||
|
||||
For all those reasons, GRDB has to require values that are asynchronously written and read from the database to be `Sendable`.
|
||||
|
||||
### Shorthand Closure Notation
|
||||
|
||||
In the Swift 5 language mode, the compiler emits a warning when a database access is written with the shorthand closure notation:
|
||||
|
||||
```swift
|
||||
// Standard closure:
|
||||
let count = try await writer.read { db in
|
||||
try Player.fetchCount(db)
|
||||
}
|
||||
|
||||
// Shorthand notation:
|
||||
// ⚠️ Converting non-sendable function value to '@Sendable (Database)
|
||||
// throws -> Int' may introduce data races.
|
||||
let count = try await writer.read(Player.fetchCount)
|
||||
```
|
||||
|
||||
**You can remove this warning** by enabling [SE-0418: Inferring `Sendable` for methods and key path literals](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md), as below:
|
||||
|
||||
- **Using Xcode**
|
||||
|
||||
Set `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` to `YES` in the build settings of your target.
|
||||
|
||||
- **In a SwiftPM package manifest**
|
||||
|
||||
Enable the `InferSendableFromCaptures` upcoming feature:
|
||||
|
||||
```swift
|
||||
.target(
|
||||
name: "MyTarget",
|
||||
swiftSettings: [
|
||||
.enableUpcomingFeature("InferSendableFromCaptures")
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
This language feature is not enabled by default, because it can potentially [affect source compatibility](https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/sourcecompatibility#Inferring-Sendable-for-methods-and-key-path-literals).
|
||||
|
||||
### Non-Sendable Configuration of Record Types
|
||||
|
||||
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when a record type specifies which columns it fetches from the database, with the ``TableRecord/databaseSelection-7iphs`` static property:
|
||||
|
||||
```swift
|
||||
extension Player: FetchableRecord, MutablePersistableRecord {
|
||||
// ❌ Static property 'databaseSelection' is not concurrency-safe
|
||||
// because non-'Sendable' type '[any SQLSelectable]'
|
||||
// may have shared mutable state
|
||||
static let databaseSelection: [any SQLSelectable] = [
|
||||
Column("id"), Column("name"), Column("score")
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**To fix this error**, replace the stored property with a computed property:
|
||||
|
||||
```swift
|
||||
extension Player: FetchableRecord, MutablePersistableRecord {
|
||||
static var databaseSelection: [any SQLSelectable] {
|
||||
[Column("id"), Column("name"), Column("score")]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Choosing between Synchronous and Asynchronous Database Accesses
|
||||
|
||||
GRDB connections provide two versions of `read` and `write`, one that is synchronous, and one that is asynchronous. It might not be clear how to choose one or the other.
|
||||
|
||||
@@ -326,7 +326,7 @@ extension Database {
|
||||
private func isShadowTable(_ tableName: String) throws -> Bool {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// Maybe SQLCipher is too old: check actual version
|
||||
if sqlite3_libversion_number() >= 3037000 {
|
||||
if Database.sqliteLibVersionNumber >= 3037000 {
|
||||
guard let table = try table(tableName) else {
|
||||
// Not a table
|
||||
return false
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
/// The virtual table module for the FTS3 full-text engine.
|
||||
///
|
||||
/// To create FTS3 tables, use the ``Database`` method
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
|
||||
/// ``Database/create(virtualTable:options:using:_:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE document USING fts3(content)
|
||||
@@ -63,7 +63,7 @@ public struct FTS3 {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
/// See ``Database/create(virtualTable:options:using:_:)``
|
||||
public init() { }
|
||||
|
||||
/// Returns an array of tokens found in the string argument.
|
||||
@@ -143,7 +143,7 @@ extension FTS3: VirtualTableModule {
|
||||
/// virtual table.
|
||||
///
|
||||
/// You don't create instances of this class. Instead, you use the `Database`
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
|
||||
/// ``Database/create(virtualTable:options:using:_:)`` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition
|
||||
|
||||
@@ -106,13 +106,13 @@ public struct FTS3TokenizerDescriptor: Sendable {
|
||||
if !separators.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as separators, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
// and Database.create(virtualTable:options:using:_:)
|
||||
arguments.append("separators=" + separators.sorted().map { String($0) }.joined())
|
||||
}
|
||||
if !tokenCharacters.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
// and Database.create(virtualTable:options:using:_:)
|
||||
arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined())
|
||||
}
|
||||
return FTS3TokenizerDescriptor("unicode61", arguments: arguments)
|
||||
|
||||
+13
-3
@@ -1,7 +1,7 @@
|
||||
/// The virtual table module for the FTS4 full-text engine.
|
||||
///
|
||||
/// To create FTS4 tables, use the ``Database`` method
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
|
||||
/// ``Database/create(virtualTable:options:using:_:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE document USING fts4(content)
|
||||
@@ -31,7 +31,7 @@ public struct FTS4 {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
/// See ``Database/create(virtualTable:options:using:_:)``
|
||||
public init() { }
|
||||
}
|
||||
|
||||
@@ -102,6 +102,16 @@ extension FTS4: VirtualTableModule {
|
||||
case .synchronized(let contentTable):
|
||||
// https://www.sqlite.org/fts3.html#_external_content_fts4_tables_
|
||||
|
||||
if definition.configuration.temporary {
|
||||
// SQLite can't rebuild the index of temporary tables:
|
||||
//
|
||||
// sqlite> CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
|
||||
// sqlite> CREATE VIRTUAL TABLE temp.ft USING fts4(content="t", b, c);
|
||||
// sqlite> INSERT INTO ft(ft) VALUES('rebuild');
|
||||
// Runtime error: SQL logic error
|
||||
fatalError("Temporary external content FTS4 tables are not supported.")
|
||||
}
|
||||
|
||||
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
|
||||
let ftsTable = tableName.quotedDatabaseIdentifier
|
||||
let content = contentTable.quotedDatabaseIdentifier
|
||||
@@ -149,7 +159,7 @@ extension FTS4: VirtualTableModule {
|
||||
/// virtual table.
|
||||
///
|
||||
/// You don't create instances of this class. Instead, you use the `Database`
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
|
||||
/// ``Database/create(virtualTable:options:using:_:)`` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition
|
||||
|
||||
+15
-5
@@ -13,7 +13,7 @@ import Foundation
|
||||
/// The virtual table module for the FTS5 full-text engine.
|
||||
///
|
||||
/// To create FTS5 tables, use the ``Database`` method
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
|
||||
/// ``Database/create(virtualTable:options:using:_:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE document USING fts5(content)
|
||||
@@ -85,7 +85,7 @@ public struct FTS5 {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
|
||||
/// See ``Database/create(virtualTable:options:using:_:)``
|
||||
public init() { }
|
||||
|
||||
// Support for FTS5Pattern initializers. Don't make public. Users tokenize
|
||||
@@ -143,7 +143,7 @@ extension FTS5: VirtualTableModule {
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
/// See Database.create(virtualTable:options:using:_:)
|
||||
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS5TableDefinition {
|
||||
FTS5TableDefinition(configuration: configuration)
|
||||
}
|
||||
@@ -219,7 +219,7 @@ extension FTS5: VirtualTableModule {
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
/// See Database.create(virtualTable:options:using:_:)
|
||||
public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws {
|
||||
switch definition.contentMode {
|
||||
case .raw:
|
||||
@@ -227,6 +227,16 @@ extension FTS5: VirtualTableModule {
|
||||
case .synchronized(let contentTable):
|
||||
// https://sqlite.org/fts5.html#external_content_tables
|
||||
|
||||
if definition.configuration.temporary {
|
||||
// SQLite can't rebuild the index of temporary tables:
|
||||
//
|
||||
// sqlite> CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
|
||||
// sqlite> CREATE VIRTUAL TABLE temp.ft USING fts5(content="t",content_rowid="a",b,c);
|
||||
// sqlite> INSERT INTO ft(ft) VALUES('rebuild');
|
||||
// Runtime error: SQL logic error
|
||||
fatalError("Temporary external content FTS5 tables are not supported.")
|
||||
}
|
||||
|
||||
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
|
||||
let ftsTable = tableName.quotedDatabaseIdentifier
|
||||
let content = contentTable.quotedDatabaseIdentifier
|
||||
@@ -274,7 +284,7 @@ extension FTS5: VirtualTableModule {
|
||||
/// virtual table.
|
||||
///
|
||||
/// You don't create instances of this class. Instead, you use the `Database`
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
|
||||
/// ``Database/create(virtualTable:options:using:_:)`` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
|
||||
|
||||
@@ -112,14 +112,14 @@ public struct FTS5TokenizerDescriptor: Sendable {
|
||||
if !separators.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as separators, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
// and Database.create(virtualTable:options:using:_:)
|
||||
components.append("separators")
|
||||
components.append(separators.sorted().map { String($0) }.joined())
|
||||
}
|
||||
if !tokenCharacters.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
// and Database.create(virtualTable:options:using:_:)
|
||||
components.append("tokenchars")
|
||||
components.append(tokenCharacters.sorted().map { String($0) }.joined())
|
||||
}
|
||||
@@ -197,14 +197,14 @@ public struct FTS5TokenizerDescriptor: Sendable {
|
||||
if !separators.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as separators, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
// and Database.create(virtualTable:options:using:_:)
|
||||
components.append("separators")
|
||||
components.append(separators.sorted().map { String($0) }.joined())
|
||||
}
|
||||
if !tokenCharacters.isEmpty {
|
||||
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
|
||||
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
|
||||
// and Database.create(virtualTable:using:)
|
||||
// and Database.create(virtualTable:options:using:_:)
|
||||
components.append("tokenchars")
|
||||
components.append(tokenCharacters.sorted().map { String($0) }.joined())
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// Fixits for changes introduced by GRDB 7.0.0
|
||||
// swiftlint:disable all
|
||||
|
||||
extension Configuration {
|
||||
@available(*, unavailable, message: "The default transaction kind is now automatically managed.")
|
||||
@@ -15,3 +16,5 @@ extension DatabasePool {
|
||||
@available(*, unavailable, message: "concurrentRead has been removed. Use `asyncConcurrentRead` instead.")
|
||||
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> { preconditionFailure() }
|
||||
}
|
||||
|
||||
// swiftlint:enable all
|
||||
@@ -1,4 +1,6 @@
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
// MARK: - JSON
|
||||
|
||||
extension Database {
|
||||
/// Validates and minifies a JSON string, with the `JSON` SQL function.
|
||||
///
|
||||
@@ -339,8 +341,19 @@ extension Database {
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jvalid>
|
||||
public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSON_VALID", [value.sqlExpression])
|
||||
///
|
||||
/// - parameter value: The tested value.
|
||||
/// - parameter options: See eventual second argument of the
|
||||
/// `JSON_VALID` function. See <https://www.sqlite.org/json1.html#the_json_valid_function>.
|
||||
public static func jsonIsValid(
|
||||
_ value: some SQLExpressible,
|
||||
options: JSONValidationOptions? = nil
|
||||
) -> SQLExpression {
|
||||
if let options {
|
||||
.function("JSON_VALID", [value.sqlExpression, options.rawValue.sqlExpression])
|
||||
} else {
|
||||
.function("JSON_VALID", [value.sqlExpression])
|
||||
}
|
||||
}
|
||||
|
||||
/// The `JSON_QUOTE` SQL function.
|
||||
@@ -419,7 +432,329 @@ extension Database {
|
||||
isJSONValue: true)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - JSONB
|
||||
|
||||
extension Database {
|
||||
public struct JSONValidationOptions: OptionSet, Sendable {
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
|
||||
public static let json = JSONValidationOptions(rawValue: 1)
|
||||
public static let json5 = JSONValidationOptions(rawValue: 2)
|
||||
public static let probablyJSONB = JSONValidationOptions(rawValue: 4)
|
||||
public static let jsonb = JSONValidationOptions(rawValue: 8)
|
||||
}
|
||||
|
||||
/// Validates and returns a binary JSONB representation of the provided
|
||||
/// JSON, with the `JSONB` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSONB(' { "a": [ "test" ] } ') → '{"a":["test"]}'
|
||||
/// Database.jsonb(#" { "a": [ "test" ] } "#)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jmini>
|
||||
public static func jsonb(_ value: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSONB", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// Creates a binary JSONB array with the `JSONB_ARRAY` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSONB_ARRAY(1, 2, 3, 4) → '[1,2,3,4]'
|
||||
/// Database.jsonbArray(1...4)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
|
||||
public static func jsonbArray(
|
||||
_ values: some Collection<some SQLExpressible>
|
||||
) -> SQLExpression {
|
||||
.function("JSONB_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
|
||||
}
|
||||
|
||||
/// Creates a binary JSONB array with the `JSONB_ARRAY` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSONB_ARRAY(1, 2, '3', 4) → '[1,2,"3",4]'
|
||||
/// Database.jsonbArray([1, 2, "3", 4])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
|
||||
public static func jsonbArray(
|
||||
_ values: some Collection<any SQLExpressible>
|
||||
) -> SQLExpression {
|
||||
.function("JSONB_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
|
||||
}
|
||||
|
||||
/// The `JSONB_EXTRACT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSONB_EXTRACT('{"a":123}', '$.a') → 123
|
||||
/// Database.jsonbExtract(#"{"a":123}"#, atPath: "$.a")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonbExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSONB_EXTRACT", [value.sqlExpression, path.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSONB_EXTRACT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSONB_EXTRACT('{"a":2,"c":[4,5]}','$.c','$.a') → '[[4,5],2]'
|
||||
/// Database.jsonbExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonbExtract(
|
||||
_ value: some SQLExpressible,
|
||||
atPaths paths: some Collection<some SQLExpressible>
|
||||
) -> SQLExpression {
|
||||
.function("JSONB_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
/// The `JSONB_INSERT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSONB_INSERT('[1,2,3,4]','$[#]',99) → '[1,2,3,4,99]'
|
||||
/// Database.jsonbInsert("[1,2,3,4]", ["$[#]": value: 99])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jinsb>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - assignments: A collection of key/value pairs, where keys are
|
||||
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonbInsert(
|
||||
_ value: some SQLExpressible,
|
||||
_ assignments: some Collection<(key: String, value: any SQLExpressible)>
|
||||
) -> SQLExpression {
|
||||
.function("JSONB_INSERT", [value.sqlExpression] + assignments.flatMap {
|
||||
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
|
||||
})
|
||||
}
|
||||
|
||||
/// The `JSONB_REPLACE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSONB_REPLACE('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
|
||||
/// Database.jsonbReplace(#"{"a":2,"c":4}"#, ["$.a": 99])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jinsb>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - assignments: A collection of key/value pairs, where keys are
|
||||
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonbReplace(
|
||||
_ value: some SQLExpressible,
|
||||
_ assignments: some Collection<(key: String, value: any SQLExpressible)>
|
||||
) -> SQLExpression {
|
||||
.function("JSONB_REPLACE", [value.sqlExpression] + assignments.flatMap {
|
||||
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
|
||||
})
|
||||
}
|
||||
|
||||
/// The `JSONB_SET` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSONB_SET('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
|
||||
/// Database.jsonbSet(#"{"a":2,"c":4}"#, ["$.a": 99]])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jinsb>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - assignments: A collection of key/value pairs, where keys are
|
||||
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonbSet(
|
||||
_ value: some SQLExpressible,
|
||||
_ assignments: some Collection<(key: String, value: any SQLExpressible)>
|
||||
) -> SQLExpression {
|
||||
.function("JSONB_SET", [value.sqlExpression] + assignments.flatMap {
|
||||
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
|
||||
})
|
||||
}
|
||||
|
||||
/// Creates a binary JSONB object with the `JSONB_OBJECT` SQL function.
|
||||
/// Pass key/value pairs with a Swift collection such as a `Dictionary`.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSONB_OBJECT('c', '{"e":5}') → '{"c":"{\"e\":5}"}'
|
||||
/// Database.jsonbObject([
|
||||
/// "c": #"{"e":5}"#,
|
||||
/// ])
|
||||
///
|
||||
/// // JSONB_OBJECT('c', JSONB_OBJECT('e', 5)) → '{"c":{"e":5}}'
|
||||
/// Database.jsonbObject([
|
||||
/// "c": Database.jsonbObject(["e": 5])),
|
||||
/// ])
|
||||
///
|
||||
/// // JSONB_OBJECT('c', JSONB('{"e":5}')) → '{"c":{"e":5}}'
|
||||
/// Database.jsonbObject([
|
||||
/// "c": Database.jsonb(#"{"e":5}"#),
|
||||
/// ])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jobj>
|
||||
public static func jsonbObject(
|
||||
_ elements: some Collection<(key: String, value: any SQLExpressible)>
|
||||
) -> SQLExpression {
|
||||
.function("JSONB_OBJECT", elements.flatMap {
|
||||
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
|
||||
})
|
||||
}
|
||||
|
||||
/// The `JSONB_PATCH` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSONB_PATCH('{"a":1,"b":2}','{"c":3,"d":4}') → '{"a":1,"b":2,"c":3,"d":4}'
|
||||
/// Database.jsonbPatch(#"{"a":1,"b":2}"#, #"{"c":3,"d":4}"#)
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
|
||||
public static func jsonbPatch(
|
||||
_ value: some SQLExpressible,
|
||||
with patch: some SQLExpressible)
|
||||
-> SQLExpression
|
||||
{
|
||||
.function("JSONB_PATCH", [value.sqlExpression, patch.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSONB_REMOVE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSONB_REMOVE('[0,1,2,3,4]', '$[2]') → '[0,1,3,4]'
|
||||
/// Database.jsonbRemove("[0,1,2,3,4]", atPath: "$[2]")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonbRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
|
||||
.function("JSONB_REMOVE", [value.sqlExpression, path.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `JSONB_REMOVE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // JSONB_REMOVE('[0,1,2,3,4]', '$[2]','$[0]') → '[1,3,4]'
|
||||
/// Database.jsonbRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"])
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - value: A JSON value.
|
||||
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
|
||||
public static func jsonbRemove(
|
||||
_ value: some SQLExpressible,
|
||||
atPaths paths: some Collection<some SQLExpressible>
|
||||
) -> SQLExpression {
|
||||
.function("JSONB_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
/// The `JSONB_GROUP_ARRAY` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT JSONB_GROUP_ARRAY(name) FROM player
|
||||
/// Player.select(Database.jsonbGroupArray(Column("name")))
|
||||
///
|
||||
/// // SELECT JSONB_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonbGroupArray(Column("name"), filter: Column("score") > 0))
|
||||
///
|
||||
/// // SELECT JSONB_GROUP_ARRAY(name ORDER BY name) FROM player
|
||||
/// Player.select(Database.jsonbGroupArray(Column("name"), orderBy: Column("name")))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
public static func jsonbGroupArray(
|
||||
_ value: some SQLExpressible,
|
||||
orderBy ordering: (any SQLOrderingTerm)? = nil,
|
||||
filter: (any SQLSpecificExpressible)? = nil)
|
||||
-> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"JSONB_GROUP_ARRAY",
|
||||
[value.sqlExpression.jsonBuilderExpression],
|
||||
ordering: ordering?.sqlOrdering,
|
||||
filter: filter?.sqlExpression,
|
||||
isJSONValue: true)
|
||||
}
|
||||
|
||||
/// The `JSONB_GROUP_OBJECT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT JSONB_GROUP_OBJECT(name, score) FROM player
|
||||
/// Player.select(Database.jsonbGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score")))
|
||||
///
|
||||
/// // SELECT JSONB_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select(Database.jsonbGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score"),
|
||||
/// filter: Column("score") > 0))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
public static func jsonbGroupObject(
|
||||
key: some SQLExpressible,
|
||||
value: some SQLExpressible,
|
||||
filter: (any SQLSpecificExpressible)? = nil
|
||||
) -> SQLExpression {
|
||||
.aggregateFunction(
|
||||
"JSONB_GROUP_OBJECT",
|
||||
[key.sqlExpression, value.sqlExpression.jsonBuilderExpression],
|
||||
filter: filter?.sqlExpression,
|
||||
isJSONValue: true)
|
||||
}
|
||||
}
|
||||
#else
|
||||
// MARK: - JSON
|
||||
|
||||
extension Database {
|
||||
/// Validates and minifies a JSON string, with the `JSON` SQL function.
|
||||
///
|
||||
|
||||
@@ -40,6 +40,10 @@ import Foundation
|
||||
/// - ``completedMigrations(_:)``
|
||||
/// - ``hasBeenSuperseded(_:)``
|
||||
/// - ``hasCompletedMigrations(_:)``
|
||||
///
|
||||
/// ### Detecting Schema Changes
|
||||
///
|
||||
/// - ``hasSchemaChanges(_:)``
|
||||
public struct DatabaseMigrator: Sendable {
|
||||
/// Controls how a migration handle foreign keys constraints.
|
||||
public enum ForeignKeyChecks: Sendable {
|
||||
@@ -102,6 +106,8 @@ public struct DatabaseMigrator: Sendable {
|
||||
/// migrator.eraseDatabaseOnSchemaChange = true
|
||||
/// #endif
|
||||
/// ```
|
||||
///
|
||||
/// See also ``hasSchemaChanges(_:)``.
|
||||
public var eraseDatabaseOnSchemaChange = false
|
||||
private var defersForeignKeyChecks = true
|
||||
private var _migrations: [Migration] = []
|
||||
@@ -279,6 +285,96 @@ public struct DatabaseMigrator: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Detecting Schema Changes
|
||||
|
||||
/// Returns a boolean value indicating whether the migrator detects a
|
||||
/// change in the definition of migrations.
|
||||
///
|
||||
/// The result is true if one of those conditions is met:
|
||||
///
|
||||
/// - A migration has been removed, or renamed.
|
||||
/// - There exists any difference in the `sqlite_master` table, which
|
||||
/// contains the SQL used to create database tables, indexes,
|
||||
/// triggers, and views.
|
||||
///
|
||||
/// This method supports the ``eraseDatabaseOnSchemaChange`` option.
|
||||
/// When `eraseDatabaseOnSchemaChange` does not exactly fit your
|
||||
/// needs, you can implement it manually as below:
|
||||
///
|
||||
/// ```swift
|
||||
/// #if DEBUG
|
||||
/// // Speed up development by nuking the database when migrations change
|
||||
/// if dbQueue.read(migrator.hasSchemaChanges) {
|
||||
/// try dbQueue.erase()
|
||||
/// // Perform other needed logic
|
||||
/// }
|
||||
/// #endif
|
||||
/// try migrator.migrate(dbQueue)
|
||||
/// ```
|
||||
///
|
||||
public func hasSchemaChanges(_ db: Database) throws -> Bool {
|
||||
let appliedIdentifiers = try appliedIdentifiers(db)
|
||||
let knownIdentifiers = Set(_migrations.map { $0.identifier })
|
||||
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
|
||||
// Database contains an unknown migration
|
||||
return true
|
||||
}
|
||||
|
||||
if let lastAppliedIdentifier = _migrations
|
||||
.map(\.identifier)
|
||||
.last(where: { appliedIdentifiers.contains($0) })
|
||||
{
|
||||
// Some migrations were already applied.
|
||||
//
|
||||
// Let's migrate a temporary database up to the same
|
||||
// level, and compare the database schemas. If they
|
||||
// differ, we'll return true
|
||||
let tmpSchema = try {
|
||||
// Make sure the temporary database is configured
|
||||
// just as the migrated database
|
||||
var tmpConfig = db.configuration
|
||||
tmpConfig.readonly = false // We need write access
|
||||
tmpConfig.targetQueue = nil // Avoid deadlocks
|
||||
tmpConfig.writeTargetQueue = nil // Avoid deadlocks
|
||||
tmpConfig.label = "GRDB.DatabaseMigrator.temporary"
|
||||
|
||||
// Create the temporary database on disk, just in
|
||||
// case migrations would involve a lot of data.
|
||||
//
|
||||
// SQLite supports temporary on-disk databases, but
|
||||
// those are not guaranteed to accept the
|
||||
// preparation functions provided by the user.
|
||||
//
|
||||
// See https://github.com/groue/GRDB.swift/issues/931
|
||||
// for an issue created by such databases.
|
||||
//
|
||||
// So let's create a "regular" temporary database:
|
||||
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory())
|
||||
.appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString)
|
||||
defer {
|
||||
try? FileManager().removeItem(at: tmpURL)
|
||||
}
|
||||
let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig)
|
||||
return try tmpDatabase.writeWithoutTransaction { db in
|
||||
try runMigrations(db, upTo: lastAppliedIdentifier)
|
||||
return try db.schema(.main)
|
||||
}
|
||||
}()
|
||||
|
||||
// Only compare user objects
|
||||
func isUserObject(_ object: SchemaObject) -> Bool {
|
||||
!Database.isSQLiteInternalTable(object.name) && !Database.isGRDBInternalTable(object.name)
|
||||
}
|
||||
let tmpUserSchema = tmpSchema.filter(isUserObject)
|
||||
let userSchema = try db.schema(.main).filter(isUserObject)
|
||||
if userSchema != tmpUserSchema {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// MARK: - Querying Migrations
|
||||
|
||||
/// The list of registered migration identifiers, in the same order as they
|
||||
@@ -409,69 +505,9 @@ public struct DatabaseMigrator: Sendable {
|
||||
if eraseDatabaseOnSchemaChange {
|
||||
var needsErase = false
|
||||
try db.inTransaction(.deferred) {
|
||||
let appliedIdentifiers = try appliedIdentifiers(db)
|
||||
let knownIdentifiers = Set(_migrations.map { $0.identifier })
|
||||
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
|
||||
// Database contains an unknown migration
|
||||
needsErase = true
|
||||
return .commit
|
||||
}
|
||||
|
||||
if let lastAppliedIdentifier = _migrations
|
||||
.map(\.identifier)
|
||||
.last(where: { appliedIdentifiers.contains($0) })
|
||||
{
|
||||
// Some migrations were already applied.
|
||||
//
|
||||
// Let's migrate a temporary database up to the same
|
||||
// level, and compare the database schemas. If they
|
||||
// differ, we'll erase the database.
|
||||
let tmpSchema = try {
|
||||
// Make sure the temporary database is configured
|
||||
// just as the migrated database
|
||||
var tmpConfig = db.configuration
|
||||
tmpConfig.targetQueue = nil // Avoid deadlocks
|
||||
tmpConfig.writeTargetQueue = nil // Avoid deadlocks
|
||||
tmpConfig.label = "GRDB.DatabaseMigrator.temporary"
|
||||
|
||||
// Create the temporary database on disk, just in
|
||||
// case migrations would involve a lot of data.
|
||||
//
|
||||
// SQLite supports temporary on-disk databases, but
|
||||
// those are not guaranteed to accept the
|
||||
// preparation functions provided by the user.
|
||||
//
|
||||
// See https://github.com/groue/GRDB.swift/issues/931
|
||||
// for an issue created by such databases.
|
||||
//
|
||||
// So let's create a "regular" temporary database:
|
||||
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory())
|
||||
.appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString)
|
||||
defer {
|
||||
try? FileManager().removeItem(at: tmpURL)
|
||||
}
|
||||
let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig)
|
||||
return try tmpDatabase.writeWithoutTransaction { db in
|
||||
try runMigrations(db, upTo: lastAppliedIdentifier)
|
||||
return try db.schema(.main)
|
||||
}
|
||||
}()
|
||||
|
||||
// Only compare user objects
|
||||
func isUserObject(_ object: SchemaObject) -> Bool {
|
||||
!Database.isSQLiteInternalTable(object.name) && !Database.isGRDBInternalTable(object.name)
|
||||
}
|
||||
let tmpUserSchema = tmpSchema.filter(isUserObject)
|
||||
let userSchema = try db.schema(.main).filter(isUserObject)
|
||||
if userSchema != tmpUserSchema {
|
||||
needsErase = true
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
|
||||
needsErase = try hasSchemaChanges(db)
|
||||
return .commit
|
||||
}
|
||||
|
||||
if needsErase {
|
||||
try db.erase()
|
||||
}
|
||||
|
||||
@@ -281,6 +281,12 @@ extension Association {
|
||||
relation.ctes[cte.tableName] = cte.cte
|
||||
}
|
||||
}
|
||||
|
||||
public func limit(_ limit: Int, offset: Int? = nil) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation.limit = SQLLimit(limit: limit, offset: offset)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AssociationToOne
|
||||
|
||||
@@ -56,6 +56,7 @@
|
||||
/// - ``select(_:as:)-3o8qw``
|
||||
/// - ``select(literal:as:)``
|
||||
/// - ``select(sql:arguments:as:)``
|
||||
/// - ``selectID()``
|
||||
/// - ``selectPrimaryKey(as:)``
|
||||
///
|
||||
/// ### Batch Delete
|
||||
@@ -237,7 +238,7 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
select(sqlLiteral, as: type)
|
||||
}
|
||||
|
||||
/// Selects the primary key.
|
||||
/// Returns a request that selects the primary key.
|
||||
///
|
||||
/// All primary keys are supported:
|
||||
///
|
||||
@@ -281,6 +282,46 @@ extension QueryInterfaceRequest: SelectionRequest {
|
||||
.asRequest(of: PrimaryKey.self)
|
||||
}
|
||||
|
||||
/// Returns a request that selects the primary key.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT id FROM player WHERE ...
|
||||
/// let request = try Player.filter(...).selectID()
|
||||
/// ```
|
||||
///
|
||||
/// **Important**: if the record type has an `ID` type that is an
|
||||
/// optional, such as `Int64?`, it is recommended to prefer
|
||||
/// ``selectPrimaryKey(as:)`` instead:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: Identifiable {
|
||||
/// var id: Int64?
|
||||
/// }
|
||||
///
|
||||
/// // NOT RECOMMENDED: Set<Int64?>
|
||||
/// let ids = try Player.filter(...)
|
||||
/// .selectID()
|
||||
/// .fetchSet(db)
|
||||
///
|
||||
/// // BETTER: Set<Int64>
|
||||
/// let ids = try Player.filter(...)
|
||||
/// .selectPrimaryKey(as: Int64.self)
|
||||
/// .fetchSet(db)
|
||||
/// ```
|
||||
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
|
||||
where RowDecoder: Identifiable
|
||||
{
|
||||
selectWhenConnected { db in
|
||||
let primaryKey = try db.primaryKey(self.databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
|
||||
return [Column(primaryKey.columns[0])]
|
||||
}.asRequest(of: RowDecoder.ID.self)
|
||||
}
|
||||
|
||||
public func annotatedWhenConnected(
|
||||
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
|
||||
-> Self
|
||||
@@ -1477,7 +1518,7 @@ private func prefetch(
|
||||
fatalError("Not implemented: prefetch association without any foreign key")
|
||||
|
||||
case let .foreignKey(pivotForeignKey):
|
||||
let originTable = originRelation.source.tableName
|
||||
let originTable = originRelation.source.associationOriginTable ?? originRelation.source.tableName
|
||||
let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable)
|
||||
let pivotColumns = pivotMapping.map(\.right)
|
||||
let leftColumns = pivotMapping.map(\.left)
|
||||
@@ -1610,7 +1651,7 @@ func makePrefetchRequest(
|
||||
// Author.including(all: Author.books)
|
||||
let pivotAlias = TableAlias()
|
||||
|
||||
let prefetchRelation = association
|
||||
var prefetchRelation = association
|
||||
.with {
|
||||
$0.pivot.relation = $0.pivot.relation
|
||||
.aliased(pivotAlias)
|
||||
@@ -1619,7 +1660,52 @@ func makePrefetchRequest(
|
||||
.destinationRelation()
|
||||
.annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") })
|
||||
|
||||
return QueryInterfaceRequest<Row>(relation: prefetchRelation)
|
||||
if let limit = prefetchRelation.limit {
|
||||
let baseName = "grdb_" + association.destination.key.name(singular: true)
|
||||
let cteName = baseName + "_limited"
|
||||
let rowNumberName = "rowNumber"
|
||||
|
||||
let ordering = prefetchRelation.ordering
|
||||
|
||||
let rowNumberFilter: SQLExpression
|
||||
if let offset = limit.offset {
|
||||
rowNumberFilter = ((offset + 1)..<(offset + 1 + limit.limit)).contains(Column(rowNumberName)).sqlExpression
|
||||
} else {
|
||||
rowNumberFilter = (Column(rowNumberName) <= limit.limit).sqlExpression
|
||||
}
|
||||
|
||||
#warning("TODO: the order clause may refer to stuff inside the CTE.")
|
||||
var limitedPrefetchRelation = prefetchRelation
|
||||
// Annotate with the row number
|
||||
.annotatedWhenConnected { db in
|
||||
var sql: SQL = "ROW_NUMBER() OVER (PARTITION BY "
|
||||
sql.append(literal: pivotColumns
|
||||
.map { SQL(Column($0)) }
|
||||
.joined(separator: ", "))
|
||||
|
||||
let orderings = try ordering.resolve(db)
|
||||
if !orderings.isEmpty {
|
||||
sql.append(sql: " ORDER BY ")
|
||||
sql.append(literal: orderings
|
||||
.map { SQL($0) }
|
||||
.joined(separator: ", "))
|
||||
}
|
||||
sql.append(sql: ")")
|
||||
return [sql.forKey(rowNumberName)]
|
||||
}
|
||||
// Limit is applied below, with the rowNumber filter
|
||||
.unlimited()
|
||||
// Turn into a CTE so that we can filter by rowNumber
|
||||
.asCommonTableExpression(named: cteName)
|
||||
// Reapply order
|
||||
.orderWhenConnected { try ordering.resolve($0) }
|
||||
// Turnt the limit into a rowNumber filter
|
||||
.filter(rowNumberFilter)
|
||||
|
||||
return QueryInterfaceRequest<Row>(relation: limitedPrefetchRelation)
|
||||
} else {
|
||||
return QueryInterfaceRequest<Row>(relation: prefetchRelation)
|
||||
}
|
||||
}
|
||||
|
||||
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
|
||||
|
||||
@@ -458,11 +458,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
}
|
||||
|
||||
return filterWhenConnected(keys: { [databaseTableName] db in
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
|
||||
let column = primaryKey.columns[0]
|
||||
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
|
||||
let strategy = recordType.databaseDataEncodingStrategy(for: column)
|
||||
let expressions = try datas.map { try strategy.encode($0).sqlExpression }
|
||||
return expressions
|
||||
@@ -475,11 +471,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
}
|
||||
|
||||
return filterWhenConnected(keys: { [databaseTableName] db in
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
|
||||
let column = primaryKey.columns[0]
|
||||
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
|
||||
let strategy = recordType.databaseDateEncodingStrategy(for: column)
|
||||
let expressions = dates.map { strategy.encode($0).sqlExpression }
|
||||
return expressions
|
||||
@@ -492,11 +484,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
}
|
||||
|
||||
return filterWhenConnected(keys: { [databaseTableName] db in
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
|
||||
let column = primaryKey.columns[0]
|
||||
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
|
||||
let strategy = recordType.databaseUUIDEncodingStrategy(for: column)
|
||||
let expressions = uuids.map { strategy.encode($0).sqlExpression }
|
||||
return expressions
|
||||
@@ -524,12 +512,8 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
// Don't bother removing NULLs. We'd lose CPU cycles, and this does not
|
||||
// change the SQLite results anyway.
|
||||
let expressions = try keys(db)
|
||||
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
|
||||
return SQLCollection.array(expressions).contains(Column(primaryKey.columns[0]).sqlExpression)
|
||||
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
|
||||
return SQLCollection.array(expressions).contains(Column(column).sqlExpression)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -61,6 +61,13 @@ extension ColumnExpression {
|
||||
|
||||
extension ColumnExpression where Self == Column {
|
||||
/// The hidden rowID column.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT rowid FROM player
|
||||
/// let rowids = try Player.select(.rowID).fetchSet(db)
|
||||
/// ```
|
||||
public static var rowID: Self { Column.rowID }
|
||||
}
|
||||
|
||||
|
||||
@@ -954,6 +954,17 @@ extension SQLExpression {
|
||||
"JSON_REPLACE",
|
||||
"JSON_SET",
|
||||
"JSON_QUOTE",
|
||||
"JSONB",
|
||||
"JSONB_ARRAY",
|
||||
"JSONB_EXTRACT",
|
||||
"JSONB_GROUP_ARRAY",
|
||||
"JSONB_GROUP_OBJECT",
|
||||
"JSONB_INSERT",
|
||||
"JSONB_OBJECT",
|
||||
"JSONB_PATCH",
|
||||
"JSONB_REMOVE",
|
||||
"JSONB_REPLACE",
|
||||
"JSONB_SET",
|
||||
"LENGTH",
|
||||
"LIKE",
|
||||
"LIKELIHOOD",
|
||||
@@ -1005,6 +1016,16 @@ extension SQLExpression {
|
||||
"JSON_REPLACE",
|
||||
"JSON_SET",
|
||||
"JSON_QUOTE",
|
||||
"JSONB",
|
||||
"JSONB_ARRAY",
|
||||
"JSONB_GROUP_ARRAY",
|
||||
"JSONB_GROUP_OBJECT",
|
||||
"JSONB_INSERT",
|
||||
"JSONB_OBJECT",
|
||||
"JSONB_PATCH",
|
||||
"JSONB_REMOVE",
|
||||
"JSONB_REPLACE",
|
||||
"JSONB_SET",
|
||||
]
|
||||
|
||||
/// The `COUNT(*)` expression.
|
||||
@@ -2099,8 +2120,9 @@ extension SQLExpression {
|
||||
case .jsonValue:
|
||||
if isJSONValue {
|
||||
return self
|
||||
} else if Database.sqliteLibVersionNumber >= 3045000 {
|
||||
return .function("JSONB", [self])
|
||||
} else {
|
||||
// Needs explicit call to JSON()
|
||||
return .function("JSON", [self])
|
||||
}
|
||||
}
|
||||
@@ -2116,8 +2138,9 @@ extension SQLExpression {
|
||||
case .jsonValue:
|
||||
if isJSONValue {
|
||||
return self
|
||||
} else if Database.sqliteLibVersionNumber >= 3045000 {
|
||||
return .function("JSONB", [self])
|
||||
} else {
|
||||
// Needs explicit call to JSON()
|
||||
return .function("JSON", [self])
|
||||
}
|
||||
}
|
||||
@@ -2136,7 +2159,14 @@ public protocol SQLExpressible {
|
||||
}
|
||||
|
||||
extension SQLExpressible where Self == Column {
|
||||
/// The hidden rowID column
|
||||
/// The hidden rowID column.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT rowid FROM player
|
||||
/// let rowids = try Player.select(.rowID).fetchSet(db)
|
||||
/// ```
|
||||
public static var rowID: Self { Column.rowID }
|
||||
}
|
||||
|
||||
@@ -2168,6 +2198,7 @@ extension SQLExpressible where Self == Column {
|
||||
/// - ``average(_:filter:)``
|
||||
/// - ``capitalized``
|
||||
/// - ``cast(_:as:)-1dmu3``
|
||||
/// - ``coalesce(_:)``
|
||||
/// - ``count(_:)``
|
||||
/// - ``count(distinct:)``
|
||||
/// - ``dateTime(_:_:)``
|
||||
|
||||
@@ -71,6 +71,32 @@ public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Dat
|
||||
.cast(expression.sqlExpression, as: storageClass)
|
||||
}
|
||||
|
||||
/// The `COALESCE` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // COALESCE(value1, value2, ...)
|
||||
/// coalesce([Column("value1"), Column("value2"), ...])
|
||||
/// ```
|
||||
///
|
||||
/// Unlike the SQL function, `coalesce` accepts any number of arguments.
|
||||
/// When `values` is empty, the result is `NULL`. When `values` contains a
|
||||
/// single value, the result is this value. `COALESCE` is used from
|
||||
/// two values upwards.
|
||||
public func coalesce(_ values: some Collection<any SQLSpecificExpressible>) -> SQLExpression {
|
||||
// SQLite COALESCE wants at least two arguments.
|
||||
// There is no reason to apply the same limitation.
|
||||
guard let value = values.first else {
|
||||
return .null
|
||||
}
|
||||
if values.count > 1 {
|
||||
return .function("COALESCE", values.map { $0.sqlExpression })
|
||||
} else {
|
||||
return value.sqlExpression
|
||||
}
|
||||
}
|
||||
|
||||
/// The `COUNT` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -282,6 +282,12 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
func unlimited() -> Self {
|
||||
with {
|
||||
$0.limit = nil
|
||||
}
|
||||
}
|
||||
|
||||
func withStableOrder() -> Self {
|
||||
with { relation in
|
||||
relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in
|
||||
@@ -636,7 +642,7 @@ extension SQLRelation {
|
||||
}
|
||||
|
||||
// <https://github.com/groue/GRDB.swift/issues/1357>
|
||||
guard selection.allSatisfy(\.isTriviallyCountable) else {
|
||||
if selection.contains(where: \.requiresTrivialCount) {
|
||||
return try fetchTrivialCount(db)
|
||||
}
|
||||
|
||||
@@ -655,6 +661,47 @@ extension SQLRelation {
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRelation {
|
||||
#warning("TODO: the order clause may refer to stuff inside the CTE.")
|
||||
#warning("TODO: Try to leave the ordering inside the CTE")
|
||||
func asCommonTableExpression(named tableName: String) -> Self {
|
||||
with { relation in
|
||||
GRDBPrecondition(ctes[tableName] == nil, """
|
||||
Can't turn relation into a Common Table Expression because \
|
||||
CTE '\(tableName)' is already defined. Please file a bug \
|
||||
at https://github.com/groue/GRDB.swift/issues/new
|
||||
""")
|
||||
|
||||
relation.ctes[tableName] = SQLCTE(
|
||||
tableName: tableName,
|
||||
columns: nil,
|
||||
sqlSubquery: .relation(
|
||||
self
|
||||
.unorderedUnlessLimited() // only preserve ordering in the CTE if limited
|
||||
.removingPrefetchedAssociations()),
|
||||
isRecursive: false)
|
||||
|
||||
relation.source = SQLSource(
|
||||
tableName: tableName,
|
||||
associationOriginTable: relation.source.associationOriginTable ?? relation.source.tableName)
|
||||
|
||||
relation.selectionPromise = DatabasePromise { _ in [.allColumns] }
|
||||
relation.filterPromise = nil
|
||||
relation.isDistinct = false
|
||||
relation.groupPromise = nil
|
||||
relation.havingExpressionPromise = nil
|
||||
relation.limit = nil
|
||||
|
||||
relation = relation.filteringChildren { child in
|
||||
switch child.kind {
|
||||
case .all, .bridge: true
|
||||
case .oneOptional, .oneRequired: false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLLimit
|
||||
|
||||
struct SQLLimit {
|
||||
@@ -673,9 +720,15 @@ struct SQLLimit {
|
||||
// MARK: - SQLSource
|
||||
|
||||
struct SQLSource: Sendable {
|
||||
/// The name of a database table to select from.
|
||||
var tableName: String
|
||||
var alias: TableAlias?
|
||||
|
||||
/// When not nil, use this table name instead of `tableName` when looking
|
||||
/// for foreign keys on this source. This string is not nil when an
|
||||
/// `SQLRelation` has been turned into a common table expression.
|
||||
var associationOriginTable: String?
|
||||
|
||||
func aliased(_ alias: TableAlias) -> SQLSource {
|
||||
if let sourceAlias = self.alias {
|
||||
alias.becomeProxy(of: sourceAlias)
|
||||
|
||||
@@ -26,6 +26,12 @@ public struct SQLSelection: Sendable {
|
||||
/// All columns, qualified: `player.*`
|
||||
case qualifiedAllColumns(TableAlias)
|
||||
|
||||
/// All columns but the specified ones
|
||||
case allColumnsExcluding(Set<CaseInsensitiveIdentifier>)
|
||||
|
||||
/// All columns but the specified ones, qualified.
|
||||
case qualifiedAllColumnsExcluding(TableAlias, Set<CaseInsensitiveIdentifier>)
|
||||
|
||||
/// An expression
|
||||
case expression(SQLExpression)
|
||||
|
||||
@@ -41,11 +47,21 @@ public struct SQLSelection: Sendable {
|
||||
/// All columns: `*`
|
||||
static let allColumns = SQLSelection(impl: .allColumns)
|
||||
|
||||
/// All columns but the specified ones.
|
||||
static func allColumnsExcluding(_ excludedColumns: Set<CaseInsensitiveIdentifier>) -> Self {
|
||||
SQLSelection(impl: .allColumnsExcluding(excludedColumns))
|
||||
}
|
||||
|
||||
/// All columns, qualified: `player.*`
|
||||
static func qualifiedAllColumns(_ alias: TableAlias) -> Self {
|
||||
self.init(impl: .qualifiedAllColumns(alias))
|
||||
}
|
||||
|
||||
/// All columns but the specified ones, qualified.
|
||||
static func qualifiedAllColumnsExcluding(_ alias: TableAlias, _ excludedColumns: Set<CaseInsensitiveIdentifier>) -> Self {
|
||||
self.init(impl: .qualifiedAllColumnsExcluding(alias, excludedColumns))
|
||||
}
|
||||
|
||||
/// An expression
|
||||
static func expression(_ expression: SQLExpression) -> Self {
|
||||
self.init(impl: .expression(expression))
|
||||
@@ -70,13 +86,16 @@ extension SQLSelection {
|
||||
/// Returns nil when the number of columns is unknown.
|
||||
func columnCount(_ context: SQLGenerationContext) throws -> Int? {
|
||||
switch impl {
|
||||
case .allColumns:
|
||||
case .allColumns, .allColumnsExcluding:
|
||||
// Likely a GRDB bug: we can't count the number of columns in an
|
||||
// unqualified table.
|
||||
return nil
|
||||
|
||||
case let .qualifiedAllColumns(alias):
|
||||
return try context.columnCount(in: alias.tableName)
|
||||
return try context.columnCount(in: alias.tableName, excluding: [])
|
||||
|
||||
case let .qualifiedAllColumnsExcluding(alias, excludedColumns):
|
||||
return try context.columnCount(in: alias.tableName, excluding: excludedColumns)
|
||||
|
||||
case .expression,
|
||||
.aliasedExpression:
|
||||
@@ -104,7 +123,28 @@ extension SQLSelection {
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
return .all
|
||||
|
||||
case .qualifiedAllColumns:
|
||||
case .allColumnsExcluding:
|
||||
// SELECT DISTINCT a, b, c FROM tableName ...
|
||||
if distinct {
|
||||
// TODO: if the selection were qualified, and if we had a
|
||||
// database connection, we could detect the case where there
|
||||
// remains only one column, and we could perform a
|
||||
// SELECT COUNT(DISTINCT remainingColumn) FROM tableName
|
||||
//
|
||||
// Since most people will not use `.allColumns(excluding:)`
|
||||
// when they want to select only one column, I guess that
|
||||
// this optimization has little chance to be needed.
|
||||
//
|
||||
// Can't count
|
||||
return nil
|
||||
}
|
||||
|
||||
// SELECT a, b, c FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
return .all
|
||||
|
||||
case .qualifiedAllColumns, .qualifiedAllColumnsExcluding:
|
||||
return nil
|
||||
|
||||
case let .expression(expression),
|
||||
@@ -126,41 +166,6 @@ extension SQLSelection {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the SQL that feeds the argument of the `COUNT` function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// COUNT(*)
|
||||
/// COUNT(id)
|
||||
/// ^---- countedSQL
|
||||
///
|
||||
/// - parameter context: An SQL generation context which accepts
|
||||
/// statement arguments.
|
||||
func countedSQL(_ context: SQLGenerationContext) throws -> String {
|
||||
switch impl {
|
||||
case .allColumns:
|
||||
return "*"
|
||||
|
||||
case let .qualifiedAllColumns(alias):
|
||||
if context.qualifier(for: alias) != nil {
|
||||
// SELECT COUNT(t.*) is invalid SQL
|
||||
fatalError("Not implemented, or invalid query")
|
||||
}
|
||||
return "*"
|
||||
|
||||
case let .expression(expression),
|
||||
let .aliasedExpression(expression, _):
|
||||
return try expression.sql(context)
|
||||
|
||||
case .literal:
|
||||
fatalError("""
|
||||
Selection literals can't be counted. \
|
||||
To resolve this error, select one or several literal expressions instead. \
|
||||
See SQL.sqlExpression.
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the SQL that feeds the selection of a `SELECT` statement.
|
||||
///
|
||||
/// For example:
|
||||
@@ -179,11 +184,38 @@ extension SQLSelection {
|
||||
case .allColumns:
|
||||
return "*"
|
||||
|
||||
case .allColumnsExcluding:
|
||||
// Likely a GRDB bug: we don't know the table name so we can't
|
||||
// load remaining columns. This selection should have been
|
||||
// turned into a `.qualifiedAllColumnsExcluding`.
|
||||
fatalError("Not implemented, or invalid query")
|
||||
|
||||
case let .qualifiedAllColumns(alias):
|
||||
if let qualifier = context.qualifier(for: alias) {
|
||||
return qualifier.quotedDatabaseIdentifier + ".*"
|
||||
}
|
||||
return "*"
|
||||
|
||||
case let .qualifiedAllColumnsExcluding(alias, excludedColumns):
|
||||
let columnsNames = try context.columnNames(in: alias.tableName)
|
||||
let remainingColumnsNames = if excludedColumns.isEmpty {
|
||||
columnsNames
|
||||
} else {
|
||||
columnsNames.filter {
|
||||
!excludedColumns.contains(CaseInsensitiveIdentifier(rawValue: $0))
|
||||
}
|
||||
}
|
||||
if columnsNames.count == remainingColumnsNames.count {
|
||||
// We're not excluding anything
|
||||
if let qualifier = context.qualifier(for: alias) {
|
||||
return qualifier.quotedDatabaseIdentifier + ".*"
|
||||
}
|
||||
return "*"
|
||||
} else {
|
||||
return try remainingColumnsNames
|
||||
.map { try SQLExpression.column($0).qualified(with: alias).sql(context) }
|
||||
.joined(separator: ", ")
|
||||
}
|
||||
|
||||
case let .expression(expression):
|
||||
return try expression.sql(context)
|
||||
@@ -228,12 +260,15 @@ extension SQLSelection {
|
||||
/// Returns a qualified selection
|
||||
func qualified(with alias: TableAlias) -> SQLSelection {
|
||||
switch impl {
|
||||
case .qualifiedAllColumns:
|
||||
case .qualifiedAllColumns, .qualifiedAllColumnsExcluding:
|
||||
return self
|
||||
|
||||
case .allColumns:
|
||||
return .qualifiedAllColumns(alias)
|
||||
|
||||
case let .allColumnsExcluding(excludedColumns):
|
||||
return .qualifiedAllColumnsExcluding(alias, excludedColumns)
|
||||
|
||||
case let .expression(expression):
|
||||
return .expression(expression.qualified(with: alias))
|
||||
|
||||
@@ -245,15 +280,27 @@ extension SQLSelection {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether this selection MUST be counted with a "trivial"
|
||||
/// count: `SELECT COUNT(*) FROM (SELECT ...)`.
|
||||
///
|
||||
/// Supports SQLRelation.fetchCount.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/issues/1357>
|
||||
var isTriviallyCountable: Bool {
|
||||
var requiresTrivialCount: Bool {
|
||||
switch impl {
|
||||
case .aliasedExpression, .literal:
|
||||
return false
|
||||
case .allColumns, .qualifiedAllColumns, .expression:
|
||||
// Trivial count is required.
|
||||
//
|
||||
// For example, the WHERE clause here requires the aliased
|
||||
// column to be preserved in the counting request:
|
||||
// SELECT *, column AS alt FROM player WHERE alt
|
||||
return true
|
||||
case .allColumns, .qualifiedAllColumns:
|
||||
return false
|
||||
case .allColumnsExcluding, .qualifiedAllColumnsExcluding:
|
||||
return false
|
||||
case .expression:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -297,15 +344,41 @@ enum SQLCount {
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Standard Selections
|
||||
///
|
||||
/// - ``rowID``
|
||||
/// - ``allColumns``
|
||||
/// - ``allColumns(excluding:)-3sg4w``
|
||||
/// - ``allColumns(excluding:)-3blq4``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AllColumns``
|
||||
/// - ``AllColumnsExcluding``
|
||||
/// - ``SQLSelection``
|
||||
public protocol SQLSelectable {
|
||||
/// Returns an SQL selection.
|
||||
var sqlSelection: SQLSelection { get }
|
||||
}
|
||||
|
||||
extension SQLSelectable where Self == Column {
|
||||
/// The hidden rowID column.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: FetchableRecord, TableRecord {
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// [.allColumns, .rowID]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, rowid FROM player
|
||||
/// Player.fetchAll(db)
|
||||
/// ```
|
||||
public static var rowID: Self { Column.rowID }
|
||||
}
|
||||
|
||||
extension SQLSelection: SQLSelectable {
|
||||
// Not a real deprecation, just a usage warning
|
||||
@available(*, deprecated, message: "Already SQLSelection")
|
||||
@@ -319,10 +392,14 @@ extension SQLSelection: SQLSelectable {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// // SELECT * FROM player
|
||||
/// let players = try Player.select(AllColumns()).fetchAll(db)
|
||||
/// struct Player: FetchableRecord, TableRecord {
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// [.allColumns, .rowID]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, rowid FROM player
|
||||
/// Player.fetchAll(db)
|
||||
/// ```
|
||||
public struct AllColumns: Sendable {
|
||||
/// The `*` selection.
|
||||
@@ -334,3 +411,92 @@ extension AllColumns: SQLSelectable {
|
||||
.allColumns
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLSelectable where Self == AllColumns {
|
||||
/// All columns of the requested table.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: FetchableRecord, TableRecord {
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// [.allColumns, .rowID]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT *, rowid FROM player
|
||||
/// Player.fetchAll(db)
|
||||
/// ```
|
||||
public static var allColumns: AllColumns { AllColumns() }
|
||||
}
|
||||
|
||||
// MARK: - AllColumnsExcluding
|
||||
|
||||
/// `AllColumnsExcluding` selects all columns in a database table, but the
|
||||
/// ones you specify.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// [.allColumns(excluding: ["generatedColumn"])]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id, name, score FROM player
|
||||
/// Player.fetchAll(db)
|
||||
/// ```
|
||||
public struct AllColumnsExcluding: Sendable {
|
||||
var excludedColumns: Set<CaseInsensitiveIdentifier>
|
||||
|
||||
public init(_ excludedColumns: some Collection<String>) {
|
||||
self.excludedColumns = Set(excludedColumns.lazy.map {
|
||||
CaseInsensitiveIdentifier(rawValue: $0)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
extension AllColumnsExcluding: SQLSelectable {
|
||||
public var sqlSelection: SQLSelection {
|
||||
.allColumnsExcluding(excludedColumns)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLSelectable where Self == AllColumnsExcluding {
|
||||
/// All columns of the requested table, excluding the provided columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// [.allColumns(excluding: ["generatedColumn"])]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id, name, score FROM player
|
||||
/// Player.fetchAll(db)
|
||||
/// ```
|
||||
public static func allColumns(excluding excludedColumns: some Collection<String>) -> Self {
|
||||
AllColumnsExcluding(excludedColumns)
|
||||
}
|
||||
|
||||
/// All columns of the requested table, excluding the provided columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// [.allColumns(excluding: [Column("generatedColumn")])]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id, name, score FROM player
|
||||
/// Player.fetchAll(db)
|
||||
/// ```
|
||||
public static func allColumns(excluding excludedColumns: some Collection<any ColumnExpression>) -> Self {
|
||||
AllColumnsExcluding(excludedColumns.map(\.name))
|
||||
}
|
||||
}
|
||||
@@ -94,6 +94,7 @@
|
||||
/// - ``select(literal:as:)``
|
||||
/// - ``select(sql:arguments:)``
|
||||
/// - ``select(sql:arguments:as:)``
|
||||
/// - ``selectID()``
|
||||
/// - ``selectPrimaryKey(as:)``
|
||||
/// - ``with(_:)``
|
||||
///
|
||||
@@ -424,6 +425,40 @@ extension Table {
|
||||
all().selectPrimaryKey(as: type)
|
||||
}
|
||||
|
||||
/// Returns a request that selects the primary key.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let table = Table<Player>("player")
|
||||
///
|
||||
/// // SELECT id FROM player
|
||||
/// let request = try table.selectID()
|
||||
/// ```
|
||||
///
|
||||
/// **Important**: if the record type has an `ID` type that is an
|
||||
/// optional, such as `Int64?`, it is recommended to prefer
|
||||
/// ``selectPrimaryKey(as:)`` instead:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: Identifiable {
|
||||
/// var id: Int64?
|
||||
/// }
|
||||
///
|
||||
/// let table = Table<Player>("player")
|
||||
///
|
||||
/// // NOT RECOMMENDED: Set<Int64?>
|
||||
/// let ids = try table.selectID().fetchSet(db)
|
||||
///
|
||||
/// // BETTER: Set<Int64>
|
||||
/// let ids = try table.selectPrimaryKey(as: Int64.self).fetchSet(db)
|
||||
/// ```
|
||||
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
|
||||
where RowDecoder: Identifiable
|
||||
{
|
||||
all().selectID()
|
||||
}
|
||||
|
||||
/// Returns a request with the provided result columns appended to the
|
||||
/// table columns.
|
||||
///
|
||||
|
||||
@@ -153,15 +153,50 @@ final class SQLGenerationContext {
|
||||
return nil
|
||||
}
|
||||
|
||||
func columnCount(in tableName: String) throws -> Int {
|
||||
/// Return the number of columns in the table or CTE identified
|
||||
/// by `tableName`.
|
||||
///
|
||||
/// - parameter tableName: The table name.
|
||||
/// - parameter excludedColumns: The eventual set of excluded columns.
|
||||
func columnCount(
|
||||
in tableName: String,
|
||||
excluding excludedColumns: Set<CaseInsensitiveIdentifier>
|
||||
) throws -> Int {
|
||||
if let cte = ownCTEs[tableName.lowercased()] {
|
||||
return try cte.columnCount(db)
|
||||
if excludedColumns.isEmpty {
|
||||
return try cte.columnCount(db)
|
||||
} else {
|
||||
fatalError("Not implemented: counting CTE columns with excluded columns")
|
||||
}
|
||||
}
|
||||
switch parent {
|
||||
case let .context(context):
|
||||
return try context.columnCount(in: tableName)
|
||||
return try context.columnCount(in: tableName, excluding: excludedColumns)
|
||||
case let .none(db: db, argumentsSink: _):
|
||||
return try db.columns(in: tableName).count
|
||||
if excludedColumns.isEmpty {
|
||||
return try db.columns(in: tableName).count
|
||||
} else {
|
||||
return try db
|
||||
.columns(in: tableName)
|
||||
.filter { !excludedColumns.contains(CaseInsensitiveIdentifier(rawValue: $0.name)) }
|
||||
.count
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the names of the columns in the table or CTE identified
|
||||
/// by `tableName`.
|
||||
///
|
||||
/// - parameter tableName: The table name.
|
||||
func columnNames(in tableName: String) throws -> [String] {
|
||||
if ownCTEs[tableName.lowercased()] != nil {
|
||||
fatalError("Not implemented: extracing CTE column names")
|
||||
}
|
||||
switch parent {
|
||||
case let .context(context):
|
||||
return try context.columnNames(in: tableName)
|
||||
case let .none(db: db, argumentsSink: _):
|
||||
return try db.columns(in: tableName).map(\.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
let region = try prefetchedRegion(
|
||||
db,
|
||||
associations: prefetchedAssociations,
|
||||
from: relation.source.tableName)
|
||||
from: relation.source.associationOriginTable ?? relation.source.tableName)
|
||||
statement.databaseRegion.formUnion(region)
|
||||
}
|
||||
|
||||
@@ -235,7 +235,11 @@ struct SQLQueryGenerator: Refinable {
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
|
||||
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
|
||||
return try makeStatement(
|
||||
db, sql: sql,
|
||||
arguments: context.arguments,
|
||||
returning: selection,
|
||||
from: relation.source.tableName)
|
||||
|
||||
case .unique:
|
||||
return try makeTrivialDeleteStatement(db, selection: selection)
|
||||
@@ -264,7 +268,11 @@ struct SQLQueryGenerator: Refinable {
|
||||
sql += try selectPrimaryKey.requestSQL(subqueryContext)
|
||||
sql += ")"
|
||||
|
||||
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
|
||||
return try makeStatement(
|
||||
db, sql: sql,
|
||||
arguments: context.arguments,
|
||||
returning: selection,
|
||||
from: tableName)
|
||||
}
|
||||
|
||||
/// Returns an `UPDATE` statement, with `RETURNING` clause if `selection`
|
||||
@@ -323,7 +331,11 @@ struct SQLQueryGenerator: Refinable {
|
||||
sql += " LIMIT " + limit.sql
|
||||
}
|
||||
|
||||
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
|
||||
return try makeStatement(
|
||||
db, sql: sql,
|
||||
arguments: context.arguments,
|
||||
returning: selection,
|
||||
from: relation.source.tableName)
|
||||
|
||||
case .unique:
|
||||
return try makeTrivialUpdateStatement(
|
||||
@@ -380,7 +392,11 @@ struct SQLQueryGenerator: Refinable {
|
||||
sql += try selectPrimaryKey.requestSQL(subqueryContext)
|
||||
sql += ")"
|
||||
|
||||
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
|
||||
return try makeStatement(
|
||||
db, sql: sql,
|
||||
arguments: context.arguments,
|
||||
returning: selection,
|
||||
from: tableName)
|
||||
}
|
||||
|
||||
// Support for the RETURNING clause
|
||||
@@ -388,7 +404,8 @@ struct SQLQueryGenerator: Refinable {
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments,
|
||||
returning selection: [any SQLSelectable])
|
||||
returning selection: [any SQLSelectable],
|
||||
from tableName: String)
|
||||
throws -> Statement
|
||||
{
|
||||
if selection.isEmpty {
|
||||
@@ -396,12 +413,17 @@ struct SQLQueryGenerator: Refinable {
|
||||
statement.arguments = arguments
|
||||
return statement
|
||||
} else {
|
||||
let context = SQLGenerationContext(db)
|
||||
// Generate the RETURNING clause by turning selection into SQL.
|
||||
// Make sure the selection is qualified with a table alias, so
|
||||
// that selectables such as `.allColumns(excluding:)` can query
|
||||
// the database about the database table.
|
||||
let alias = TableAlias(tableName: tableName)
|
||||
let context = SQLGenerationContext(db, aliases: [alias])
|
||||
var sql = sql
|
||||
var arguments = arguments
|
||||
sql += " RETURNING "
|
||||
sql += try selection
|
||||
.map { try $0.sqlSelection.sql(context) }
|
||||
.map { try $0.sqlSelection.qualified(with: alias).sql(context) }
|
||||
.joined(separator: ", ")
|
||||
arguments += context.arguments
|
||||
let statement = try db.makeStatement(sql: sql)
|
||||
@@ -719,9 +741,15 @@ private struct SQLQualifiedSource {
|
||||
var tableName: String
|
||||
var alias: TableAlias
|
||||
|
||||
/// When not nil, use this table name instead of `tableName` when looking
|
||||
/// for foreign keys on this source. This string is not nil when an
|
||||
/// `SQLRelation` has been turned into a common table expression.
|
||||
var associationOriginTable: String?
|
||||
|
||||
init(_ source: SQLSource) {
|
||||
self.tableName = source.tableName
|
||||
self.alias = source.alias ?? TableAlias(tableName: source.tableName)
|
||||
self.associationOriginTable = source.associationOriginTable
|
||||
assert(alias.tableName == tableName)
|
||||
}
|
||||
|
||||
|
||||
@@ -67,7 +67,12 @@ extension SQLInterpolation {
|
||||
/// let player: Player = ...
|
||||
/// let request: SQLRequest<Player> = "SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p"
|
||||
public mutating func appendInterpolation(columnsOf recordType: (some TableRecord).Type, tableAlias: String? = nil) {
|
||||
let alias = TableAlias(name: tableAlias ?? recordType.databaseTableName)
|
||||
// Make sure we provide the tableName, so that we can interpolate
|
||||
// the columns of a type whose `databaseSelection` contains an
|
||||
// instance of `AllColumnsExcluding`.
|
||||
let alias = TableAlias(
|
||||
tableName: recordType.databaseTableName,
|
||||
userName: tableAlias ?? recordType.databaseTableName)
|
||||
elements.append(contentsOf: recordType.databaseSelection
|
||||
.map { CollectionOfOne(.selection($0.sqlSelection.qualified(with: alias))) }
|
||||
.joined(separator: CollectionOfOne(.sql(", "))))
|
||||
@@ -79,7 +84,7 @@ extension SQLInterpolation {
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT \(AllColumns()) FROM player
|
||||
/// SELECT \(.allColumns) FROM player
|
||||
/// """
|
||||
public mutating func appendInterpolation(_ selection: some SQLSelectable) {
|
||||
elements.append(.selection(selection.sqlSelection))
|
||||
@@ -89,7 +94,7 @@ extension SQLInterpolation {
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT \(AllColumns()) FROM player
|
||||
/// SELECT \(.allColumns) FROM player
|
||||
/// """
|
||||
@_disfavoredOverload
|
||||
public mutating func appendInterpolation(_ selection: (any SQLSelectable)?) {
|
||||
|
||||
@@ -370,6 +370,32 @@ public final class ColumnDefinition {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// To remove the generated columns from the selection of record types,
|
||||
/// define their `databaseSelection`:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: Codable {
|
||||
/// // No property for `totalScore`
|
||||
/// var id: Int64
|
||||
/// var score: Int
|
||||
/// var bonus: Int
|
||||
/// }
|
||||
///
|
||||
/// extension Player: FetchableRecord, PersistableRecord {
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// // Option 1
|
||||
/// [Column("id"), Column("score"), Column("bonus")]
|
||||
/// // Option 2
|
||||
/// [.allColumns(excluding: ["totalScore"])]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id, score, bonus FROM player
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -409,6 +435,32 @@ public final class ColumnDefinition {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// To remove the generated columns from the selection of record types,
|
||||
/// define their `databaseSelection`:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: Codable {
|
||||
/// // No property for `totalScore`
|
||||
/// var id: Int64
|
||||
/// var score: Int
|
||||
/// var bonus: Int
|
||||
/// }
|
||||
///
|
||||
/// extension Player: FetchableRecord, PersistableRecord {
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// // Option 1
|
||||
/// [Column("id"), Column("score"), Column("bonus")]
|
||||
/// // Option 2
|
||||
/// [.allColumns(excluding: ["totalScore"])]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id, score, bonus FROM player
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -447,6 +499,32 @@ public final class ColumnDefinition {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// To remove the generated columns from the selection of record types,
|
||||
/// define their `databaseSelection`:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: Codable {
|
||||
/// // No property for `totalScore`
|
||||
/// var id: Int64
|
||||
/// var score: Int
|
||||
/// var bonus: Int
|
||||
/// }
|
||||
///
|
||||
/// extension Player: FetchableRecord, PersistableRecord {
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// // Option 1
|
||||
/// [Column("id"), Column("score"), Column("bonus")]
|
||||
/// // Option 2
|
||||
/// [.allColumns(excluding: ["totalScore"])]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id, score, bonus FROM player
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -487,6 +565,32 @@ public final class ColumnDefinition {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// To remove the generated columns from the selection of record types,
|
||||
/// define their `databaseSelection`:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: Codable {
|
||||
/// // No property for `totalScore`
|
||||
/// var id: Int64
|
||||
/// var score: Int
|
||||
/// var bonus: Int
|
||||
/// }
|
||||
///
|
||||
/// extension Player: FetchableRecord, PersistableRecord {
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// // Option 1
|
||||
/// [Column("id"), Column("score"), Column("bonus")]
|
||||
/// // Option 2
|
||||
/// [.allColumns(excluding: ["totalScore"])]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT id, score, bonus FROM player
|
||||
/// let players = try dbQueue.read { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
|
||||
///
|
||||
/// - parameters:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/// The protocol for SQLite virtual table modules.
|
||||
///
|
||||
/// The protocol can define a DSL for the
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` `Database` method:
|
||||
/// ``Database/create(virtualTable:options:using:_:)`` `Database` method:
|
||||
///
|
||||
/// ```swift
|
||||
/// let module = ...
|
||||
@@ -20,7 +20,7 @@
|
||||
/// - ``VirtualTableConfiguration``
|
||||
public protocol VirtualTableModule {
|
||||
/// The type of the argument in the
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` closure.
|
||||
/// ``Database/create(virtualTable:options:using:_:)`` closure.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -35,7 +35,7 @@ public protocol VirtualTableModule {
|
||||
var moduleName: String { get }
|
||||
|
||||
/// Returns a table definition that is passed as the argument in the
|
||||
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` closure.
|
||||
/// ``Database/create(virtualTable:options:using:_:)`` closure.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -54,10 +54,29 @@ public protocol VirtualTableModule {
|
||||
func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
|
||||
}
|
||||
|
||||
// TODO: Question the existence of this API. VirtualTableConfiguration was
|
||||
// never able to be used by user-defined VirtualTableModule types, because
|
||||
// `ifNotExists` has never been public.
|
||||
public struct VirtualTableConfiguration {
|
||||
/// If true, existing objects must not be replaced, or generate any error
|
||||
/// (even if they do not match the objects that would be created otherwise.)
|
||||
var ifNotExists: Bool
|
||||
|
||||
/// If true, new objects must be created in the temp schema.
|
||||
var temporary: Bool
|
||||
}
|
||||
|
||||
/// Virtual table creation options.
|
||||
public struct VirtualTableOptions: OptionSet, Sendable {
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) { self.rawValue = rawValue }
|
||||
|
||||
/// Only creates the table if it does not already exist.
|
||||
public static let ifNotExists = VirtualTableOptions(rawValue: 1 << 0)
|
||||
|
||||
/// Creates a temporary table.
|
||||
public static let temporary = VirtualTableOptions(rawValue: 1 << 1)
|
||||
}
|
||||
|
||||
extension Database {
|
||||
@@ -77,18 +96,24 @@ extension Database {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - options: Table creation options.
|
||||
/// - module: The name of an SQLite virtual table module.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
|
||||
public func create(
|
||||
virtualTable name: String,
|
||||
options: VirtualTableOptions = [],
|
||||
using module: String
|
||||
) throws {
|
||||
var chunks: [String] = []
|
||||
chunks.append("CREATE VIRTUAL TABLE")
|
||||
if ifNotExists {
|
||||
if options.contains(.ifNotExists) {
|
||||
chunks.append("IF NOT EXISTS")
|
||||
}
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
if options.contains(.temporary) {
|
||||
chunks.append("temp.\(name.quotedDatabaseIdentifier)")
|
||||
} else {
|
||||
chunks.append(name.quotedDatabaseIdentifier)
|
||||
}
|
||||
chunks.append("USING")
|
||||
chunks.append(module)
|
||||
let sql = chunks.joined(separator: " ")
|
||||
@@ -114,21 +139,21 @@ extension Database {
|
||||
///
|
||||
/// - parameters:
|
||||
/// - tableName: The table name.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - options: Table creation options.
|
||||
/// - module: a virtual module.
|
||||
/// - body: An optional closure that defines the virtual table.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func create<Module: VirtualTableModule>(
|
||||
virtualTable tableName: String,
|
||||
ifNotExists: Bool = false,
|
||||
options: VirtualTableOptions = [],
|
||||
using module: Module,
|
||||
_ body: ((Module.TableDefinition) throws -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
// Define virtual table
|
||||
let configuration = VirtualTableConfiguration(ifNotExists: ifNotExists)
|
||||
let configuration = VirtualTableConfiguration(
|
||||
ifNotExists: options.contains(.ifNotExists),
|
||||
temporary: options.contains(.temporary))
|
||||
let definition = module.makeTableDefinition(configuration: configuration)
|
||||
if let body {
|
||||
try body(definition)
|
||||
@@ -137,10 +162,14 @@ extension Database {
|
||||
// Create virtual table
|
||||
var chunks: [String] = []
|
||||
chunks.append("CREATE VIRTUAL TABLE")
|
||||
if ifNotExists {
|
||||
if options.contains(.ifNotExists) {
|
||||
chunks.append("IF NOT EXISTS")
|
||||
}
|
||||
chunks.append(tableName.quotedDatabaseIdentifier)
|
||||
if options.contains(.temporary) {
|
||||
chunks.append("temp.\(tableName.quotedDatabaseIdentifier)")
|
||||
} else {
|
||||
chunks.append(tableName.quotedDatabaseIdentifier)
|
||||
}
|
||||
chunks.append("USING")
|
||||
let arguments = try module.moduleArguments(for: definition, in: self)
|
||||
if arguments.isEmpty {
|
||||
@@ -156,4 +185,78 @@ extension Database {
|
||||
return .commit
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a virtual database table.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // CREATE VIRTUAL TABLE vocabulary USING spellfix1
|
||||
/// try db.create(virtualTable: "vocabulary", using: "spellfix1")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html>
|
||||
///
|
||||
/// - warning: This is a legacy interface that is preserved for backwards
|
||||
/// compatibility. Use of this interface is not recommended: prefer
|
||||
/// ``create(virtualTable:options:using:)`` instead.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The table name.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - module: The name of an SQLite virtual table module.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@_disfavoredOverload
|
||||
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
|
||||
try create(
|
||||
virtualTable: name,
|
||||
options: ifNotExists ? .ifNotExists : [],
|
||||
using: module)
|
||||
}
|
||||
|
||||
/// Creates a virtual database table.
|
||||
///
|
||||
/// The type of the argument of the `body` function depends on the type of
|
||||
/// the `module` argument: refer to this module's documentation.
|
||||
///
|
||||
/// You can use this method to create full-text virtual tables:
|
||||
///
|
||||
/// ```swift
|
||||
/// try db.create(virtualTable: "book", using: FTS4()) { t in
|
||||
/// t.column("title")
|
||||
/// t.column("author")
|
||||
/// t.column("body")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html>
|
||||
///
|
||||
/// - warning: This is a legacy interface that is preserved for backwards
|
||||
/// compatibility. Use of this interface is not recommended: prefer
|
||||
/// ``create(virtualTable:options:using:_:)`` instead.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - tableName: The table name.
|
||||
/// - ifNotExists: If false (the default), an error is thrown if the
|
||||
/// table already exists. Otherwise, the table is created unless it
|
||||
/// already exists.
|
||||
/// - module: a virtual module.
|
||||
/// - body: An optional closure that defines the virtual table.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@_disfavoredOverload
|
||||
public func create<Module: VirtualTableModule>(
|
||||
virtualTable tableName: String,
|
||||
ifNotExists: Bool = false,
|
||||
using module: Module,
|
||||
_ body: ((Module.TableDefinition) throws -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
try create(
|
||||
virtualTable: tableName,
|
||||
options: ifNotExists ? .ifNotExists : [],
|
||||
using: module,
|
||||
body)
|
||||
}
|
||||
}
|
||||
@@ -251,6 +251,36 @@ extension TableRecord {
|
||||
all().selectPrimaryKey(as: type)
|
||||
}
|
||||
|
||||
/// Returns a request that selects the primary key.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT id FROM player
|
||||
/// let request = try Player.selectID()
|
||||
/// ```
|
||||
///
|
||||
/// **Important**: if the record type has an `ID` type that is an
|
||||
/// optional, such as `Int64?`, it is recommended to prefer
|
||||
/// ``selectPrimaryKey(as:)`` instead:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: Identifiable {
|
||||
/// var id: Int64?
|
||||
/// }
|
||||
///
|
||||
/// // NOT RECOMMENDED: Set<Int64?>
|
||||
/// let ids = try Player.selectID().fetchSet(db)
|
||||
///
|
||||
/// // BETTER: Set<Int64>
|
||||
/// let ids = try Player.selectPrimaryKey(as: Int64.self).fetchSet(db)
|
||||
/// ```
|
||||
public static func selectID() -> QueryInterfaceRequest<Self.ID>
|
||||
where Self: Identifiable
|
||||
{
|
||||
all().selectID()
|
||||
}
|
||||
|
||||
/// Returns a request with the provided result columns appended to the
|
||||
/// record selection.
|
||||
///
|
||||
|
||||
@@ -524,7 +524,12 @@ public enum DatabaseDataEncodingStrategy: Sendable {
|
||||
/// var creationDate: Date
|
||||
/// }
|
||||
/// ```
|
||||
public enum DatabaseDateEncodingStrategy: Sendable {
|
||||
public enum DatabaseDateEncodingStrategy: @unchecked Sendable {
|
||||
// @unchecked Sendable because of `DateFormatter`, which lost its
|
||||
// `Sendable` conformance with Xcode 16.3 beta. See
|
||||
// <https://github.com/swiftlang/swift/issues/78635>.
|
||||
// TODO: remove @unchecked when the compiler issue is fixed.
|
||||
|
||||
/// The strategy that uses formatting from the Date structure.
|
||||
///
|
||||
/// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the
|
||||
|
||||
@@ -929,7 +929,12 @@ public enum DatabaseDataDecodingStrategy: Sendable {
|
||||
/// var name: String
|
||||
/// var registrationDate: Date // decoded from epoch timestamp
|
||||
/// }
|
||||
public enum DatabaseDateDecodingStrategy: Sendable {
|
||||
public enum DatabaseDateDecodingStrategy: @unchecked Sendable {
|
||||
// @unchecked Sendable because of `DateFormatter`, which lost its
|
||||
// `Sendable` conformance with Xcode 16.3 beta. See
|
||||
// <https://github.com/swiftlang/swift/issues/78635>.
|
||||
// TODO: remove @unchecked when the compiler issue is fixed.
|
||||
|
||||
/// The strategy that uses formatting from the Date structure.
|
||||
///
|
||||
/// It decodes numeric values as a number of seconds since Epoch
|
||||
|
||||
@@ -249,12 +249,17 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
statement.setUncheckedArguments(arguments)
|
||||
return statement
|
||||
} else {
|
||||
let context = SQLGenerationContext(db)
|
||||
// Generate the RETURNING clause by turning selection into SQL.
|
||||
// Make sure the selection is qualified with a table alias, so
|
||||
// that selectables such as `.allColumns(excluding:)` can query
|
||||
// the database about the database table.
|
||||
let alias = TableAlias(tableName: databaseTableName)
|
||||
let context = SQLGenerationContext(db, aliases: [alias])
|
||||
var sql = sql
|
||||
var arguments = arguments
|
||||
sql += " RETURNING "
|
||||
sql += try selection
|
||||
.map { try $0.sqlSelection.sql(context) }
|
||||
.map { try $0.sqlSelection.qualified(with: alias).sql(context) }
|
||||
.joined(separator: ", ")
|
||||
arguments += context.arguments
|
||||
let statement = try db.internalCachedStatement(sql: sql)
|
||||
|
||||
@@ -107,7 +107,7 @@ open class Record {
|
||||
/// try PartialPlayer.fetchAll(db)
|
||||
/// ```
|
||||
open class var databaseSelection: [any SQLSelectable] {
|
||||
[AllColumns()]
|
||||
[.allColumns]
|
||||
}
|
||||
|
||||
/// Encodes the record into the provided persistence container.
|
||||
|
||||
@@ -98,6 +98,7 @@ import Foundation
|
||||
/// - ``select(literal:as:)``
|
||||
/// - ``select(sql:arguments:)``
|
||||
/// - ``select(sql:arguments:as:)``
|
||||
/// - ``selectID()``
|
||||
/// - ``selectPrimaryKey(as:)``
|
||||
/// - ``with(_:)``
|
||||
///
|
||||
@@ -134,8 +135,9 @@ public protocol TableRecord {
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// // This is the default
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// [AllColumns()]
|
||||
/// [.allColumns]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
@@ -146,11 +148,20 @@ public protocol TableRecord {
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Team: TableRecord {
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// [.allColumns(excluding: ["generatedColumn"])]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// try Player.fetchAll(db)
|
||||
///
|
||||
/// // SELECT id, name FROM player
|
||||
/// try PartialPlayer.fetchAll(db)
|
||||
///
|
||||
/// // SELECT id, name, color FROM team
|
||||
/// try Team.fetchAll(db)
|
||||
/// ```
|
||||
///
|
||||
/// > Important: Make sure the `databaseSelection` property is
|
||||
@@ -168,7 +179,7 @@ public protocol TableRecord {
|
||||
/// > // concurrency-safe because non-'Sendable' type
|
||||
/// > // '[any SQLSelectable]' may have shared
|
||||
/// > // mutable state.
|
||||
/// > static let databaseSelection: [any SQLSelectable] = [AllColumns()]
|
||||
/// > static let databaseSelection: [any SQLSelectable] = [.allColumns]
|
||||
/// > ```
|
||||
static var databaseSelection: [any SQLSelectable] { get }
|
||||
}
|
||||
@@ -215,9 +226,9 @@ extension TableRecord {
|
||||
defaultDatabaseTableName
|
||||
}
|
||||
|
||||
/// The default selection is all columns: `[AllColumns()]`.
|
||||
/// The default selection is all columns: `[.allColumns]`.
|
||||
public static var databaseSelection: [any SQLSelectable] {
|
||||
[AllColumns()]
|
||||
[.allColumns]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -744,13 +755,10 @@ extension TableRecord {
|
||||
/// any error that prevented the `RecordError` from being constructed.
|
||||
public static func recordNotFound(_ db: Database, key: some DatabaseValueConvertible) -> any Error {
|
||||
do {
|
||||
let primaryKey = try db.primaryKey(databaseTableName)
|
||||
GRDBPrecondition(
|
||||
primaryKey.columns.count == 1,
|
||||
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
|
||||
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
|
||||
return RecordError.recordNotFound(
|
||||
databaseTableName: databaseTableName,
|
||||
key: [primaryKey.columns[0]: key.databaseValue])
|
||||
key: [column: key.databaseValue])
|
||||
} catch {
|
||||
return error
|
||||
}
|
||||
|
||||
@@ -63,7 +63,7 @@ extension Inflections {
|
||||
inflections.plural("^(ax|test)is$", "$1es")
|
||||
inflections.plural("(octop|vir)us$", "$1i")
|
||||
inflections.plural("(octop|vir)i$", "$1i")
|
||||
inflections.plural("(alias|status)$", "$1es")
|
||||
inflections.plural("(alias|bias|canvas|focus|gas|lens|status)$", "$1es")
|
||||
inflections.plural("(bu)s$", "$1ses")
|
||||
inflections.plural("(buffal|tomat|her)o$", "$1oes")
|
||||
inflections.plural("([ti])um$", "$1a")
|
||||
@@ -102,13 +102,12 @@ extension Inflections {
|
||||
inflections.singular("(cris|test)(is|es)$", "$1is")
|
||||
inflections.singular("^(a)x[ie]s$", "$1xis")
|
||||
inflections.singular("(octop|vir)(us|i)$", "$1us")
|
||||
inflections.singular("(alias|status)(es)?$", "$1")
|
||||
inflections.singular("(alias|bias|canvas|focus|gas|lens|status)(es)?$", "$1")
|
||||
inflections.singular("^(ox)en$", "$1")
|
||||
inflections.singular("(vert|ind)ices$", "$1ex")
|
||||
inflections.singular("(matr)ices$", "$1ix")
|
||||
inflections.singular("(quiz)zes$", "$1")
|
||||
inflections.singular("(database)s$", "$1")
|
||||
inflections.singular("(canvas)(es)?$", "$1")
|
||||
|
||||
inflections.uncountableWords([
|
||||
"advice",
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
#if !canImport(Darwin)
|
||||
@preconcurrency import Dispatch
|
||||
#endif
|
||||
import Foundation
|
||||
|
||||
// MARK: - Public
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Copyright (C) 2015-2024 Gwendal Roué
|
||||
Copyright (C) 2015-2025 Gwendal Roué
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
|
||||
@@ -10,18 +10,18 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://developer.apple.com/swift/"><img alt="Swift 5.7" src="https://img.shields.io/badge/swift-5.7-orange.svg?style=flat"></a>
|
||||
<a href="https://developer.apple.com/swift/"><img alt="Swift 6" src="https://img.shields.io/badge/swift-6-orange.svg?style=flat"></a>
|
||||
<a href="https://github.com/groue/GRDB.swift/blob/master/LICENSE"><img alt="License" src="https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000"></a>
|
||||
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
|
||||
</p>
|
||||
|
||||
**Latest release**: September 29, 2024 • [version 7.0.0-beta.2](https://github.com/groue/GRDB.swift/tree/v7.0.0-beta.2) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
|
||||
**Latest release**: February 23, 2025 • [version 7.3.0](https://github.com/groue/GRDB.swift/tree/v7.3.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
|
||||
|
||||
**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ • SQLite 3.20.0+ • Swift 6+ / Xcode 16+
|
||||
|
||||
**Contact**:
|
||||
|
||||
- Release announcements and usage tips: follow [@groue](http://twitter.com/groue) on Twitter, [@groue@hachyderm.io](https://hachyderm.io/@groue) on Mastodon.
|
||||
- Release announcements and usage tips: follow [@groue@hachyderm.io](https://hachyderm.io/@groue) on Mastodon.
|
||||
- Report bugs in a [Github issue](https://github.com/groue/GRDB.swift/issues/new). Make sure you check the [existing issues](https://github.com/groue/GRDB.swift/issues?q=is%3Aopen) first.
|
||||
- A question? Looking for advice? Do you wonder how to contribute? Fancy a chat? Go to the [GitHub discussions](https://github.com/groue/GRDB.swift/discussions), or the [GRDB forums](https://forums.swift.org/c/related-projects/grdb).
|
||||
|
||||
@@ -281,7 +281,7 @@ Documentation
|
||||
|
||||
#### Reference
|
||||
|
||||
- 📖 [GRDB Reference](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/)
|
||||
- 📖 [GRDB Reference](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/)
|
||||
|
||||
#### Getting Started
|
||||
|
||||
@@ -295,7 +295,7 @@ Documentation
|
||||
#### Records and the Query Interface
|
||||
|
||||
- [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies
|
||||
- [Query Interface](#the-query-interface): A swift way to generate SQL • [create tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) • [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md)
|
||||
- [Query Interface](#the-query-interface): A swift way to generate SQL • [create tables, indexes, etc](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) • [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md)
|
||||
|
||||
#### Application Tools
|
||||
|
||||
@@ -315,10 +315,10 @@ Documentation
|
||||
- [Error Handling](#error-handling)
|
||||
- [Unicode](#unicode)
|
||||
- [Memory Management](#memory-management)
|
||||
- [Data Protection](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections)
|
||||
- [Data Protection](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections)
|
||||
- :bulb: [Migrating From GRDB 6 to GRDB 7](Documentation/Documentation/GRDB7MigrationGuide.md)
|
||||
- :bulb: [Why Adopt GRDB?](Documentation/WhyAdoptGRDB.md)
|
||||
- :bulb: [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
|
||||
- :bulb: [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices)
|
||||
|
||||
#### Companion Libraries
|
||||
|
||||
@@ -415,7 +415,7 @@ The differences are:
|
||||
|
||||
**If you are not sure, choose [`DatabaseQueue`].** You will always be able to switch to [`DatabasePool`] later.
|
||||
|
||||
For more information and tips when opening connections, see [Database Connections](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections).
|
||||
For more information and tips when opening connections, see [Database Connections](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections).
|
||||
|
||||
|
||||
SQLite API
|
||||
@@ -441,14 +441,14 @@ Advanced topics:
|
||||
|
||||
- [Prepared Statements]
|
||||
- [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates)
|
||||
- [Database Schema Introspection](#database-schema-introspection)
|
||||
- [Row Adapters](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter)
|
||||
- [Database Schema Introspection](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschemaintrospection)
|
||||
- [Row Adapters](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter)
|
||||
- [Raw SQLite Pointers](#raw-sqlite-pointers)
|
||||
|
||||
|
||||
## Executing Updates
|
||||
|
||||
Once granted with a [database connection], the [`execute(sql:arguments:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/execute(sql:arguments:)) method executes the SQL statements that do not return any database row, such as `CREATE TABLE`, `INSERT`, `DELETE`, `ALTER`, etc.
|
||||
Once granted with a [database connection], the [`execute(sql:arguments:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/execute(sql:arguments:)) method executes the SQL statements that do not return any database row, such as `CREATE TABLE`, `INSERT`, `DELETE`, `ALTER`, etc.
|
||||
|
||||
For example:
|
||||
|
||||
@@ -474,7 +474,7 @@ try dbQueue.write { db in
|
||||
|
||||
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [`StatementArguments`] for a detailed documentation of SQLite arguments.
|
||||
|
||||
You can also embed query arguments right into your SQL queries, with [`execute(literal:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/execute(literal:)), as in the example below. See [SQL Interpolation] for more details.
|
||||
You can also embed query arguments right into your SQL queries, with [`execute(literal:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/execute(literal:)), as in the example below. See [SQL Interpolation] for more details.
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
@@ -526,7 +526,7 @@ try db.execute(literal: """
|
||||
|
||||
When you want to make sure that a single statement is executed, use a prepared [`Statement`].
|
||||
|
||||
**After an INSERT statement**, you can get the row ID of the inserted row with [`lastInsertedRowID`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/lastinsertedrowid):
|
||||
**After an INSERT statement**, you can get the row ID of the inserted row with [`lastInsertedRowID`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/lastinsertedrowid):
|
||||
|
||||
```swift
|
||||
try db.execute(
|
||||
@@ -626,7 +626,7 @@ try Row.fetchOne(...) // Row?
|
||||
|
||||
### Cursors
|
||||
|
||||
📖 [`Cursor`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/cursor)
|
||||
📖 [`Cursor`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/cursor)
|
||||
|
||||
**Whenever you consume several rows from the database, you can fetch an Array, a Set, or a Cursor**.
|
||||
|
||||
@@ -712,7 +712,7 @@ try dbQueue.read { db in
|
||||
let dictionary = try Dictionary(uniqueKeysWithValues: cursor)
|
||||
```
|
||||
|
||||
- **Cursors adopt the [Cursor](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/cursor) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
|
||||
- **Cursors adopt the [Cursor](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/cursor) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
|
||||
|
||||
```swift
|
||||
// Prints all Github links
|
||||
@@ -753,7 +753,7 @@ If you don't see, or don't care about the difference, use arrays. If you care ab
|
||||
- [Column Values](#column-values)
|
||||
- [DatabaseValue](#databasevalue)
|
||||
- [Rows as Dictionaries](#rows-as-dictionaries)
|
||||
- 📖 [`Row`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/row)
|
||||
- 📖 [`Row`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/row)
|
||||
|
||||
|
||||
#### Fetching Rows
|
||||
@@ -841,6 +841,13 @@ row[...] as Int?
|
||||
> if let int = row[...] as Int? { ... } // GOOD
|
||||
> ```
|
||||
|
||||
> **Warning**: avoid nil-coalescing row values, and prefer the `coalesce` method instead:
|
||||
>
|
||||
> ```swift
|
||||
> let name: String? = row["nickname"] ?? row["name"] // BAD - doesn't work
|
||||
> let name: String? = row.coalesce(["nickname", "name"]) // GOOD
|
||||
> ```
|
||||
|
||||
Generally speaking, you can extract the type you need, provided it can be converted from the underlying SQLite value:
|
||||
|
||||
- **Successful conversions include:**
|
||||
@@ -921,7 +928,7 @@ Generally speaking, you can extract the type you need, provided it can be conver
|
||||
|
||||
#### DatabaseValue
|
||||
|
||||
📖 [`DatabaseValue`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalue)
|
||||
📖 [`DatabaseValue`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasevalue)
|
||||
|
||||
**`DatabaseValue` is an intermediate type between SQLite and your values, which gives information about the raw value stored in the database.**
|
||||
|
||||
@@ -947,7 +954,7 @@ case .blob(let data): print("Data: \(data)")
|
||||
}
|
||||
```
|
||||
|
||||
You can extract regular [values](#values) (Bool, Int, String, Date, Swift enums, etc.) from `DatabaseValue` with the [fromDatabaseValue()](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible/fromdatabasevalue(_:)-21zzv) method:
|
||||
You can extract regular [values](#values) (Bool, Int, String, Date, Swift enums, etc.) from `DatabaseValue` with the [fromDatabaseValue()](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasevalueconvertible/fromdatabasevalue(_:)-21zzv) method:
|
||||
|
||||
```swift
|
||||
let dbValue: DatabaseValue = row["bookCount"]
|
||||
@@ -1033,7 +1040,7 @@ See the documentation of [`Dictionary.init(_:uniquingKeysWith:)`](https://develo
|
||||
|
||||
### Value Queries
|
||||
|
||||
📖 [`DatabaseValueConvertible`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible)
|
||||
📖 [`DatabaseValueConvertible`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasevalueconvertible)
|
||||
|
||||
**Instead of rows, you can directly fetch values.** There are many supported [value types](#values) (Bool, Int, String, Date, Swift enums, etc.).
|
||||
|
||||
@@ -1104,7 +1111,7 @@ GRDB ships with built-in support for the following value types:
|
||||
|
||||
- Generally speaking, all types that adopt the [`DatabaseValueConvertible`] protocol.
|
||||
|
||||
Values can be used as [statement arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
|
||||
Values can be used as [statement arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let url: URL = ...
|
||||
@@ -1430,7 +1437,7 @@ SELECT maxLength(name) FROM player; -- custom aggregate
|
||||
|
||||
### Custom SQL Functions
|
||||
|
||||
📖 [`DatabaseFunction`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasefunction)
|
||||
📖 [`DatabaseFunction`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasefunction)
|
||||
|
||||
A *function* argument takes an array of [DatabaseValue](#databasevalue), and returns any valid [value](#values) (Bool, Int, String, Date, Swift enums, etc.) The number of database values is guaranteed to be *argumentCount*.
|
||||
|
||||
@@ -1511,7 +1518,7 @@ Player.select(reverseString(nameColumn))
|
||||
|
||||
### Custom Aggregates
|
||||
|
||||
📖 [`DatabaseFunction`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasefunction), [`DatabaseAggregate`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseaggregate)
|
||||
📖 [`DatabaseFunction`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasefunction), [`DatabaseAggregate`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseaggregate)
|
||||
|
||||
Before registering a custom aggregate, you need to define a type that adopts the `DatabaseAggregate` protocol:
|
||||
|
||||
@@ -1589,41 +1596,6 @@ try Int.fetchOne(db, request) // Int?
|
||||
```
|
||||
|
||||
|
||||
## Database Schema Introspection
|
||||
|
||||
GRDB comes with a set of schema introspection methods:
|
||||
|
||||
```swift
|
||||
try dbQueue.read { db in
|
||||
// Bool, true if the table exists
|
||||
try db.tableExists("player")
|
||||
|
||||
// [ColumnInfo], the columns in the table
|
||||
try db.columns(in: "player")
|
||||
|
||||
// PrimaryKeyInfo
|
||||
try db.primaryKey("player")
|
||||
|
||||
// [ForeignKeyInfo], the foreign keys defined on the table
|
||||
try db.foreignKeys(on: "player")
|
||||
|
||||
// [IndexInfo], the indexes defined on the table
|
||||
try db.indexes(on: "player")
|
||||
|
||||
// Bool, true if column(s) is a unique key (primary key or unique index)
|
||||
try db.table("player", hasUniqueKey: ["email"])
|
||||
}
|
||||
|
||||
// Bool, true if argument is the name of an internal SQLite table
|
||||
Database.isSQLiteInternalTable(...)
|
||||
|
||||
// Bool, true if argument is the name of an internal GRDB table
|
||||
Database.isGRDBInternalTable(...)
|
||||
```
|
||||
|
||||
For more information, see [`tableExists(_:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/tableexists(_:)) and related methods.
|
||||
|
||||
|
||||
## Raw SQLite Pointers
|
||||
|
||||
**If not all SQLite APIs are exposed in GRDB, you can still use the [SQLite C Interface](https://www.sqlite.org/c3ref/intro.html) and call [SQLite C functions](https://www.sqlite.org/c3ref/funclist.html).**
|
||||
@@ -1671,14 +1643,14 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
Of course, you need to open a [database connection], and [create database tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) first.
|
||||
Of course, you need to open a [database connection], and [create database tables](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) first.
|
||||
|
||||
To define a record type, define a type and extend it with protocols that come with focused sets of features.
|
||||
|
||||
For example:
|
||||
|
||||
```
|
||||
struct Player: {
|
||||
```swift
|
||||
struct Player {
|
||||
var id: Int64
|
||||
var name: String
|
||||
var score: Int
|
||||
@@ -1695,7 +1667,7 @@ See some [examples of record definitions](#examples-of-record-definitions).
|
||||
|
||||
> Note: if you are familiar with Core Data's NSManagedObject or Realm's Object, you may experience a cultural shock: GRDB records are not uniqued, do not auto-update, and do not lazy-load. This is both a purpose, and a consequence of protocol-oriented programming.
|
||||
>
|
||||
> Tip: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide provides general guidance..
|
||||
> Tip: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) guide provides general guidance..
|
||||
>
|
||||
> Tip: See the [Demo Applications] for sample apps that uses records.
|
||||
|
||||
@@ -1897,7 +1869,7 @@ Details follow:
|
||||
|
||||
## FetchableRecord Protocol
|
||||
|
||||
📖 [`FetchableRecord`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/fetchablerecord)
|
||||
📖 [`FetchableRecord`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/fetchablerecord)
|
||||
|
||||
**The FetchableRecord protocol grants fetching methods to any type** that can be built from a database row:
|
||||
|
||||
@@ -1977,7 +1949,7 @@ See [fetching methods](#fetching-methods) for information about the `fetchCursor
|
||||
|
||||
## TableRecord Protocol
|
||||
|
||||
📖 [`TableRecord`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerecord)
|
||||
📖 [`TableRecord`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerecord)
|
||||
|
||||
**The TableRecord protocol** generates SQL for you:
|
||||
|
||||
@@ -2028,7 +2000,7 @@ TableRecord can also fetch deal with primary and unique keys: see [Fetching by K
|
||||
|
||||
## PersistableRecord Protocol
|
||||
|
||||
📖 [`EncodableRecord`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/encodablerecord), [`MutablePersistableRecord`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/mutablepersistablerecord), [`PersistableRecord`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/persistablerecord)
|
||||
📖 [`EncodableRecord`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/encodablerecord), [`MutablePersistableRecord`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/mutablepersistablerecord), [`PersistableRecord`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/persistablerecord)
|
||||
|
||||
**GRDB record types can create, update, and delete rows in the database.**
|
||||
|
||||
@@ -2459,7 +2431,7 @@ Here is a list with all the available [persistence callbacks], listed in the sam
|
||||
- `aroundDelete`
|
||||
- `didDelete`
|
||||
|
||||
For detailed information about each callback, check the [reference](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/mutablepersistablerecord/).
|
||||
For detailed information about each callback, check the [reference](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/mutablepersistablerecord/).
|
||||
|
||||
In the `MutablePersistableRecord` protocol, `willInsert` and `didInsert` are mutating methods. In `PersistableRecord`, they are not mutating.
|
||||
|
||||
@@ -2467,7 +2439,7 @@ In the `MutablePersistableRecord` protocol, `willInsert` and `didInsert` are mut
|
||||
>
|
||||
> **Warning**: Callbacks are only invoked from persistence methods called on record instances. Callbacks are not invoked when you call a type method, perform a batch operations, or execute raw SQL.
|
||||
>
|
||||
> **Warning**: When a `did***` callback is invoked, do not assume that the change is actually persisted on disk, because the database may still be inside an uncommitted transaction. When you need to handle transaction completions, use the [afterNextTransaction(onCommit:onRollback:)](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)). For example:
|
||||
> **Warning**: When a `did***` callback is invoked, do not assume that the change is actually persisted on disk, because the database may still be inside an uncommitted transaction. When you need to handle transaction completions, use the [afterNextTransaction(onCommit:onRollback:)](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)). For example:
|
||||
>
|
||||
> ```swift
|
||||
> struct PictureFile: PersistableRecord {
|
||||
@@ -2494,7 +2466,7 @@ struct Player: Identifiable, FetchableRecord, PersistableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
When `id` has a [database-compatible type](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible) (Int64, Int, String, UUID, ...), the `Identifiable` conformance unlocks type-safe record and request methods:
|
||||
When `id` has a [database-compatible type](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasevalueconvertible) (Int64, Int, String, UUID, ...), the `Identifiable` conformance unlocks type-safe record and request methods:
|
||||
|
||||
```swift
|
||||
let player = try Player.find(db, id: 1) // Player
|
||||
@@ -2673,7 +2645,7 @@ protocol EncodableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See [DatabaseColumnDecodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasecolumndecodingstrategy) and [DatabaseColumnEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasecolumnencodingstrategy/) to learn about all available strategies.
|
||||
See [DatabaseColumnDecodingStrategy](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasecolumndecodingstrategy) and [DatabaseColumnEncodingStrategy](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasecolumnencodingstrategy/) to learn about all available strategies.
|
||||
|
||||
|
||||
### Data, Date, and UUID Coding Strategies
|
||||
@@ -2697,7 +2669,7 @@ protocol EncodableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See [DatabaseDataDecodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedatadecodingstrategy/), [DatabaseDateDecodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedatedecodingstrategy/), [DatabaseDataEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedataencodingstrategy/), [DatabaseDateEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasedateencodingstrategy/), and [DatabaseUUIDEncodingStrategy](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseuuidencodingstrategy/) to learn about all available strategies.
|
||||
See [DatabaseDataDecodingStrategy](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasedatadecodingstrategy/), [DatabaseDateDecodingStrategy](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasedatedecodingstrategy/), [DatabaseDataEncodingStrategy](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasedataencodingstrategy/), [DatabaseDateEncodingStrategy](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasedateencodingstrategy/), and [DatabaseUUIDEncodingStrategy](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseuuidencodingstrategy/) to learn about all available strategies.
|
||||
|
||||
There is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs and uuid strings, both uppercase and lowercase).
|
||||
|
||||
@@ -2817,7 +2789,7 @@ extension Player: FetchableRecord, PersistableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
See the [query interface](#the-query-interface) and [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for further information.
|
||||
See the [query interface](#the-query-interface) and [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) for further information.
|
||||
|
||||
|
||||
## Record Comparison
|
||||
@@ -2997,7 +2969,7 @@ try player.insert(db)
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> **Note**: The `replace` policy may have to delete rows so that inserts and updates can succeed. Those deletions are not reported to [transaction observers](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) (this might change in a future release of SQLite).
|
||||
> **Note**: The `replace` policy may have to delete rows so that inserts and updates can succeed. Those deletions are not reported to [transaction observers](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver) (this might change in a future release of SQLite).
|
||||
|
||||
### Beyond FetchableRecord
|
||||
|
||||
@@ -3278,7 +3250,7 @@ So don't miss the [SQL API](#sqlite-api).
|
||||
|
||||
> **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output.
|
||||
|
||||
- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema)
|
||||
- [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema)
|
||||
- [Requests](#requests)
|
||||
- [Expressions](#expressions)
|
||||
- [SQL Operators](#sql-operators)
|
||||
@@ -3297,7 +3269,7 @@ So don't miss the [SQL API](#sqlite-api).
|
||||
|
||||
## Requests
|
||||
|
||||
📖 [`QueryInterfaceRequest`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/queryinterfacerequest), [`Table`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/table)
|
||||
📖 [`QueryInterfaceRequest`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest), [`Table`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/table)
|
||||
|
||||
**The query interface requests** let you fetch values from the database:
|
||||
|
||||
@@ -3353,7 +3325,7 @@ enum Columns: String, ColumnExpression {
|
||||
|
||||
You can now build requests with the following methods: `all`, `none`, `select`, `distinct`, `filter`, `matching`, `group`, `having`, `order`, `reversed`, `limit`, `joining`, `including`, `with`. All those methods return another request, which you can further refine by applying another method: `Player.select(...).filter(...).order(...)`.
|
||||
|
||||
- [`all()`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerecord/all()), [`none()`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerecord/none()): the requests for all rows, or no row.
|
||||
- [`all()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerecord/all()), [`none()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerecord/none()): the requests for all rows, or no row.
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player
|
||||
@@ -3362,21 +3334,31 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
|
||||
By default, all columns are selected. See [Columns Selected by a Request].
|
||||
|
||||
- [`select(...)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/selectionrequest/select(_:)-30yzl) and [`select(..., as:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/queryinterfacerequest/select(_:as:)-282xc) define the selected columns. See [Columns Selected by a Request].
|
||||
- [`select(...)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/selectionrequest/select(_:)-30yzl) and [`select(..., as:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/select(_:as:)-282xc) define the selected columns. See [Columns Selected by a Request].
|
||||
|
||||
```swift
|
||||
// SELECT name FROM player
|
||||
Player.select(nameColumn, as: String.self)
|
||||
```
|
||||
|
||||
- [`annotated(with: expression...)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/selectionrequest/annotated(with:)-6ehs4) extends the selection.
|
||||
- [`selectID()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/selectID()) is available on [Identifiable Records]. It supports all tables that have a single-column primary key:
|
||||
|
||||
```swift
|
||||
// SELECT id FROM player
|
||||
Player.selectID()
|
||||
|
||||
// SELECT id FROM player WHERE name IS NOT NULL
|
||||
Player.filter(nameColumn != nil).selectID()
|
||||
```
|
||||
|
||||
- [`annotated(with: expression...)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/selectionrequest/annotated(with:)-6ehs4) extends the selection.
|
||||
|
||||
```swift
|
||||
// SELECT *, (score + bonus) AS total FROM player
|
||||
Player.annotated(with: (scoreColumn + bonusColumn).forKey("total"))
|
||||
```
|
||||
|
||||
- [`annotated(with: aggregate)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/derivablerequest/annotated(with:)-74xfs) extends the selection with [association aggregates](Documentation/AssociationsBasics.md#association-aggregates).
|
||||
- [`annotated(with: aggregate)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/derivablerequest/annotated(with:)-74xfs) extends the selection with [association aggregates](Documentation/AssociationsBasics.md#association-aggregates).
|
||||
|
||||
```swift
|
||||
// SELECT team.*, COUNT(DISTINCT player.id) AS playerCount
|
||||
@@ -3386,7 +3368,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Team.annotated(with: Team.players.count)
|
||||
```
|
||||
|
||||
- [`annotated(withRequired: association)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/annotated(withrequired:)) and [`annotated(withOptional: association)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/annotated(withoptional:)) extends the selection with [Associations].
|
||||
- [`annotated(withRequired: association)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/annotated(withrequired:)) and [`annotated(withOptional: association)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/annotated(withoptional:)) extends the selection with [Associations].
|
||||
|
||||
```swift
|
||||
// SELECT player.*, team.color
|
||||
@@ -3395,14 +3377,14 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Player.annotated(withRequired: Player.team.select(colorColumn))
|
||||
```
|
||||
|
||||
- [`distinct()`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/derivablerequest/distinct()) performs uniquing.
|
||||
- [`distinct()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/derivablerequest/distinct()) performs uniquing.
|
||||
|
||||
```swift
|
||||
// SELECT DISTINCT name FROM player
|
||||
Player.select(nameColumn, as: String.self).distinct()
|
||||
```
|
||||
|
||||
- [`filter(expression)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/filteredrequest/filter(_:)) applies conditions.
|
||||
- [`filter(expression)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/filteredrequest/filter(_:)) applies conditions.
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE id IN (1, 2, 3)
|
||||
@@ -3412,7 +3394,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Player.filter(nameColumn != nil && heightColumn > 1.75)
|
||||
```
|
||||
|
||||
- [`filter(id:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/filter(id:)) and [`filter(ids:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/filter(ids:)) are type-safe methods available on [Identifiable Records]:
|
||||
- [`filter(id:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/filter(id:)) and [`filter(ids:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/filter(ids:)) are type-safe methods available on [Identifiable Records]:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE id = 1
|
||||
@@ -3422,7 +3404,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Country.filter(ids: ["FR", "US"])
|
||||
```
|
||||
|
||||
- [`filter(key:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/filter(key:)-1p9sq) and [`filter(keys:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/filter(keys:)-6ggt1) apply conditions on primary and unique keys:
|
||||
- [`filter(key:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/filter(key:)-1p9sq) and [`filter(keys:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/filter(keys:)-6ggt1) apply conditions on primary and unique keys:
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE id = 1
|
||||
@@ -3438,7 +3420,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Player.filter(key: ["email": "arthur@example.com"])
|
||||
```
|
||||
|
||||
- `matching(pattern)` ([FTS3](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/matching(_:)-3s3zr), [FTS5](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/matching(_:)-7c1e8)) performs [full-text search](Documentation/FullTextSearch.md).
|
||||
- `matching(pattern)` ([FTS3](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/matching(_:)-3s3zr), [FTS5](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/matching(_:)-7c1e8)) performs [full-text search](Documentation/FullTextSearch.md).
|
||||
|
||||
```swift
|
||||
// SELECT * FROM document WHERE document MATCH 'sqlite database'
|
||||
@@ -3448,7 +3430,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
|
||||
When the pattern is nil, no row will match.
|
||||
|
||||
- [`group(expression, ...)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/aggregatingrequest/group(_:)-edak) groups rows.
|
||||
- [`group(expression, ...)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/aggregatingrequest/group(_:)-edak) groups rows.
|
||||
|
||||
```swift
|
||||
// SELECT name, MAX(score) FROM player GROUP BY name
|
||||
@@ -3457,7 +3439,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
.group(nameColumn)
|
||||
```
|
||||
|
||||
- [`having(expression)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/aggregatingrequest/having(_:)) applies conditions on grouped rows.
|
||||
- [`having(expression)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/aggregatingrequest/having(_:)) applies conditions on grouped rows.
|
||||
|
||||
```swift
|
||||
// SELECT team, MAX(score) FROM player GROUP BY team HAVING MIN(score) >= 1000
|
||||
@@ -3467,7 +3449,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
.having(min(scoreColumn) >= 1000)
|
||||
```
|
||||
|
||||
- [`having(aggregate)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/derivablerequest/having(_:)) applies conditions on grouped rows, according to an [association aggregate](Documentation/AssociationsBasics.md#association-aggregates).
|
||||
- [`having(aggregate)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/derivablerequest/having(_:)) applies conditions on grouped rows, according to an [association aggregate](Documentation/AssociationsBasics.md#association-aggregates).
|
||||
|
||||
```swift
|
||||
// SELECT team.*
|
||||
@@ -3478,7 +3460,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Team.having(Team.players.count >= 5)
|
||||
```
|
||||
|
||||
- [`order(ordering, ...)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/orderedrequest/order(_:)-63rzl) sorts.
|
||||
- [`order(ordering, ...)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/orderedrequest/order(_:)-63rzl) sorts.
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player ORDER BY name
|
||||
@@ -3502,7 +3484,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Player.order(scoreColumn).order(nameColumn)
|
||||
```
|
||||
|
||||
- [`reversed()`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/orderedrequest/reversed()) reverses the eventual orderings.
|
||||
- [`reversed()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/orderedrequest/reversed()) reverses the eventual orderings.
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player ORDER BY score ASC, name DESC
|
||||
@@ -3516,7 +3498,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Player.all().reversed()
|
||||
```
|
||||
|
||||
- [`limit(limit, offset: offset)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/queryinterfacerequest/limit(_:offset:)) limits and pages results.
|
||||
- [`limit(limit, offset: offset)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/limit(_:offset:)) limits and pages results.
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player LIMIT 5
|
||||
@@ -3526,7 +3508,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Player.limit(5, offset: 10)
|
||||
```
|
||||
|
||||
- [`joining(required:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/joining(required:)), [`joining(optional:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/joining(optional:)), [`including(required:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/including(required:)), [`including(optional:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/including(optional:)), and [`including(all:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/including(all:)) fetch and join records through [Associations].
|
||||
- [`joining(required:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/joining(required:)), [`joining(optional:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/joining(optional:)), [`including(required:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/including(required:)), [`including(optional:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/including(optional:)), and [`including(all:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/including(all:)) fetch and join records through [Associations].
|
||||
|
||||
```swift
|
||||
// SELECT player.*, team.*
|
||||
@@ -3535,7 +3517,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Player.including(required: Player.team)
|
||||
```
|
||||
|
||||
- [`with(cte)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/derivablerequest/with(_:)) embeds a [common table expression]:
|
||||
- [`with(cte)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/derivablerequest/with(_:)) embeds a [common table expression]:
|
||||
|
||||
```swift
|
||||
// WITH ... SELECT * FROM player
|
||||
@@ -3545,7 +3527,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
|
||||
- Other requests that involve the primary key:
|
||||
|
||||
- [`selectPrimaryKey(as:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/queryinterfacerequest/selectprimarykey(as:)) selects the primary key.
|
||||
- [`selectPrimaryKey(as:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/selectprimarykey(as:)) selects the primary key.
|
||||
|
||||
```swift
|
||||
// SELECT id FROM player
|
||||
@@ -3558,7 +3540,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Citizenship.selectPrimaryKey(as: Row.self) // QueryInterfaceRequest<Row>
|
||||
```
|
||||
|
||||
- [`orderByPrimaryKey()`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/orderbyprimarykey()) sorts by primary key.
|
||||
- [`orderByPrimaryKey()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/orderbyprimarykey()) sorts by primary key.
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player ORDER BY id
|
||||
@@ -3571,7 +3553,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
|
||||
Citizenship.orderByPrimaryKey()
|
||||
```
|
||||
|
||||
- [`groupByPrimaryKey()`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/groupbyprimarykey()) groups rows by primary key.
|
||||
- [`groupByPrimaryKey()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/groupbyprimarykey()) groups rows by primary key.
|
||||
|
||||
|
||||
You can refine requests by chaining those methods:
|
||||
@@ -3595,7 +3577,7 @@ Player // SELECT * FROM player
|
||||
```
|
||||
|
||||
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
|
||||
Raw SQL snippets are also accepted, with eventual [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
|
||||
@@ -3632,21 +3614,41 @@ let request = Player.select(max(Column("score")), as: Int.self)
|
||||
let maxScore = try request.fetchOne(db) // Int?
|
||||
```
|
||||
|
||||
The default selection for a record type is controlled by the `databaseSelection` property:
|
||||
The default selection for a record type is controlled by the `databaseSelection` property. For example:
|
||||
|
||||
```swift
|
||||
// Select a limited set of columns
|
||||
struct RestrictedPlayer : TableRecord {
|
||||
static let databaseTableName = "player"
|
||||
static var databaseSelection: [any SQLSelectable] { [Column("id"), Column("name")] }
|
||||
}
|
||||
|
||||
struct ExtendedPlayer : TableRecord {
|
||||
static let databaseTableName = "player"
|
||||
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
|
||||
static var databaseSelection: [any SQLSelectable] {
|
||||
[Column("id"), Column("name")]
|
||||
}
|
||||
}
|
||||
|
||||
// SELECT id, name FROM player
|
||||
let request = RestrictedPlayer.all()
|
||||
```
|
||||
|
||||
```swift
|
||||
// Select all but a few columns
|
||||
struct Player : TableRecord {
|
||||
static var databaseSelection: [any SQLSelectable] {
|
||||
[.allColumns(excluding: ["generatedColumn"])]
|
||||
}
|
||||
}
|
||||
|
||||
// SELECT id, name FROM player
|
||||
let request = RestrictedPlayer.all()
|
||||
```
|
||||
|
||||
```swift
|
||||
// Select all columns are more
|
||||
struct ExtendedPlayer : TableRecord {
|
||||
static let databaseTableName = "player"
|
||||
static var databaseSelection: [any SQLSelectable] {
|
||||
[.allColumns, .rowID]
|
||||
}
|
||||
}
|
||||
|
||||
// SELECT *, rowid FROM player
|
||||
let request = ExtendedPlayer.all()
|
||||
@@ -3662,7 +3664,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code:
|
||||
|
||||
### SQL Operators
|
||||
|
||||
📖 [`SQLSpecificExpressible`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sqlspecificexpressible)
|
||||
📖 [`SQLSpecificExpressible`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/sqlspecificexpressible)
|
||||
|
||||
GRDB comes with a Swift version of many SQLite [built-in operators](https://sqlite.org/lang_expr.html#operators), listed below. But not all: see [Embedding SQL in Query Interface Requests] for a way to add support for missing SQL operators.
|
||||
|
||||
@@ -3932,13 +3934,13 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli
|
||||
|
||||
### SQL Functions
|
||||
|
||||
📖 [`SQLSpecificExpressible`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sqlspecificexpressible)
|
||||
📖 [`SQLSpecificExpressible`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/sqlspecificexpressible)
|
||||
|
||||
GRDB comes with a Swift version of many SQLite [built-in functions](https://sqlite.org/lang_corefunc.html), listed below. But not all: see [Embedding SQL in Query Interface Requests] for a way to add support for missing SQL functions.
|
||||
|
||||
- `ABS`, `AVG`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`:
|
||||
- `ABS`, `AVG`, `COALESCE`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`:
|
||||
|
||||
Those are based on the `abs`, `average`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min`, `sum` and `total` Swift functions:
|
||||
Those are based on the `abs`, `average`, `coalesce`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min`, `sum`, and `total` Swift functions:
|
||||
|
||||
```swift
|
||||
// SELECT MIN(score), MAX(score) FROM player
|
||||
@@ -4509,7 +4511,7 @@ try Player.customRequest().fetchAll(db) // [Player]
|
||||
}
|
||||
```
|
||||
|
||||
- The [`asRequest(of:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/queryinterfacerequest/asrequest(of:)) method changes the type fetched by the request. It is useful, for example, when you use [Associations]:
|
||||
- The [`asRequest(of:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/asrequest(of:)) method changes the type fetched by the request. It is useful, for example, when you use [Associations]:
|
||||
|
||||
```swift
|
||||
struct BookInfo: FetchableRecord, Decodable {
|
||||
@@ -4525,7 +4527,7 @@ try Player.customRequest().fetchAll(db) // [Player]
|
||||
try request.fetchAll(db)
|
||||
```
|
||||
|
||||
- The [`adapted(_:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/fetchrequest/adapted(_:)) method eases the consumption of complex rows with row adapters. See [`RowAdapter`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter) and [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:)) for a sample code that uses `adapted(_:)`.
|
||||
- The [`adapted(_:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/fetchrequest/adapted(_:)) method eases the consumption of complex rows with row adapters. See [`RowAdapter`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter) and [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:)) for a sample code that uses `adapted(_:)`.
|
||||
|
||||
|
||||
Encryption
|
||||
@@ -4596,7 +4598,7 @@ See [SQLCipher 4.0.0 Release](https://www.zetetic.net/blog/2018/11/30/sqlcipher-
|
||||
|
||||
**You can change the passphrase** of an already encrypted database.
|
||||
|
||||
When you use a [database queue](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue), open the database with the old passphrase, and then apply the new passphrase:
|
||||
When you use a [database queue](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue), open the database with the old passphrase, and then apply the new passphrase:
|
||||
|
||||
```swift
|
||||
try dbQueue.write { db in
|
||||
@@ -4604,7 +4606,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
When you use a [database pool](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool), make sure that no concurrent read can happen by changing the passphrase within the `barrierWriteWithoutTransaction` block. You must also ensure all future reads open a new database connection by calling the `invalidateReadOnlyConnections` method:
|
||||
When you use a [database pool](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool), make sure that no concurrent read can happen by changing the passphrase within the `barrierWriteWithoutTransaction` block. You must also ensure all future reads open a new database connection by calling the `invalidateReadOnlyConnections` method:
|
||||
|
||||
```swift
|
||||
try dbPool.barrierWriteWithoutTransaction { db in
|
||||
@@ -4631,7 +4633,7 @@ try dbPool.barrierWriteWithoutTransaction { db in
|
||||
> }
|
||||
> ```
|
||||
|
||||
> **Note**: The `DatabasePool.barrierWriteWithoutTransaction` method does not prevent [database snapshots](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshot) from accessing the database during the passphrase change, or after the new passphrase has been applied to the database. Those database accesses may throw errors. Applications should provide their own mechanism for invalidating open snapshots before the passphrase is changed.
|
||||
> **Note**: The `DatabasePool.barrierWriteWithoutTransaction` method does not prevent [database snapshots](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesnapshot) from accessing the database during the passphrase change, or after the new passphrase has been applied to the database. Those database accesses may throw errors. Applications should provide their own mechanism for invalidating open snapshots before the passphrase is changed.
|
||||
|
||||
> **Note**: Instead of changing the passphrase "in place" as described here, you can also export the database in a new encrypted database that uses the new passphrase. See [Exporting a Database to an Encrypted Database](#exporting-a-database-to-an-encrypted-database).
|
||||
|
||||
@@ -4786,7 +4788,7 @@ try source.backup(to: destination)
|
||||
|
||||
The `backup` method blocks the current thread until the destination database contains the same contents as the source database.
|
||||
|
||||
When the source is a [database pool](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool), concurrent writes can happen during the backup. Those writes may, or may not, be reflected in the backup, but they won't trigger any error.
|
||||
When the source is a [database pool](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool), concurrent writes can happen during the backup. Those writes may, or may not, be reflected in the backup, but they won't trigger any error.
|
||||
|
||||
`Database` has an analogous `backup` method.
|
||||
|
||||
@@ -4948,7 +4950,7 @@ Considering that a local database is not some JSON loaded from a remote server,
|
||||
|
||||
### DatabaseError
|
||||
|
||||
📖 [`DatabaseError`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseerror)
|
||||
📖 [`DatabaseError`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseerror)
|
||||
|
||||
**DatabaseError** are thrown on SQLite errors:
|
||||
|
||||
@@ -4980,7 +4982,7 @@ do {
|
||||
}
|
||||
```
|
||||
|
||||
If you want to see statement arguments in the error description, [make statement arguments public](https://swiftpackageindex.com/groue/grdb.swift/configuration/publicstatementarguments).
|
||||
If you want to see statement arguments in the error description, [make statement arguments public](https://swiftpackageindex.com/groue/GRDB.swift/configuration/publicstatementarguments).
|
||||
|
||||
**SQLite uses [results codes](https://www.sqlite.org/rescode.html) to distinguish between various errors**.
|
||||
|
||||
@@ -5022,7 +5024,7 @@ Each DatabaseError has two codes: an `extendedResultCode` (see [extended result
|
||||
|
||||
### RecordError
|
||||
|
||||
📖 [`RecordError`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recorderror)
|
||||
📖 [`RecordError`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recorderror)
|
||||
|
||||
**RecordError** is thrown by the [PersistableRecord] protocol when the `update` method could not find any row to update:
|
||||
|
||||
@@ -5058,7 +5060,7 @@ They uncover programmer errors, false assumptions, and prevent misuses. Here are
|
||||
let name: String = row["name"]
|
||||
```
|
||||
|
||||
Solution: fix the contents of the database, use [NOT NULL constraints](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/columndefinition/notnull(onconflict:)), or load an optional:
|
||||
Solution: fix the contents of the database, use [NOT NULL constraints](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/columndefinition/notnull(onconflict:)), or load an optional:
|
||||
|
||||
```swift
|
||||
let name: String? = row["name"]
|
||||
@@ -5303,7 +5305,7 @@ dbPool.releaseMemoryEventually()
|
||||
|
||||
**The iOS operating system likes applications that do not consume much memory.**
|
||||
|
||||
[Database queues] and [pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool) automatically free non-essential memory when the application receives a memory warning, and when the application enters background.
|
||||
[Database queues] and [pools](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool) automatically free non-essential memory when the application receives a memory warning, and when the application enters background.
|
||||
|
||||
You can opt out of this automatic memory management:
|
||||
|
||||
@@ -5362,7 +5364,7 @@ FAQ
|
||||
|
||||
First choose a proper location for the database file. Document-based applications will let the user pick a location. Apps that use the database as a global storage will prefer the Application Support directory.
|
||||
|
||||
The sample code below creates or opens a database file inside its dedicated directory (a [recommended practice](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections)). On the first run, a new empty database file is created. On subsequent runs, the database file already exists, so it just opens a connection:
|
||||
The sample code below creates or opens a database file inside its dedicated directory (a [recommended practice](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections)). On the first run, a new empty database file is created. On subsequent runs, the database file already exists, so it just opens a connection:
|
||||
|
||||
```swift
|
||||
// HOW TO create an empty database, or open an existing database file
|
||||
@@ -5404,7 +5406,7 @@ if let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite") {
|
||||
|
||||
Database connections are automatically closed when `DatabaseQueue` or `DatabasePool` instances are deinitialized.
|
||||
|
||||
If the correct execution of your program depends on precise database closing, perform an explicit call to [`close()`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasereader/close()). This method may fail and create zombie connections, so please check its detailed documentation.
|
||||
If the correct execution of your program depends on precise database closing, perform an explicit call to [`close()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasereader/close()). This method may fail and create zombie connections, so please check its detailed documentation.
|
||||
|
||||
## FAQ: SQL
|
||||
|
||||
@@ -5442,7 +5444,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](https://swiftpackageindex.com/groue/grdb.swift/configuration/publicstatementarguments).
|
||||
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](https://swiftpackageindex.com/groue/GRDB.swift/configuration/publicstatementarguments).
|
||||
|
||||
> **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output.
|
||||
|
||||
@@ -5479,7 +5481,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](https://swiftpackageindex.com/groue/grdb.swift/configuration/publicstatementarguments).
|
||||
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](https://swiftpackageindex.com/groue/GRDB.swift/configuration/publicstatementarguments).
|
||||
|
||||
### What Are Experimental Features?
|
||||
|
||||
@@ -5784,7 +5786,7 @@ When this is the case, there are two possible explanations:
|
||||
try db.execute(sql: "UPDATE player SET name = ?", arguments: [name])
|
||||
```
|
||||
|
||||
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#double_quoted_string_literals_are_accepted), and [Configuration.acceptsDoubleQuotedStringLiterals](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/acceptsdoublequotedstringliterals).
|
||||
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#double_quoted_string_literals_are_accepted), and [Configuration.acceptsDoubleQuotedStringLiterals](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/configuration/acceptsdoublequotedstringliterals).
|
||||
|
||||
|
||||
|
||||
@@ -5859,15 +5861,15 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
|
||||
|
||||
#### Advanced DatabasePool
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
|
||||
|
||||
#### After Commit Hook
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)).
|
||||
|
||||
#### Asynchronous APIs
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
|
||||
|
||||
#### Changes Tracking
|
||||
|
||||
@@ -5875,7 +5877,7 @@ This chapter has been renamed [Record Comparison].
|
||||
|
||||
#### Concurrency
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
|
||||
|
||||
#### Custom Value Types
|
||||
|
||||
@@ -5891,27 +5893,27 @@ This chapter was replaced with [Persistence Callbacks].
|
||||
|
||||
#### Database Changes Observation
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation).
|
||||
|
||||
#### Database Configuration
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/configuration).
|
||||
|
||||
#### Database Queues
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue).
|
||||
|
||||
#### Database Pools
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool).
|
||||
|
||||
#### Database Snapshots
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
|
||||
|
||||
#### DatabaseWriter and DatabaseReader Protocols
|
||||
|
||||
This chapter was removed. See the references of [DatabaseReader](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasereader) and [DatabaseWriter](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasewriter).
|
||||
This chapter was removed. See the references of [DatabaseReader](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasereader) and [DatabaseWriter](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasewriter).
|
||||
|
||||
#### Date and UUID Coding Strategies
|
||||
|
||||
@@ -5923,7 +5925,7 @@ This chapter has been superseded by the [Sharing a Database] guide.
|
||||
|
||||
#### Differences between Database Queues and Pools
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
|
||||
|
||||
#### Enabling FTS5 Support
|
||||
|
||||
@@ -5941,19 +5943,19 @@ This chapter has [moved](Documentation/FullTextSearch.md).
|
||||
|
||||
#### Guarantees and Rules
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
|
||||
|
||||
#### Joined Queries Support
|
||||
|
||||
This chapter was replaced with the documentation of [splittingRowAdapters(columnCounts:)](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:)).
|
||||
This chapter was replaced with the documentation of [splittingRowAdapters(columnCounts:)](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:)).
|
||||
|
||||
#### List of Record Methods
|
||||
|
||||
See [Records and the Query Interface](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/queryinterface).
|
||||
See [Records and the Query Interface](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterface).
|
||||
|
||||
#### Migrations
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations).
|
||||
|
||||
#### NSNumber and NSDecimalNumber
|
||||
|
||||
@@ -5969,15 +5971,15 @@ This error was renamed to [RecordError].
|
||||
|
||||
#### Prepared Statements
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statement).
|
||||
|
||||
#### Record Class
|
||||
|
||||
The [`Record`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/record) class is a legacy GRDB type. Since GRDB 7, it is not recommended to define record types by subclassing the `Record` class.
|
||||
The [`Record`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/record) class is a legacy GRDB type. Since GRDB 7, it is not recommended to define record types by subclassing the `Record` class.
|
||||
|
||||
#### Row Adapters
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter).
|
||||
|
||||
#### RowConvertible Protocol
|
||||
|
||||
@@ -5989,23 +5991,23 @@ This protocol has been renamed [TableRecord] in GRDB 3.0.
|
||||
|
||||
#### Transactions and Savepoints
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactions).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactions).
|
||||
|
||||
#### Transaction Hook
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)).
|
||||
|
||||
#### TransactionObserver Protocol
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver).
|
||||
|
||||
#### Unsafe Concurrency APIs
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
|
||||
|
||||
#### ValueObservation
|
||||
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
|
||||
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation).
|
||||
|
||||
#### ValueObservation and DatabaseRegionObservation
|
||||
|
||||
@@ -6024,7 +6026,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
|
||||
[Fetching from Requests]: #fetching-from-requests
|
||||
[Embedding SQL in Query Interface Requests]: #embedding-sql-in-query-interface-requests
|
||||
[Full-Text Search]: Documentation/FullTextSearch.md
|
||||
[Migrations]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
|
||||
[Migrations]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations
|
||||
[The userInfo Dictionary]: #the-userinfo-dictionary
|
||||
[JSON Columns]: #json-columns
|
||||
[FetchableRecord]: #fetchablerecord-protocol
|
||||
@@ -6034,40 +6036,40 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
|
||||
[Record Customization Options]: #record-customization-options
|
||||
[Persistence Callbacks]: #persistence-callbacks
|
||||
[persistence callbacks]: #persistence-callbacks
|
||||
[Record Timestamps and Transaction Date]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps
|
||||
[Record Timestamps and Transaction Date]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps
|
||||
[TableRecord]: #tablerecord-protocol
|
||||
[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
|
||||
[DatabaseRegion]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregion
|
||||
[DatabaseRegion]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregion
|
||||
[SQL Interpolation]: Documentation/SQLInterpolation.md
|
||||
[custom SQLite build]: Documentation/CustomSQLiteBuilds.md
|
||||
[Combine]: https://developer.apple.com/documentation/combine
|
||||
[Combine Support]: Documentation/Combine.md
|
||||
[Concurrency]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
|
||||
[Concurrency]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency
|
||||
[Demo Applications]: Documentation/DemoApps
|
||||
[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing
|
||||
[Sharing a Database]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing
|
||||
[FAQ]: #faq
|
||||
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
|
||||
[SQLRequest]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sqlrequest
|
||||
[Database Observation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation
|
||||
[SQLRequest]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/sqlrequest
|
||||
[SQL literal]: Documentation/SQLInterpolation.md#sql-literal
|
||||
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
|
||||
[Query Interface Organization]: Documentation/QueryInterfaceOrganization.md
|
||||
[Database Configuration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration
|
||||
[Database Configuration]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/configuration
|
||||
[Persistence Methods]: #persistence-methods
|
||||
[persistence methods]: #persistence-methods
|
||||
[Persistence Methods and the `RETURNING` clause]: #persistence-methods-and-the-returning-clause
|
||||
[RecordError]: #recorderror
|
||||
[Transactions and Savepoints]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactions
|
||||
[`DatabaseQueue`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue
|
||||
[Database queues]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue
|
||||
[`DatabasePool`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
|
||||
[database pools]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
|
||||
[`DatabaseValueConvertible`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible
|
||||
[`StatementArguments`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments
|
||||
[Prepared Statements]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement
|
||||
[prepared statements]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement
|
||||
[`Statement`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement
|
||||
[Transactions and Savepoints]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactions
|
||||
[`DatabaseQueue`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue
|
||||
[Database queues]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue
|
||||
[`DatabasePool`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool
|
||||
[database pools]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool
|
||||
[`DatabaseValueConvertible`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasevalueconvertible
|
||||
[`StatementArguments`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments
|
||||
[Prepared Statements]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statement
|
||||
[prepared statements]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statement
|
||||
[`Statement`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statement
|
||||
[Database Connections]: #database-connections
|
||||
[Database connections]: #database-connections
|
||||
[database connection]: #database-connections
|
||||
+1
-1
Submodule SQLiteCustom/src updated: 31e6aa6618...69395d1f72.
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>7.0.0-beta.2</string>
|
||||
<string>7.3.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -66,6 +66,16 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
|
||||
XCTAssertEqual(rows[0].scopes["team"]!, ["id":1, "name":"Reds"])
|
||||
}
|
||||
|
||||
func testDefaultScopeIncludingRequiredRestrictedSelection() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player.select(.allColumns(excluding: ["name"])).including(required: Player.defaultTeam)
|
||||
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
|
||||
XCTAssertEqual(rows.count, 1)
|
||||
XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1])
|
||||
XCTAssertEqual(Set(rows[0].scopes.names), ["team"])
|
||||
XCTAssertEqual(rows[0].scopes["team"]!, ["id":1, "name":"Reds"])
|
||||
}
|
||||
|
||||
func testDefaultScopeAnnotatedWithRequired() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player.annotated(withRequired: Player.defaultTeam)
|
||||
@@ -82,6 +92,14 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
|
||||
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"])
|
||||
}
|
||||
|
||||
func testDefaultScopeAnnotatedWithRequiredRestrictedSelection() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player.annotated(withRequired: Player.defaultTeam.select(.allColumns(excluding: ["name"])))
|
||||
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
|
||||
XCTAssertEqual(rows.count, 1)
|
||||
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1])
|
||||
}
|
||||
|
||||
func testDefaultScopeIncludingOptional() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player.including(optional: Player.defaultTeam)
|
||||
@@ -113,6 +131,15 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
|
||||
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "teamName":nil])
|
||||
}
|
||||
|
||||
func testDefaultScopeAnnotatedWithOptionalRestrictedSelection() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player.annotated(withOptional: Player.defaultTeam.select(.allColumns(excluding: ["name"])))
|
||||
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
|
||||
XCTAssertEqual(rows.count, 2)
|
||||
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1])
|
||||
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "id":nil])
|
||||
}
|
||||
|
||||
func testDefaultScopeJoiningRequired() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player.joining(required: Player.defaultTeam)
|
||||
@@ -153,6 +180,16 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
|
||||
XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"])
|
||||
}
|
||||
|
||||
func testCustomScopeIncludingRequiredRestrictedSelection() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player.select(.allColumns(excluding: ["name"])).including(required: Player.customTeam)
|
||||
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
|
||||
XCTAssertEqual(rows.count, 1)
|
||||
XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1])
|
||||
XCTAssertEqual(Set(rows[0].scopes.names), ["customTeam"])
|
||||
XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"])
|
||||
}
|
||||
|
||||
func testCustomScopeAnnotatedWithRequired() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player.annotated(withRequired: Player.customTeam)
|
||||
@@ -169,6 +206,14 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
|
||||
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"])
|
||||
}
|
||||
|
||||
func testCustomScopeAnnotatedWithRequiredRestrictedSelection() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player.annotated(withRequired: Player.customTeam.select(.allColumns(excluding: ["name"])))
|
||||
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
|
||||
XCTAssertEqual(rows.count, 1)
|
||||
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1])
|
||||
}
|
||||
|
||||
func testCustomScopeIncludingOptional() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player.including(optional: Player.customTeam)
|
||||
@@ -200,6 +245,15 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
|
||||
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "teamName":nil])
|
||||
}
|
||||
|
||||
func testCustomScopeAnnotatedWithOptionalRestrictedSelection() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player.annotated(withOptional: Player.customTeam.select(.allColumns(excluding: ["name"])))
|
||||
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
|
||||
XCTAssertEqual(rows.count, 2)
|
||||
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1])
|
||||
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "id":nil])
|
||||
}
|
||||
|
||||
func testCustomPluralScopeIncludingRequired() throws {
|
||||
// Make sure explicit plural keys are preserved
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
|
||||
@@ -5,7 +5,8 @@ import GRDB
|
||||
private struct A : TableRecord {
|
||||
static let databaseTableName = "a"
|
||||
static let b = belongsTo(B.self)
|
||||
static let restrictedB = belongsTo(RestrictedB.self)
|
||||
static let restrictedB1 = belongsTo(RestrictedB1.self)
|
||||
static let restrictedB2 = belongsTo(RestrictedB2.self)
|
||||
static let extendedB = belongsTo(ExtendedB.self)
|
||||
}
|
||||
|
||||
@@ -14,14 +15,19 @@ private struct B : TableRecord {
|
||||
static let databaseTableName = "b"
|
||||
}
|
||||
|
||||
private struct RestrictedB : TableRecord {
|
||||
private struct RestrictedB1 : TableRecord {
|
||||
static let databaseTableName = "b"
|
||||
static var databaseSelection: [any SQLSelectable] { [Column("name")] }
|
||||
}
|
||||
|
||||
private struct RestrictedB2 : TableRecord {
|
||||
static let databaseTableName = "b"
|
||||
static var databaseSelection: [any SQLSelectable] { [.allColumns(excluding: ["id"])] }
|
||||
}
|
||||
|
||||
private struct ExtendedB : TableRecord {
|
||||
static let databaseTableName = "b"
|
||||
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
|
||||
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
|
||||
}
|
||||
|
||||
/// Test SQL generation
|
||||
@@ -48,7 +54,12 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bid"
|
||||
""")
|
||||
try assertEqualSQL(db, A.including(required: A.restrictedB), """
|
||||
try assertEqualSQL(db, A.including(required: A.restrictedB1), """
|
||||
SELECT "a".*, "b"."name" \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bid"
|
||||
""")
|
||||
try assertEqualSQL(db, A.including(required: A.restrictedB2), """
|
||||
SELECT "a".*, "b"."name" \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bid"
|
||||
@@ -76,8 +87,8 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
|
||||
do {
|
||||
let request = A.including(required: A.b
|
||||
.select(
|
||||
AllColumns(),
|
||||
Column.rowID))
|
||||
.allColumns,
|
||||
.rowID))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".*, "b"."rowid" \
|
||||
FROM "a" \
|
||||
@@ -89,9 +100,9 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
|
||||
let request = A
|
||||
.aliased(aAlias)
|
||||
.including(required: A.b
|
||||
.select(
|
||||
Column("name"),
|
||||
(Column("id") + aAlias[Column("id")]).forKey("foo")))
|
||||
.select(
|
||||
Column("name"),
|
||||
(Column("id") + aAlias[Column("id")]).forKey("foo")))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \
|
||||
FROM "a" \
|
||||
|
||||
@@ -76,6 +76,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
|
||||
SELECT "children".*, "parents".* \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "children".*, "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE "rowid" = 1
|
||||
@@ -139,6 +149,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
|
||||
SELECT "children".*, "parents".* \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "children".*, "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE "id" = 1
|
||||
@@ -229,6 +249,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
|
||||
SELECT "children".*, "parents".* \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "children".*, "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE "id" = 1
|
||||
@@ -292,6 +322,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
|
||||
SELECT "children".*, "parents".* \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "children".*, "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE "id" = 1
|
||||
@@ -380,6 +420,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
|
||||
SELECT "children".*, "parents".* \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "children".*, "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE "id" = 1
|
||||
@@ -443,6 +493,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
|
||||
SELECT "children".*, "parents".* \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "children".*, "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE "id" = 1
|
||||
@@ -506,6 +566,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
|
||||
SELECT "children".*, "parents".* \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "children".*, "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE "id" = 1
|
||||
@@ -599,6 +669,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
|
||||
SELECT "children".*, "parents".* \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "children".*, "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE "id" = 1
|
||||
@@ -662,6 +742,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
|
||||
SELECT "children".*, "parents".* \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "children".*, "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE "id" = 1
|
||||
@@ -725,7 +815,17 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
|
||||
SELECT "children".*, "parents".* \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "children".*, "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE "id" = 2
|
||||
""")
|
||||
@@ -788,6 +888,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
|
||||
SELECT "children".*, "parents".* \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "children".*, "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE "id" = 2
|
||||
@@ -882,6 +992,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
|
||||
SELECT "children".*, "parents"."b", "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
|
||||
@@ -991,6 +1106,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
|
||||
SELECT "children".*, "parents"."b", "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
|
||||
@@ -1068,6 +1188,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
|
||||
SELECT "children".*, "parents"."b", "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
|
||||
@@ -1176,6 +1301,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
|
||||
SELECT "children".*, "parents"."b", "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
|
||||
@@ -1253,6 +1383,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
|
||||
SELECT "children".*, "parents"."b", "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
|
||||
@@ -1330,6 +1465,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
|
||||
SELECT "children".*, "parents"."b", "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
|
||||
@@ -1447,6 +1587,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
|
||||
SELECT "children".*, "parents"."b", "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
|
||||
@@ -1524,6 +1669,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
|
||||
SELECT "children".*, "parents"."b", "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
|
||||
@@ -1601,6 +1751,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
|
||||
SELECT "children".*, "parents"."b", "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE ("a" = 3) AND ("b" = 4)
|
||||
@@ -1678,6 +1833,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
|
||||
SELECT "children".*, "parents"."b", "parents"."name" \
|
||||
FROM "children" \
|
||||
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE ("a" = 3) AND ("b" = 4)
|
||||
@@ -1699,7 +1859,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """
|
||||
SELECT "custom".* FROM "parents" "custom" WHERE 0
|
||||
""")
|
||||
|
||||
|
||||
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: nil).request(for: association), """
|
||||
SELECT * FROM "parents" WHERE 0
|
||||
""")
|
||||
@@ -1896,6 +2056,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "CHILDREN" \
|
||||
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "CHILDREN".*, "PARENTS"."name" \
|
||||
FROM "CHILDREN" \
|
||||
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
|
||||
SELECT * FROM "PARENTS" WHERE "id" = 1
|
||||
@@ -1959,6 +2124,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "CHILDREN" \
|
||||
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "CHILDREN".*, "PARENTS"."name" \
|
||||
FROM "CHILDREN" \
|
||||
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
|
||||
SELECT * FROM "PARENTS" WHERE "id" = 1
|
||||
@@ -2022,6 +2192,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
|
||||
FROM "CHILDREN" \
|
||||
LEFT JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
|
||||
""")
|
||||
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
|
||||
SELECT "CHILDREN".*, "PARENTS"."name" \
|
||||
FROM "CHILDREN" \
|
||||
LEFT JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
|
||||
""")
|
||||
|
||||
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
|
||||
SELECT * FROM "PARENTS" WHERE "ID" = 1
|
||||
|
||||
@@ -5,7 +5,8 @@ import GRDB
|
||||
private struct A : TableRecord {
|
||||
static let databaseTableName = "a"
|
||||
static let b = hasOne(B.self)
|
||||
static let restrictedB = hasOne(RestrictedB.self)
|
||||
static let restrictedB1 = hasOne(RestrictedB1.self)
|
||||
static let restrictedB2 = hasOne(RestrictedB2.self)
|
||||
static let extendedB = hasOne(ExtendedB.self)
|
||||
}
|
||||
|
||||
@@ -14,14 +15,19 @@ private struct B : TableRecord {
|
||||
static let databaseTableName = "b"
|
||||
}
|
||||
|
||||
private struct RestrictedB : TableRecord {
|
||||
private struct RestrictedB1 : TableRecord {
|
||||
static let databaseTableName = "b"
|
||||
static var databaseSelection: [any SQLSelectable] { [Column("name")] }
|
||||
}
|
||||
|
||||
private struct RestrictedB2 : TableRecord {
|
||||
static let databaseTableName = "b"
|
||||
static var databaseSelection: [any SQLSelectable] { [.allColumns(excluding: ["id"])] }
|
||||
}
|
||||
|
||||
private struct ExtendedB : TableRecord {
|
||||
static let databaseTableName = "b"
|
||||
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
|
||||
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
|
||||
}
|
||||
|
||||
/// Test SQL generation
|
||||
@@ -48,11 +54,16 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."aid" = "a"."id"
|
||||
""")
|
||||
try assertEqualSQL(db, A.including(required: A.restrictedB), """
|
||||
try assertEqualSQL(db, A.including(required: A.restrictedB1), """
|
||||
SELECT "a".*, "b"."name" \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."aid" = "a"."id"
|
||||
""")
|
||||
try assertEqualSQL(db, A.including(required: A.restrictedB2), """
|
||||
SELECT "a".*, "b"."aid", "b"."name" \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."aid" = "a"."id"
|
||||
""")
|
||||
try assertEqualSQL(db, A.including(required: A.extendedB), """
|
||||
SELECT "a".*, "b".*, "b"."rowid" \
|
||||
FROM "a" \
|
||||
@@ -76,8 +87,8 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
|
||||
do {
|
||||
let request = A.including(required: A.b
|
||||
.select(
|
||||
AllColumns(),
|
||||
Column.rowID))
|
||||
.allColumns,
|
||||
.rowID))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".*, "b"."rowid" \
|
||||
FROM "a" \
|
||||
@@ -89,9 +100,9 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
|
||||
let request = A
|
||||
.aliased(aAlias)
|
||||
.including(required: A.b
|
||||
.select(
|
||||
Column("name"),
|
||||
(Column("id") + aAlias[Column("id")]).forKey("foo")))
|
||||
.select(
|
||||
Column("name"),
|
||||
(Column("id") + aAlias[Column("id")]).forKey("foo")))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \
|
||||
FROM "a" \
|
||||
|
||||
@@ -4,27 +4,34 @@ import GRDB
|
||||
private struct A: TableRecord {
|
||||
static let b = belongsTo(B.self)
|
||||
static let c = hasOne(C.self, through: b, using: B.c)
|
||||
static let restrictedC = hasOne(RestrictedC.self, through: b, using: B.restrictedC)
|
||||
static let restrictedC1 = hasOne(RestrictedC1.self, through: b, using: B.restrictedC1)
|
||||
static let restrictedC2 = hasOne(RestrictedC2.self, through: b, using: B.restrictedC2)
|
||||
static let extendedC = hasOne(ExtendedC.self, through: b, using: B.extendedC)
|
||||
}
|
||||
|
||||
private struct B: TableRecord {
|
||||
static let c = belongsTo(C.self)
|
||||
static let restrictedC = belongsTo(RestrictedC.self)
|
||||
static let restrictedC1 = belongsTo(RestrictedC1.self)
|
||||
static let restrictedC2 = belongsTo(RestrictedC2.self)
|
||||
static let extendedC = belongsTo(ExtendedC.self)
|
||||
}
|
||||
|
||||
private struct C: TableRecord {
|
||||
}
|
||||
|
||||
private struct RestrictedC : TableRecord {
|
||||
private struct RestrictedC1 : TableRecord {
|
||||
static let databaseTableName = "c"
|
||||
static var databaseSelection: [any SQLSelectable] { [Column("name")] }
|
||||
}
|
||||
|
||||
private struct RestrictedC2 : TableRecord {
|
||||
static let databaseTableName = "c"
|
||||
static var databaseSelection: [any SQLSelectable] { [.allColumns(excluding: ["id"])] }
|
||||
}
|
||||
|
||||
private struct ExtendedC : TableRecord {
|
||||
static let databaseTableName = "c"
|
||||
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
|
||||
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
|
||||
}
|
||||
|
||||
/// Test SQL generation
|
||||
@@ -56,7 +63,13 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase {
|
||||
JOIN "b" ON "b"."id" = "a"."bId" \
|
||||
JOIN "c" ON "c"."id" = "b"."cId"
|
||||
""")
|
||||
try assertEqualSQL(db, A.including(required: A.restrictedC), """
|
||||
try assertEqualSQL(db, A.including(required: A.restrictedC1), """
|
||||
SELECT "a".*, "c"."name" \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bId" \
|
||||
JOIN "c" ON "c"."id" = "b"."cId"
|
||||
""")
|
||||
try assertEqualSQL(db, A.including(required: A.restrictedC2), """
|
||||
SELECT "a".*, "c"."name" \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bId" \
|
||||
@@ -87,8 +100,8 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase {
|
||||
do {
|
||||
let request = A.including(required: A.c
|
||||
.select(
|
||||
AllColumns(),
|
||||
Column.rowID))
|
||||
.allColumns,
|
||||
.rowID))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c".*, "c"."rowid" \
|
||||
FROM "a" \
|
||||
|
||||
@@ -157,6 +157,110 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasMany_limit() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
// Plain request
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_bs_limited" AS (\
|
||||
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
|
||||
FROM "b" \
|
||||
WHERE "colb2" IN (1, 2, 3)\
|
||||
) \
|
||||
SELECT * FROM "grdb_bs_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colb1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with avoided prefetch
|
||||
do {
|
||||
let request = A
|
||||
.none()
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM \"a\" WHERE 0 ORDER BY \"cola1\"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
do {
|
||||
let request = A
|
||||
.filter(Column("cola1") != 3)
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.filter(Column("colb1") == 4)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("bs1")
|
||||
.limit(3))
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.filter(Column("colb1") != 4)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("bs2")
|
||||
.limit(5, offset: 2))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" \
|
||||
WHERE "cola1" <> 3 \
|
||||
ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_bs1_limited" AS (\
|
||||
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
|
||||
FROM "b" \
|
||||
WHERE ("colb1" = 4) AND ("colb2" IN (1, 2))\
|
||||
) \
|
||||
SELECT * FROM "grdb_bs1_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colb1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_bs2_limited" AS (\
|
||||
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
|
||||
FROM "b" \
|
||||
WHERE ("colb1" <> 4) AND ("colb2" IN (1, 2))\
|
||||
) \
|
||||
SELECT * FROM "grdb_bs2_limited" \
|
||||
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8) \
|
||||
ORDER BY "colb1"
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyScalar() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
@@ -188,6 +292,42 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyScalar_limit() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
// Plain request
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.select(Column("colb2"))
|
||||
.distinct()
|
||||
.order(Column("colb2"))
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_bs_limited" AS (\
|
||||
SELECT DISTINCT "colb2", "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb2") AS "rowNumber" \
|
||||
FROM "b" \
|
||||
WHERE "colb2" IN (1, 2, 3)\
|
||||
) \
|
||||
SELECT * FROM "grdb_bs_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colb2"
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyWithCompoundForeignKey() throws {
|
||||
// We can use the CTE technique
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
@@ -304,6 +444,141 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyWithCompoundForeignKey_limit() throws {
|
||||
// We can use the CTE technique
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "parent") { t in
|
||||
t.column("parentA", .text)
|
||||
t.column("parentB", .text)
|
||||
t.primaryKey(["parentA", "parentB"])
|
||||
}
|
||||
try db.create(table: "child") { t in
|
||||
t.column("pA", .text)
|
||||
t.column("pB", .text)
|
||||
t.column("name", .text)
|
||||
t.foreignKey(["pA", "pB"], references: "parent")
|
||||
}
|
||||
try db.execute(sql: """
|
||||
INSERT INTO parent (parentA, parentB) VALUES ('foo', 'bar');
|
||||
INSERT INTO parent (parentA, parentB) VALUES ('baz', 'qux');
|
||||
INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar1');
|
||||
INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar2');
|
||||
INSERT INTO child (pA, pB, name) VALUES ('baz', 'qux', 'bazqux1');
|
||||
""")
|
||||
|
||||
struct Parent: TableRecord { }
|
||||
struct Child: TableRecord { }
|
||||
|
||||
// Plain request
|
||||
do {
|
||||
let request = Parent
|
||||
.including(all: Parent
|
||||
.hasMany(Child.self)
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" ORDER BY "parentA", "parentB"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_children_limited" AS (\
|
||||
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
|
||||
FROM "child" \
|
||||
WHERE ("pA", "pB") IN "grdb_base"\
|
||||
), \
|
||||
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \
|
||||
SELECT * \
|
||||
FROM "grdb_children_limited" \
|
||||
WHERE "rowNumber" <= 3
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with avoided prefetch
|
||||
do {
|
||||
let request = Parent
|
||||
.none()
|
||||
.including(all: Parent
|
||||
.hasMany(Child.self)
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" WHERE 0 ORDER BY "parentA", "parentB"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
do {
|
||||
let request = Parent
|
||||
.including(all: Parent
|
||||
.hasMany(Child.self)
|
||||
.filter(Column("name") == "foo")
|
||||
.limit(3))
|
||||
.filter(Column("parentA") == "foo")
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" WHERE "parentA" = 'foo' ORDER BY "parentA", "parentB"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_children_limited" AS (\
|
||||
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
|
||||
FROM "child" \
|
||||
WHERE ("name" = 'foo') AND (("pA", "pB") IN "grdb_base")\
|
||||
), \
|
||||
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "parentA" = 'foo') \
|
||||
SELECT * \
|
||||
FROM "grdb_children_limited" \
|
||||
WHERE "rowNumber" <= 3
|
||||
"""])
|
||||
}
|
||||
|
||||
// Limited ordered request (preserve both ordering and limit in the CTE)
|
||||
do {
|
||||
let request = Parent
|
||||
.including(all: Parent
|
||||
.hasMany(Child.self)
|
||||
.limit(5, offset: 2))
|
||||
.orderByPrimaryKey()
|
||||
.limit(1)
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_children_limited" AS (\
|
||||
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
|
||||
FROM "child" WHERE ("pA", "pB") IN "grdb_base"\
|
||||
), \
|
||||
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1) \
|
||||
SELECT * FROM "grdb_children_limited" \
|
||||
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8)
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyIncludingAllHasMany() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
@@ -455,6 +730,218 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyIncludingAllHasMany_limit() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
// Plain request
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.orderByPrimaryKey()
|
||||
.limit(5, offset: 2))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_cs_limited" AS (\
|
||||
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" ORDER BY "colc1") AS "rowNumber" \
|
||||
FROM "c" \
|
||||
WHERE "colc2" IN (1, 2, 3)\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_cs_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colc1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE "cold2" IN (7, 8, 9)\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds_limited" \
|
||||
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8) \
|
||||
ORDER BY "cold1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with avoided second-level prefetch
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.none()
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.orderByPrimaryKey()
|
||||
.limit(5, offset: 2))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_cs_limited" AS (\
|
||||
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" ORDER BY "colc1") AS "rowNumber" \
|
||||
FROM "c" \
|
||||
WHERE 0 AND ("colc2" IN (1, 2, 3))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_cs_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colc1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
do {
|
||||
let request = A
|
||||
.filter(Column("cola1") != 3)
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.filter(Column("colc1") > 7)
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") == 11)
|
||||
.orderByPrimaryKey()
|
||||
.limit(1)
|
||||
.forKey("ds1"))
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") != 11)
|
||||
.orderByPrimaryKey()
|
||||
.limit(2)
|
||||
.forKey("ds2"))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3)
|
||||
.forKey("cs1"))
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.filter(Column("colc1") < 9)
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") == 11)
|
||||
.orderByPrimaryKey()
|
||||
.limit(3)
|
||||
.forKey("ds1"))
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") != 11)
|
||||
.orderByPrimaryKey()
|
||||
.limit(4)
|
||||
.forKey("ds2"))
|
||||
.orderByPrimaryKey()
|
||||
.limit(5)
|
||||
.forKey("cs2"))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * \
|
||||
FROM "a" \
|
||||
WHERE "cola1" <> 3 \
|
||||
ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_cs1_limited" AS (\
|
||||
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" \
|
||||
ORDER BY "colc1") AS "rowNumber" \
|
||||
FROM "c" \
|
||||
WHERE ("colc1" > 7) AND ("colc2" IN (1, 2))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_cs1_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colc1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds1_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
|
||||
ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE ("cold1" = 11) AND ("cold2" IN (8, 9))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds1_limited" \
|
||||
WHERE "rowNumber" <= 1 \
|
||||
ORDER BY "cold1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds2_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
|
||||
ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE ("cold1" <> 11) AND ("cold2" IN (8, 9))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds2_limited" \
|
||||
WHERE "rowNumber" <= 2 \
|
||||
ORDER BY "cold1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_cs2_limited" AS (\
|
||||
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" \
|
||||
ORDER BY "colc1") AS "rowNumber" \
|
||||
FROM "c" \
|
||||
WHERE ("colc1" < 9) AND ("colc2" IN (1, 2))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_cs2_limited" \
|
||||
WHERE "rowNumber" <= 5 \
|
||||
ORDER BY "colc1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds1_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
|
||||
ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE ("cold1" = 11) AND ("cold2" IN (7, 8))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds1_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "cold1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds2_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
|
||||
ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE ("cold1" <> 11) AND ("cold2" IN (7, 8))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds2_limited" \
|
||||
WHERE "rowNumber" <= 4 \
|
||||
ORDER BY "cold1"
|
||||
""",
|
||||
])}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyIncludingAllHasManyWithCompoundForeignKey() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
@@ -730,6 +1217,138 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyIncludingRequiredOrOptionalHasMany_limit() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
// Plain request
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.including(required: C
|
||||
.hasMany(D.self)
|
||||
.orderByPrimaryKey())
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
#warning("TODO: ordering on D is lost")
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d".* \
|
||||
FROM "c" \
|
||||
JOIN "d" ON "d"."cold2" = "c"."colc1" \
|
||||
WHERE "c"."colc2" IN (1, 2, 3) \
|
||||
ORDER BY "c"."colc1", "d"."cold1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with avoided prefetch
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.none()
|
||||
.including(required: C
|
||||
.hasMany(D.self)
|
||||
.orderByPrimaryKey())
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d".* \
|
||||
FROM "c" \
|
||||
JOIN "d" ON "d"."cold2" = "c"."colc1" \
|
||||
WHERE 0 AND ("c"."colc2" IN (1, 2, 3)) \
|
||||
ORDER BY "c"."colc1", "d"."cold1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
do {
|
||||
let request = A
|
||||
.filter(Column("cola1") != 3)
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.filter(Column("colc1") > 7)
|
||||
.including(optional: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") == 11)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("d1"))
|
||||
.including(required: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") != 11)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("d2"))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3)
|
||||
.forKey("cs1"))
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.filter(Column("colc1") < 9)
|
||||
.including(optional: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") == 11)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("d1"))
|
||||
.including(required: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") != 11)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("d2"))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3)
|
||||
.forKey("cs2"))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * \
|
||||
FROM "a" \
|
||||
WHERE "cola1" <> 3 \
|
||||
ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
|
||||
FROM "c" \
|
||||
LEFT JOIN "d" "d1" ON ("d1"."cold2" = "c"."colc1") AND ("d1"."cold1" = 11) \
|
||||
JOIN "d" "d2" ON ("d2"."cold2" = "c"."colc1") AND ("d2"."cold1" <> 11) \
|
||||
WHERE ("c"."colc1" > 7) AND ("c"."colc2" IN (1, 2)) \
|
||||
ORDER BY "c"."colc1", "d1"."cold1", "d2"."cold1"
|
||||
""",
|
||||
"""
|
||||
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
|
||||
FROM "c" \
|
||||
LEFT JOIN "d" "d1" ON ("d1"."cold2" = "c"."colc1") AND ("d1"."cold1" = 11) \
|
||||
JOIN "d" "d2" ON ("d2"."cold2" = "c"."colc1") AND ("d2"."cold1" <> 11) \
|
||||
WHERE ("c"."colc1" < 9) AND ("c"."colc2" IN (1, 2)) \
|
||||
ORDER BY "c"."colc1", "d1"."cold1", "d2"."cold1"
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyThroughHasManyUsingHasMany() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
@@ -139,7 +130,7 @@ class DatabaseConfigurationTests: GRDBTestCase {
|
||||
let foo = try dbQueue.inDatabase { db in
|
||||
try String.fetchOne(db, sql: "SELECT \"foo\" FROM player")
|
||||
}
|
||||
if sqlite3_libversion_number() >= 3029000 {
|
||||
if Database.sqliteLibVersionNumber >= 3029000 {
|
||||
XCTFail("Expected error")
|
||||
} else {
|
||||
XCTAssertEqual(foo, "foo")
|
||||
@@ -154,7 +145,7 @@ class DatabaseConfigurationTests: GRDBTestCase {
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.execute(sql: "CREATE INDEX i ON player(\"foo\")")
|
||||
}
|
||||
if sqlite3_libversion_number() >= 3029000 {
|
||||
if Database.sqliteLibVersionNumber >= 3029000 {
|
||||
XCTFail("Expected error")
|
||||
}
|
||||
} catch let error as DatabaseError {
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
@@ -1282,7 +1273,7 @@ final class DatabaseDumpTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func test_dumpSchema_ignores_shadow_tables() throws {
|
||||
guard sqlite3_libversion_number() >= 3037000 else {
|
||||
guard Database.sqliteLibVersionNumber >= 3037000 else {
|
||||
throw XCTSkip("Can't detect shadow tables")
|
||||
}
|
||||
|
||||
@@ -1486,7 +1477,7 @@ final class DatabaseDumpTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func test_dumpContent_ignores_shadow_tables() throws {
|
||||
guard sqlite3_libversion_number() >= 3037000 else {
|
||||
guard Database.sqliteLibVersionNumber >= 3037000 else {
|
||||
throw XCTSkip("Can't detect shadow tables")
|
||||
}
|
||||
|
||||
|
||||
@@ -655,9 +655,11 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
migrator.registerMigration("1", migrate: { _ in })
|
||||
try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges))
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
migrator.registerMigration("2", migrate: { _ in })
|
||||
try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges))
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
|
||||
@@ -669,12 +671,50 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
migrator.registerMigration("1", migrate: { _ in })
|
||||
try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges))
|
||||
try migrator.migrate(dbQueue)
|
||||
|
||||
migrator.registerMigration("2", migrate: { _ in })
|
||||
try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges))
|
||||
try migrator.migrate(dbQueue)
|
||||
}
|
||||
|
||||
func testHasSchemaChangesWorksWithReadonlyConfig() throws {
|
||||
// 1st version of the migrator
|
||||
var migrator1 = DatabaseMigrator()
|
||||
migrator1.registerMigration("1") { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text)
|
||||
}
|
||||
}
|
||||
|
||||
// 2nd version of the migrator
|
||||
var migrator2 = DatabaseMigrator()
|
||||
migrator2.registerMigration("1") { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text)
|
||||
t.column("score", .integer) // <- schema change, because reasons (development)
|
||||
}
|
||||
}
|
||||
|
||||
let dbName = ProcessInfo.processInfo.globallyUniqueString
|
||||
let dbQueue = try makeDatabaseQueue(filename: dbName)
|
||||
|
||||
try XCTAssertFalse(dbQueue.read(migrator1.hasSchemaChanges))
|
||||
try migrator1.migrate(dbQueue)
|
||||
try XCTAssertFalse(dbQueue.read(migrator1.hasSchemaChanges))
|
||||
try dbQueue.close()
|
||||
|
||||
// check that the migrator doesn't fail for a readonly connection
|
||||
dbConfiguration.readonly = true
|
||||
let readonlyQueue = try makeDatabaseQueue(filename: dbName)
|
||||
|
||||
try XCTAssertFalse(readonlyQueue.read(migrator1.hasSchemaChanges))
|
||||
try XCTAssertTrue(readonlyQueue.read(migrator2.hasSchemaChanges))
|
||||
}
|
||||
|
||||
func testEraseDatabaseOnSchemaChange() throws {
|
||||
// 1st version of the migrator
|
||||
var migrator1 = DatabaseMigrator()
|
||||
@@ -714,10 +754,58 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
|
||||
// ... unless database gets erased
|
||||
migrator2.eraseDatabaseOnSchemaChange = true
|
||||
try XCTAssertTrue(dbQueue.read(migrator2.hasSchemaChanges))
|
||||
try migrator2.migrate(dbQueue)
|
||||
try XCTAssertFalse(dbQueue.read(migrator2.hasSchemaChanges))
|
||||
try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1", "2"])
|
||||
}
|
||||
|
||||
func testManualEraseDatabaseOnSchemaChange() throws {
|
||||
// 1st version of the migrator
|
||||
var migrator1 = DatabaseMigrator()
|
||||
migrator1.registerMigration("1") { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text)
|
||||
}
|
||||
}
|
||||
|
||||
// 2nd version of the migrator
|
||||
var migrator2 = DatabaseMigrator()
|
||||
migrator2.registerMigration("1") { db in
|
||||
try db.create(table: "player") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
t.column("name", .text)
|
||||
t.column("score", .integer) // <- schema change, because reasons (development)
|
||||
}
|
||||
}
|
||||
migrator2.registerMigration("2") { db in
|
||||
try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)")
|
||||
}
|
||||
|
||||
// Apply 1st migrator
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try migrator1.migrate(dbQueue)
|
||||
|
||||
// Test than 2nd migrator can't run...
|
||||
do {
|
||||
try migrator2.migrate(dbQueue)
|
||||
XCTFail("Expected DatabaseError")
|
||||
} catch let error as DatabaseError {
|
||||
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
|
||||
XCTAssertEqual(error.message, "table player has no column named score")
|
||||
}
|
||||
try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1"])
|
||||
|
||||
// ... unless database gets erased
|
||||
if try dbQueue.read(migrator2.hasSchemaChanges) {
|
||||
try dbQueue.erase()
|
||||
}
|
||||
try migrator2.migrate(dbQueue)
|
||||
try XCTAssertFalse(dbQueue.read(migrator2.hasSchemaChanges))
|
||||
try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1", "2"])
|
||||
}
|
||||
|
||||
func testEraseDatabaseOnSchemaChangeWithConfiguration() throws {
|
||||
// 1st version of the migrator
|
||||
var migrator1 = DatabaseMigrator()
|
||||
@@ -763,7 +851,9 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
|
||||
// ... unless database gets erased
|
||||
migrator2.eraseDatabaseOnSchemaChange = true
|
||||
try XCTAssertTrue(dbQueue.read(migrator2.hasSchemaChanges))
|
||||
try migrator2.migrate(dbQueue)
|
||||
try XCTAssertFalse(dbQueue.read(migrator2.hasSchemaChanges))
|
||||
try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1", "2"])
|
||||
}
|
||||
|
||||
@@ -792,6 +882,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
CREATE TABLE t2(id INTEGER PRIMARY KEY);
|
||||
""")
|
||||
}
|
||||
try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges))
|
||||
try migrator.migrate(dbQueue)
|
||||
try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, sql: "SELECT id FROM t1") }, 1)
|
||||
try XCTAssertTrue(dbQueue.read { try $0.tableExists("t2") })
|
||||
@@ -818,6 +909,7 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
}
|
||||
|
||||
// Then 2nd migration does not erase database
|
||||
try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges))
|
||||
try migrator.migrate(dbQueue)
|
||||
try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, sql: "SELECT id FROM t") }, 1)
|
||||
}
|
||||
@@ -845,7 +937,9 @@ class DatabaseMigratorTests : GRDBTestCase {
|
||||
INSERT INTO t1(id) VALUES (2)
|
||||
""")
|
||||
}
|
||||
try XCTAssertTrue(dbQueue.read(migrator2.hasSchemaChanges))
|
||||
try migrator2.migrate(dbQueue)
|
||||
try XCTAssertFalse(dbQueue.read(migrator2.hasSchemaChanges))
|
||||
try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, sql: "SELECT id FROM t1") }, 2)
|
||||
}
|
||||
|
||||
|
||||
@@ -388,12 +388,35 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
|
||||
try main.inDatabase { db in
|
||||
try db.execute(literal: "ATTACH DATABASE \(attached.path) AS attached")
|
||||
|
||||
let tableExists = try db.tableExists("t")
|
||||
let viewExists = try db.viewExists("v")
|
||||
let triggerExists = try db.triggerExists("tr")
|
||||
XCTAssertTrue(tableExists)
|
||||
XCTAssertTrue(viewExists)
|
||||
XCTAssertTrue(triggerExists)
|
||||
try XCTAssertTrue(db.tableExists("t"))
|
||||
try XCTAssertTrue(db.viewExists("v"))
|
||||
try XCTAssertTrue(db.triggerExists("tr"))
|
||||
|
||||
try XCTAssertFalse(db.tableExists("t", in: "main"))
|
||||
try XCTAssertFalse(db.viewExists("v", in: "main"))
|
||||
try XCTAssertFalse(db.triggerExists("tr", in: "main"))
|
||||
|
||||
try XCTAssertTrue(db.tableExists("t", in: "attached"))
|
||||
try XCTAssertTrue(db.viewExists("v", in: "attached"))
|
||||
try XCTAssertTrue(db.triggerExists("tr", in: "attached"))
|
||||
}
|
||||
}
|
||||
|
||||
func testExistsWithUnspecifiedSchemaFindsTempSchema() throws {
|
||||
try makeDatabaseQueue().inDatabase { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TEMPORARY TABLE t (id INTEGER);
|
||||
CREATE TEMPORARY VIEW v AS SELECT * FROM t;
|
||||
""")
|
||||
|
||||
try XCTAssertTrue(db.tableExists("t"))
|
||||
try XCTAssertTrue(db.viewExists("v"))
|
||||
|
||||
try XCTAssertTrue(db.tableExists("t", in: "temp"))
|
||||
try XCTAssertTrue(db.viewExists("v", in: "temp"))
|
||||
|
||||
try XCTAssertFalse(db.tableExists("t", in: "main"))
|
||||
try XCTAssertFalse(db.viewExists("v", in: "main"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,3 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import XCTest
|
||||
@testable import GRDB
|
||||
|
||||
@@ -565,7 +556,7 @@ class DatabaseRegionTests : GRDBTestCase {
|
||||
//
|
||||
// See also testRowIdNameInUpdateStatement
|
||||
|
||||
guard sqlite3_libversion_number() < 3019003 else {
|
||||
guard Database.sqliteLibVersionNumber < 3019003 else {
|
||||
// This test fails on SQLite 3.19.3 (iOS 11.2) and SQLite 3.21.0 (custom build),
|
||||
// but succeeds on SQLite 3.16.0 (iOS 10.3.1).
|
||||
// TODO: evaluate the consequences
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
// Import C SQLite functions
|
||||
#if SWIFT_PACKAGE
|
||||
import GRDBSQLite
|
||||
#elseif GRDBCIPHER
|
||||
import SQLCipher
|
||||
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
|
||||
import SQLite3
|
||||
#endif
|
||||
|
||||
import XCTest
|
||||
import GRDB
|
||||
|
||||
@@ -208,7 +199,7 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
throw XCTSkip("VACUUM INTO is not available")
|
||||
}
|
||||
// Prevent SQLCipher failures
|
||||
guard sqlite3_libversion_number() >= 3027000 else {
|
||||
guard Database.sqliteLibVersionNumber >= 3027000 else {
|
||||
throw XCTSkip("VACUUM INTO is not available")
|
||||
}
|
||||
|
||||
@@ -373,7 +364,7 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
@available(iOS 14, macOS 10.16, tvOS 14, *) // async + vacuum into
|
||||
func testAsyncAwait_vacuumInto() async throws {
|
||||
// Prevent SQLCipher failures
|
||||
guard sqlite3_libversion_number() >= 3027000 else {
|
||||
guard Database.sqliteLibVersionNumber >= 3027000 else {
|
||||
throw XCTSkip("VACUUM INTO is not available")
|
||||
}
|
||||
|
||||
@@ -424,6 +415,57 @@ class DatabaseWriterTests : GRDBTestCase {
|
||||
|
||||
// MARK: - Task Cancellation
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1715>.
|
||||
func test_write_is_possible_after_read_cancelled_after_database_access() async throws {
|
||||
// When a read access is cancelled, DatabaseQueue needs to execute
|
||||
// `PRAGMA query_only=0` in order to restore the read/write access.
|
||||
//
|
||||
// Here we test that this pragma can run from a cancelled read.
|
||||
//
|
||||
// Small difficulty: some SQLite versions (seen with 3.43.2) execute
|
||||
// the `query_only` pragma at compile time, not only at execution
|
||||
// time (yeah, that's an SQLite bug). The problem of this bug is
|
||||
// that even if the `PRAGMA query_only=0` is not executed due to
|
||||
// Task cancellation, its side effect is still executed when it is
|
||||
// compiled, unintentionally. A cancelled `PRAGMA query_only=0`
|
||||
// still works!
|
||||
//
|
||||
// To avoid this SQLite bug from messing with our test, we perform
|
||||
// two reads: one that compiles and cache `PRAGMA query_only`
|
||||
// statements, and a second read that we cancel. This time the
|
||||
// `PRAGMA query_only=0` triggers its side effect if and only if it
|
||||
// is actually executed (the behavior we are testing).
|
||||
func test(_ dbWriter: some DatabaseWriter) async throws {
|
||||
let semaphore = AsyncSemaphore(value: 0)
|
||||
let cancelledTaskMutex = Mutex<Task<Void, any Error>?>(nil)
|
||||
let task = Task {
|
||||
await semaphore.wait()
|
||||
|
||||
// First read, not cancelled, so that all `query_only`
|
||||
// pragma statements are compiled (see above).
|
||||
try await dbWriter.read { db in }
|
||||
|
||||
// Second read, cancelled.
|
||||
try await dbWriter.read { db in
|
||||
try XCTUnwrap(cancelledTaskMutex.load()).cancel()
|
||||
}
|
||||
}
|
||||
cancelledTaskMutex.store(task)
|
||||
semaphore.signal()
|
||||
// Wait until reads are completed
|
||||
try? await task.value
|
||||
|
||||
// Write access is restored after read cancellation (no error is thrown)
|
||||
try await dbWriter.write { db in
|
||||
try db.execute(sql: "CREATE TABLE test(a)")
|
||||
}
|
||||
}
|
||||
|
||||
try await test(makeDatabaseQueue())
|
||||
try await test(makeDatabasePool())
|
||||
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
|
||||
}
|
||||
|
||||
func test_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws {
|
||||
func test(_ dbWriter: some DatabaseWriter) async throws {
|
||||
let semaphore = AsyncSemaphore(value: 0)
|
||||
|
||||
@@ -174,11 +174,11 @@ class DerivableRequestTests: GRDBTestCase {
|
||||
try libraryMigrator.migrate(dbQueue)
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(view: "authorView", as: Author.select(
|
||||
AllColumns(),
|
||||
.allColumns,
|
||||
[Column("firstName"), Column("lastName")]
|
||||
.joined(operator: .concat)
|
||||
.forKey("fullName")))
|
||||
|
||||
|
||||
// ... for one table
|
||||
clearSQLQueries()
|
||||
let authorNames = try Author.all()
|
||||
@@ -221,7 +221,7 @@ class DerivableRequestTests: GRDBTestCase {
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
SELECT * FROM "author" ORDER BY "id"
|
||||
""")
|
||||
|
||||
|
||||
clearSQLQueries()
|
||||
_ /* stableOrderAuthors */ = try Author.all()
|
||||
.orderByFullName()
|
||||
@@ -267,7 +267,7 @@ class DerivableRequestTests: GRDBTestCase {
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
SELECT * FROM "authorView" ORDER BY 1, 2, 3, 4, 5
|
||||
""")
|
||||
|
||||
|
||||
clearSQLQueries()
|
||||
_ /* stableOrderAuthorViews */ = try Table("authorView").all()
|
||||
.order(Column("fullName"))
|
||||
|
||||
@@ -19,7 +19,7 @@ extension Book : FetchableRecord {
|
||||
|
||||
extension Book : MutablePersistableRecord {
|
||||
static let databaseTableName = "books"
|
||||
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
|
||||
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
|
||||
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container[.rowID] = id
|
||||
|
||||
@@ -13,7 +13,29 @@ class FTS3TableBuilderTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testOptions() throws {
|
||||
func test_option_ifNotExists() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", options: .ifNotExists, using: FTS3())
|
||||
assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"documents\" USING fts3")
|
||||
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func test_option_temporary() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", options: .temporary, using: FTS3())
|
||||
assertDidExecute(sql: "CREATE VIRTUAL TABLE temp.\"documents\" USING fts3")
|
||||
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testLegacyOptions() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", ifNotExists: true, using: FTS3())
|
||||
|
||||
@@ -19,7 +19,7 @@ extension Book : FetchableRecord {
|
||||
|
||||
extension Book : MutablePersistableRecord {
|
||||
static let databaseTableName = "books"
|
||||
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
|
||||
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
|
||||
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container[.rowID] = id
|
||||
|
||||
@@ -13,7 +13,29 @@ class FTS4TableBuilderTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testOptions() throws {
|
||||
func test_option_ifNotExists() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", options: .ifNotExists, using: FTS4())
|
||||
assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"documents\" USING fts4")
|
||||
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func test_option_temporary() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", options: .temporary, using: FTS4())
|
||||
assertDidExecute(sql: "CREATE VIRTUAL TABLE temp.\"documents\" USING fts4")
|
||||
|
||||
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testLegacyOptions() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
try db.create(virtualTable: "documents", ifNotExists: true, using: FTS4())
|
||||
@@ -193,8 +215,8 @@ class FTS4TableBuilderTests: GRDBTestCase {
|
||||
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func testFTS4SynchronizationIfNotExists() throws {
|
||||
|
||||
func testFTS4Synchronization_with_ifNotExists_option() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.writeWithoutTransaction { db in
|
||||
try db.create(table: "documents") { t in
|
||||
@@ -202,7 +224,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
|
||||
t.column("content", .text)
|
||||
}
|
||||
assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)")
|
||||
try db.create(virtualTable: "ft_documents", ifNotExists: true, using: FTS4()) { t in
|
||||
try db.create(virtualTable: "ft_documents", options: .ifNotExists, using: FTS4()) { t in
|
||||
t.synchronize(withTable: "documents")
|
||||
t.column("content")
|
||||
}
|
||||
@@ -210,7 +232,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
|
||||
assertDidExecute(sql: "CREATE TRIGGER IF NOT EXISTS \"__ft_documents_bu\" BEFORE UPDATE ON \"documents\" BEGIN\n DELETE FROM \"ft_documents\" WHERE docid=old.\"id\";\nEND")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func testFTS4SynchronizationCleanup() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
|
||||
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user