Compare commits

..
Author SHA1 Message Date
Gwendal Roué c93ba4fba8 WIP 2025-01-17 17:52:52 +01:00
71 changed files with 478 additions and 3233 deletions

No files matched your search

+1 -1
View File
@@ -50,7 +50,7 @@ jobs:
name: "iOS"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "OS=18.1,name=Apple TV"
destination: "OS=18.0,name=Apple TV"
name: "tvOS"
steps:
- uses: actions/checkout@v4
+29 -49
View File
@@ -7,8 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `7.0.x` Releases - [7.0.0](#700)
- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6) - [7.0.0-beta.7](#700-beta7)
- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6)
#### 6.x Releases
@@ -132,25 +131,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 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
@@ -192,7 +172,7 @@ Released September 29, 2024
[Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) describes in detail how to bump the GRDB version in your application.
The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
The [demo app](Documentation/DemoApps/) was rewritten from scratch in a brand new Xcode 16 project.
@@ -251,8 +231,8 @@ Released July 11, 2024
Released April 21, 2024
- **Fixed**: [#1533](https://github.com/groue/GRDB.swift/pull/1533) by [@groue](https://github.com/groue): Fix a bug in Decodable support
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/singlerowtables) guide was updated with guidance about default configuration values.
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide was updated with guidance about default configuration values.
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
## 6.26.0
@@ -277,7 +257,7 @@ Released February 25, 2024
Released January 21, 2024
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
- **New**: Associations that involve views instead of tables were already supported, with an explicit `ForeignKey` in their definition. When the foreign key is missing, a clear diagnostic message is now emitted, instead of an unhelpful "no such table" runtime error.
## 6.24.1
@@ -304,7 +284,7 @@ Released November 26, 2023
- **New**: [#1452](https://github.com/groue/GRDB.swift/pull/1452) by [@groue](https://github.com/groue): SQLite 3.44.0, FILTER and ORDER BY clauses in aggregate functions
- **New**: [#1460](https://github.com/groue/GRDB.swift/pull/1460) by [@groue](https://github.com/groue): Explicit change notifications help applications deal with undetected database changes.
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
## 6.21.0
@@ -340,8 +320,8 @@ Released October 4, 2023 • [diff](https://github.com/groue/GRDB.swift/compa
- **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions
- **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method.
- **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information.
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/json) article provides an overview of JSON handling.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol.
## 6.18.0
@@ -365,14 +345,14 @@ Released July 9, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/
- **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13
- **New**: :star: [#1405](https://github.com/groue/GRDB.swift/pull/1405) Simplify the declaration of BelongsTo associations in the database schema
- **Documentation Update**: The documentation was updated for the new recommended way to declare associations in the database schema, with the `belongsTo()` method introduced by [#1405](https://github.com/groue/GRDB.swift/pull/1405):
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
- [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema)
- [Migrations](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations)
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices)
- [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:))
- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema)
- [Migrations](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations)
- [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
- [Associations](Documentation/AssociationsBasics.md)
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/belongstoassociation)
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/hasmanyassociation)
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/hasoneassociation)
- [`BelongsToAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/belongstoassociation)
- [`HasManyAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasmanyassociation)
- [`HasOneAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasoneassociation)
## 6.15.1
@@ -389,7 +369,7 @@ Released June 2, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/
- **New**: [#1382](https://github.com/groue/GRDB.swift/pull/1382) Add `DerivableRequest.all()`
- **New**: [#1384](https://github.com/groue/GRDB.swift/pull/1384) Allow ValueObservation to start from a truncated wal file
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`.
## 6.14.0
@@ -424,7 +404,7 @@ Released April 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compar
Released April 10, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.1...v6.10.2)
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC.
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC.
- **Documentation Update**: The [Demo Applications](Documentation/DemoApps/) demonstrate how their `AppDatabase` "database manager" can provide a base database configuration.
## 6.10.1
@@ -451,8 +431,8 @@ Released March 14, 2023 • [diff](https://github.com/groue/GRDB.swift/compar
Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.0...v6.9.1)
- **Documentation Updates**: Moved more README chapters into DocC:
- [`RowAdapter`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter)
- [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:))
- [`RowAdapter`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter)
- [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:))
## 6.9.0
@@ -461,9 +441,9 @@ Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compar
- **New**: [#1348](https://github.com/groue/GRDB.swift/pull/1348) by [@groue](https://github.com/groue): SQLite argument binding optimization
- **New**: `FTS5.api(db)` returns a pointer to the `fts5_api` structure, useful for low-level [FTS5 customization](https://www.sqlite.org/fts5.html#extending_fts5).
- **Documentation Updates**: Moved more README chapters into DocC, enhanced and extended DocC articles:
- [Database Connections](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections)
- [Prepared Statements](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statement)
- [DatabaseValueConvertible](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasevalueconvertible)
- [Database Connections](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections)
- [Prepared Statements](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement)
- [DatabaseValueConvertible](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible)
## 6.8.0
@@ -471,7 +451,7 @@ Released February 24, 2023 • [diff](https://github.com/groue/GRDB.swift/com
- **New**: [#1338](https://github.com/groue/GRDB.swift/pull/1338) by [@groue](https://github.com/groue): TimestampedRecord sample code
- **New**: `EncodableRecord.databaseChanges(modify:)` modifies a record and returns a dictionary of applied changes.
- **Documentation Update**: The [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps) article provides a sample `TimestampedRecord` protocol that application may adapt for their own use.
- **Documentation Update**: The [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article provides a sample `TimestampedRecord` protocol that application may adapt for their own use.
## 6.7.0
@@ -482,7 +462,7 @@ Released February 19, 2023 • [diff](https://github.com/groue/GRDB.swift/com
- **Fixed**: [#1327](https://github.com/groue/GRDB.swift/pull/1327) by [@groue](https://github.com/groue): Remove dependency on any specific SwiftLint version.
- **New**: [#1331](https://github.com/groue/GRDB.swift/pull/1331) by [@groue](https://github.com/groue): Transaction Date
- **New**: [#1336](https://github.com/groue/GRDB.swift/pull/1336) by [@groue](https://github.com/groue): Enable FTS5 by default
- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records.
- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records.
- Added support for `Table` in SQL interpolation.
## 6.6.1
@@ -512,11 +492,11 @@ Released November 28, 2022 • [diff](https://github.com/groue/GRDB.swift/com
- **New**: `DatabaseReader.configuration.readQoS` and `writeQoS` return the effective quality of service of read-only and write database accesses. This helps application code avoid priority inversion and similar scheduling misuses when needed.
- **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed.
- **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime.
- **New**: A new [`DatabaseSnapshotReader`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesnapshotreader) protocol was introduced for types that see an unchanging database content (`DatabaseSnapshot` and the new `DatabaseSnapshotPool`).
- **New**: [`Database.registerAccess(to:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/registeraccess(to:)) has `ValueObservation` track a region. This helps building optimized observations of a constant database region with [`ValueObservation.trackingConstantRegion(_:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/trackingconstantregion(_:)).
- **New**: Open several connections to the same in-memory database with [`DatabaseQueue(named:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue/init(named:configuration:)).
- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tabledefinition) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended.
- **New**: The [Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) documentation article has a brand new "Database Schema Recommendations" section.
- **New**: A new [`DatabaseSnapshotReader`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshotreader) protocol was introduced for types that see an unchanging database content (`DatabaseSnapshot` and the new `DatabaseSnapshotPool`).
- **New**: [`Database.registerAccess(to:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/registeraccess(to:)) has `ValueObservation` track a region. This helps building optimized observations of a constant database region with [`ValueObservation.trackingConstantRegion(_:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/trackingconstantregion(_:)).
- **New**: Open several connections to the same in-memory database with [`DatabaseQueue(named:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue/init(named:configuration:)).
- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended.
- **New**: The [Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) documentation article has a brand new "Database Schema Recommendations" section.
- **New**: Multiple improvements to the DocC documentation.
## 6.3.1
+1 -1
View File
@@ -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).
+5 -5
View File
@@ -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
View File
@@ -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 -1
View File
@@ -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).
+2 -2
View File
@@ -5,7 +5,7 @@ By default, GRDB uses the version of SQLite that ships with the target operating
**You can build GRDB with a custom build of [SQLite 3.47.2](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver).
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
@@ -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()
@@ -77,7 +77,7 @@ extension AppDatabase {
// }
//
// Uncomment for enabling SQL logging if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/trace(options:_:)>
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
// if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
// config.prepareDatabase { db in
// let dbName = db.description
@@ -93,7 +93,7 @@ extension AppDatabase {
// #if DEBUG
// // Protect sensitive information by enabling verbose debugging in
// // DEBUG builds only.
// // See <https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/configuration/publicstatementarguments>
// // See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
// config.publicStatementArguments = true
// #endif
@@ -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)
}
+3 -3
View File
@@ -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).
+1 -1
View File
@@ -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.
+3 -3
View File
@@ -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,
@@ -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
+4 -4
View File
@@ -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
+1 -1
View File
@@ -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:
+7 -55
View File
@@ -10,7 +10,6 @@ Migrating From GRDB 6 to GRDB 7
- [Column Coding Strategies](#column-coding-strategies)
- [Cancellable Async Database Accesses](#cancellable-async-database-accesses)
- [Default Transaction Kind](#default-transaction-kind)
- [Associations to record types named Bias, Focus, Gas, and Lens](#associations-to-record-types-named-bias-focus-gas-and-lens)
- [ValueObservation and the Main Actor](#valueobservation-and-the-main-actor)
- [Access to SQLite C functions](#access-to-sqlite-c-functions)
- [The Record Base Class is Discouraged](#the-record-base-class-is-discouraged)
@@ -97,53 +96,6 @@ try await task.value
Other asynchronous database accesses, such as methods accepting a completion blocks (`asyncRead`, etc.), Combine publishers, RxSwift observables, do not handle cancellation and will proceed to completion by default.
## Associations to record types named Bias, Focus, Gas, and Lens
GRDB 7 has fixed its singularization and pluralization rules for database tables named "bias", "focus", "gas", and "lens".
If your application defines associations to those tables, you can now rely on proper inflections (pluralization and singularization).
With GRDB 7, you can remove custom association keys:
```swift
struct Camera: TableRecord {
// GRDB 6: fix incorrect GRDB inflection
static let lenses = hasMany(Lens.self).forKey("lenses")
// GRDB 7
static let lenses = hasMany(Lens.self)
}
```
If your application was not specifying custom association keys in order to fix the wrong inflections, then it may define types that will no longer decode their properties as intended:
```swift
// Works in GRDB 6, breaks in GRDB 7
struct CameraWithLenses: Decodable, FetchableRecord {
var camera: Camera
var lens: [Lens] // <- incorrect pluralization
}
let results = Camera
.including(all: Camera.lenses)
.asRequest(of: CameraWithLenses.self)
.fetchAll(db)
```
There are two possible solutions. One is to rename properties, the other is to keep on using the wrong inflection (it's your call):
```swift
// GRDB 7, alternative 1
struct CameraWithLenses: Decodable, FetchableRecord {
var camera: Camera
var lenses: [Lens] // <- fixed pluralization
}
// GRDB 7, alternative 2
struct Camera: TableRecord {
// Use "lens" instead of "lenses" for GRDB 6 compatibility.
static let lenses = hasMany(Lens.self).forKey("lens")
}
```
## Default Transaction Kind
Some applications specify a default transaction kind, which was previously recommended in the [Sharing a Database] guide:
@@ -162,7 +114,7 @@ You can still specify a transaction kind explicitly when necessary. See [Transac
In GRDB 7, `ValueObservation` fosters the main actor, because it is frequently used to automatically update database values on screen.
By default, its [`start`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be started on the main actor, and its notification callbacks run on the main actor as well.
By default, its [`start`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be started on the main actor, and its notification callbacks run on the main actor as well.
It is not necessary to call `MainActor.assumeIsolated` in `ValueObservation` callbacks:
@@ -269,14 +221,14 @@ Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non
## Other Changes
- `DatabasePool.concurrentRead` has been removed. Use [`asyncConcurrentRead`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool/asyncconcurrentread(_:)) instead.
- `DatabasePool.concurrentRead` has been removed. Use [`asyncConcurrentRead`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool/asyncconcurrentread(_:)) instead.
- The `PersistenceContainer` subscript no longer guarantees that the value returned is the same as what was previously set. It only guarantees that both values are encoded identically in the database.
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/GRDB.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/grdb.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide
[Sharing a Database]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing
[Transaction Kinds]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactions#Transaction-Kinds
[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/swiftconcurrency
[Record]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/record
[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databasesharing
[Transaction Kinds]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/transactions#Transaction-Kinds
[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/swiftconcurrency
[Record]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/record
@@ -1,4 +1,4 @@
Good Practices for Designing Record Types
=========================================
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
+1 -1
View File
@@ -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).
+5 -5
View File
@@ -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
+1 -1
View File
@@ -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 -1
View File
@@ -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 -1
View File
@@ -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).
+8 -8
View File
@@ -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
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.0.0'
s.version = '7.0.0-beta.6'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
-3
View File
@@ -2058,9 +2058,6 @@ 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")
+10 -4
View File
@@ -4,11 +4,17 @@ GRDB helps your app deal with Swift and SQLite concurrency.
## Overview
If your app moves slow database jobs off the main thread, so that the user interface remains responsive, then this guide is for you. In the case of apps that share a database with other processes, such as an iOS app and its extensions, don't miss the dedicated <doc:DatabaseSharing> guide after this one.
If your app moves slow database jobs off the main thread, so that the user interface remains responsive, then this guide is for you.
**In all cases, and first and foremost, follow the <doc:Concurrency#Concurrency-Rules> right from the start.**
It is extended with three articles that focus on particular aspects of concurrency:
The other chapters cover, with more details, the fundamentals of SQLite concurrency, and how GRDB makes it manageable from your Swift code.
- <doc:DatabaseSharing>: for apps that **share a database** with other processes, such as an iOS app and its extensions
- <doc:SwiftConcurrency>: the relationships between GRDB and **Swift 6 Concurrency**
- <doc:MainThread>: everything you have to known about GRDB and the main thread.
**In all cases, and first and foremost, follow the Concurrency-Rules, below, right from the start.**
The following chapters cover the fundamentals of SQLite concurrency, and how GRDB makes it manageable from your Swift code.
## Concurrency Rules
@@ -322,7 +328,7 @@ Types that conform to ``TransactionObserver`` can also use those methods in thei
- <doc:SwiftConcurrency>
- <doc:DatabaseSharing>
- <doc:MainThread>
[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
[`SQLITE_BUSY`]: https://www.sqlite.org/rescode.html#busy
@@ -151,7 +151,7 @@ extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
static var databaseSelection: [any SQLSelectable] {
[.allColumns, .rowID]
[AllColumns(), Column.rowID]
}
// Update id upon successful insertion
@@ -107,10 +107,10 @@ import GRDB
import Tagged
// Add database support to Tagged values
extension Tagged: @retroactive SQLExpressible where RawValue: SQLExpressible { }
extension Tagged: @retroactive StatementBinding where RawValue: StatementBinding { }
extension Tagged: @retroactive StatementColumnConvertible where RawValue: StatementColumnConvertible { }
extension Tagged: @retroactive DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
extension Tagged: SQLExpressible where RawValue: SQLExpressible { }
extension Tagged: StatementBinding where RawValue: StatementBinding { }
extension Tagged: StatementColumnConvertible where RawValue: StatementColumnConvertible { }
extension Tagged: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
```
This makes it possible to use `Tagged` values in all the expected places:
+30
View File
@@ -0,0 +1,30 @@
# Using or Avoiding the Main Thread
Everything you have to known about GRDB and the main thread.
## Overview
**This guide describes the relationship between GRDB and the main thread.** It complements the <doc:Concurrency> guide, that you should read first.
Accessing the database from the main thread is handy. Graphical applications, for example, do not need to show a loading screen until values are fetched and ready for display. They do not need to spawn tasks or any other asynchronous constructs in response to user actions.
There are only two things one should think about when accessing the database from the main thread:
- How long does it take to start the database access?
- How long does it take to execute the database requests?
The first delay depends on *database contention*
The first delay can be slowed down if the database is already busy
SQLite is very fast, and many database accesses are so fast that the user has no time to notice them. In a graphical application, performing fast database accesses from the main thread is handy, because the application does not need to show a loading screen until values are fetched and ready for display.
Other database accesses should be performed in a background thread, in order to avoid user interface freezes.
In the end, accessing the database on or off the main thread is a choice left to the application.
The database can be accessed from the main thread, or from a background thread, at the application convenience. In this guide we explain what you have to know when you intend to access the database from the main thread, or when you want to make sure a database access does not block the main thread. We will discuss plain database accesses (`read`, `write`), as well a database observation with ``ValueObservation``.
### Avoiding the Main Thread
To avoid performing database accesses from the main thread,
<!--@START_MENU_TOKEN@-->Text<!--@END_MENU_TOKEN@-->
+1 -1
View File
@@ -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 }
@@ -4,6 +4,8 @@ How to best integrate GRDB and Swift Concurrency
## Overview
**This guide describes the relationship between GRDB and Swift 6 Concurrency.** It complements the <doc:Concurrency> guide, that you should read first.
GRDB’s primary goal is to leverage SQLite’s concurrency features for the benefit of application developers. Swift 6 makes it possible to achieve this goal while ensuring data-race safety.
For example, the ``DatabasePool`` connection allows applications to fetch and display database values on screen, even while a background task is writing the results of a network request to disk.
+2 -337
View File
@@ -1,6 +1,4 @@
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// MARK: - JSON
extension Database {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
@@ -341,19 +339,8 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jvalid>
///
/// - 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])
}
public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_VALID", [value.sqlExpression])
}
/// The `JSON_QUOTE` SQL function.
@@ -432,329 +419,7 @@ 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.
///
-7
View File
@@ -61,13 +61,6 @@ 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 }
}
+3 -42
View File
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// An SQL expression.
///
/// `SQLExpression` is an opaque representation of an SQL expression.
@@ -963,17 +954,6 @@ 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",
@@ -1025,16 +1005,6 @@ 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.
@@ -2129,9 +2099,8 @@ extension SQLExpression {
case .jsonValue:
if isJSONValue {
return self
} else if sqlite3_libversion_number() >= 3045000 {
return .function("JSONB", [self])
} else {
// Needs explicit call to JSON()
return .function("JSON", [self])
}
}
@@ -2147,9 +2116,8 @@ extension SQLExpression {
case .jsonValue:
if isJSONValue {
return self
} else if sqlite3_libversion_number() >= 3045000 {
return .function("JSONB", [self])
} else {
// Needs explicit call to JSON()
return .function("JSON", [self])
}
}
@@ -2168,14 +2136,7 @@ public protocol SQLExpressible {
}
extension SQLExpressible where Self == Column {
/// The hidden rowID column.
///
/// For example:
///
/// ```swift
/// // SELECT rowid FROM player
/// let rowids = try Player.select(.rowID).fetchSet(db)
/// ```
/// The hidden rowID column
public static var rowID: Self { Column.rowID }
}
+1 -1
View File
@@ -636,7 +636,7 @@ extension SQLRelation {
}
// <https://github.com/groue/GRDB.swift/issues/1357>
if selection.contains(where: \.requiresTrivialCount) {
guard selection.allSatisfy(\.isTriviallyCountable) else {
return try fetchTrivialCount(db)
}
+45 -211
View File
@@ -26,12 +26,6 @@ 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)
@@ -47,21 +41,11 @@ 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))
@@ -86,16 +70,13 @@ extension SQLSelection {
/// Returns nil when the number of columns is unknown.
func columnCount(_ context: SQLGenerationContext) throws -> Int? {
switch impl {
case .allColumns, .allColumnsExcluding:
case .allColumns:
// 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, excluding: [])
case let .qualifiedAllColumnsExcluding(alias, excludedColumns):
return try context.columnCount(in: alias.tableName, excluding: excludedColumns)
return try context.columnCount(in: alias.tableName)
case .expression,
.aliasedExpression:
@@ -123,28 +104,7 @@ extension SQLSelection {
// SELECT COUNT(*) FROM tableName ...
return .all
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:
case .qualifiedAllColumns:
return nil
case let .expression(expression),
@@ -166,6 +126,41 @@ 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:
@@ -184,38 +179,11 @@ 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)
@@ -260,15 +228,12 @@ extension SQLSelection {
/// Returns a qualified selection
func qualified(with alias: TableAlias) -> SQLSelection {
switch impl {
case .qualifiedAllColumns, .qualifiedAllColumnsExcluding:
case .qualifiedAllColumns:
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))
@@ -280,27 +245,15 @@ 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 requiresTrivialCount: Bool {
var isTriviallyCountable: Bool {
switch impl {
case .aliasedExpression, .literal:
// 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 false
case .allColumns, .qualifiedAllColumns, .expression:
return true
case .allColumns, .qualifiedAllColumns:
return false
case .allColumnsExcluding, .qualifiedAllColumnsExcluding:
return false
case .expression:
return false
}
}
}
@@ -344,41 +297,15 @@ 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")
@@ -392,14 +319,10 @@ extension SQLSelection: SQLSelectable {
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns, .rowID]
/// }
/// try dbQueue.read { db in
/// // SELECT * FROM player
/// let players = try Player.select(AllColumns()).fetchAll(db)
/// }
///
/// // SELECT *, rowid FROM player
/// Player.fetchAll(db)
/// ```
public struct AllColumns: Sendable {
/// The `*` selection.
@@ -411,92 +334,3 @@ 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))
}
}
@@ -153,50 +153,15 @@ final class SQLGenerationContext {
return nil
}
/// 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 {
func columnCount(in tableName: String) throws -> Int {
if let cte = ownCTEs[tableName.lowercased()] {
if excludedColumns.isEmpty {
return try cte.columnCount(db)
} else {
fatalError("Not implemented: counting CTE columns with excluded columns")
}
return try cte.columnCount(db)
}
switch parent {
case let .context(context):
return try context.columnCount(in: tableName, excluding: excludedColumns)
return try context.columnCount(in: tableName)
case let .none(db: db, argumentsSink: _):
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)
return try db.columns(in: tableName).count
}
}
}
@@ -235,11 +235,7 @@ struct SQLQueryGenerator: Refinable {
sql += " LIMIT " + limit.sql
}
return try makeStatement(
db, sql: sql,
arguments: context.arguments,
returning: selection,
from: relation.source.tableName)
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
case .unique:
return try makeTrivialDeleteStatement(db, selection: selection)
@@ -268,11 +264,7 @@ struct SQLQueryGenerator: Refinable {
sql += try selectPrimaryKey.requestSQL(subqueryContext)
sql += ")"
return try makeStatement(
db, sql: sql,
arguments: context.arguments,
returning: selection,
from: tableName)
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
}
/// Returns an `UPDATE` statement, with `RETURNING` clause if `selection`
@@ -331,11 +323,7 @@ struct SQLQueryGenerator: Refinable {
sql += " LIMIT " + limit.sql
}
return try makeStatement(
db, sql: sql,
arguments: context.arguments,
returning: selection,
from: relation.source.tableName)
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
case .unique:
return try makeTrivialUpdateStatement(
@@ -392,11 +380,7 @@ struct SQLQueryGenerator: Refinable {
sql += try selectPrimaryKey.requestSQL(subqueryContext)
sql += ")"
return try makeStatement(
db, sql: sql,
arguments: context.arguments,
returning: selection,
from: tableName)
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
}
// Support for the RETURNING clause
@@ -404,8 +388,7 @@ struct SQLQueryGenerator: Refinable {
_ db: Database,
sql: String,
arguments: StatementArguments,
returning selection: [any SQLSelectable],
from tableName: String)
returning selection: [any SQLSelectable])
throws -> Statement
{
if selection.isEmpty {
@@ -413,17 +396,12 @@ struct SQLQueryGenerator: Refinable {
statement.arguments = arguments
return statement
} else {
// 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])
let context = SQLGenerationContext(db)
var sql = sql
var arguments = arguments
sql += " RETURNING "
sql += try selection
.map { try $0.sqlSelection.qualified(with: alias).sql(context) }
.map { try $0.sqlSelection.sql(context) }
.joined(separator: ", ")
arguments += context.arguments
let statement = try db.makeStatement(sql: sql)
@@ -67,12 +67,7 @@ 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) {
// 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)
let alias = TableAlias(name: tableAlias ?? recordType.databaseTableName)
elements.append(contentsOf: recordType.databaseSelection
.map { CollectionOfOne(.selection($0.sqlSelection.qualified(with: alias))) }
.joined(separator: CollectionOfOne(.sql(", "))))
@@ -84,7 +79,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))
@@ -94,7 +89,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,32 +370,6 @@ 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:
@@ -435,32 +409,6 @@ 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:
@@ -499,32 +447,6 @@ 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:
@@ -565,32 +487,6 @@ 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:
@@ -249,17 +249,12 @@ final class DAO<Record: MutablePersistableRecord> {
statement.setUncheckedArguments(arguments)
return statement
} else {
// 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])
let context = SQLGenerationContext(db)
var sql = sql
var arguments = arguments
sql += " RETURNING "
sql += try selection
.map { try $0.sqlSelection.qualified(with: alias).sql(context) }
.map { try $0.sqlSelection.sql(context) }
.joined(separator: ", ")
arguments += context.arguments
let statement = try db.internalCachedStatement(sql: sql)
+1 -1
View File
@@ -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.
+4 -14
View File
@@ -134,9 +134,8 @@ public protocol TableRecord {
///
/// ```swift
/// struct Player: TableRecord {
/// // This is the default
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns]
/// [AllColumns()]
/// }
/// }
///
@@ -147,20 +146,11 @@ 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
@@ -178,7 +168,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 }
}
@@ -225,9 +215,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()]
}
}
+3 -2
View File
@@ -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|bias|canvas|focus|gas|lens|status)$", "$1es")
inflections.plural("(alias|status)$", "$1es")
inflections.plural("(bu)s$", "$1ses")
inflections.plural("(buffal|tomat|her)o$", "$1oes")
inflections.plural("([ti])um$", "$1a")
@@ -102,12 +102,13 @@ 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|bias|canvas|focus|gas|lens|status)(es)?$", "$1")
inflections.singular("(alias|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",
+124 -144
View File
@@ -15,13 +15,13 @@
<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**: January 26, 2025 • [version 7.0.0](https://github.com/groue/GRDB.swift/tree/v7.0.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Latest release**: October 13, 2024 • [version 7.0.0-beta.6](https://github.com/groue/GRDB.swift/tree/v7.0.0-beta.6) • [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+ &bull; SQLite 3.20.0+ &bull; Swift 6+ / Xcode 16+
**Contact**:
- Release announcements and usage tips: follow [@groue@hachyderm.io](https://hachyderm.io/@groue) on Mastodon.
- Release announcements and usage tips: follow [@groue](http://twitter.com/groue) on Twitter, [@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 &bull; [create tables, indexes, etc](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) &bull; [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md)
- [Query Interface](#the-query-interface): A swift way to generate SQL &bull; [create tables, indexes, etc](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databaseschema) &bull; [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](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschemaintrospection)
- [Row Adapters](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter)
- [Database Schema Introspection](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/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
@@ -928,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.**
@@ -954,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"]
@@ -1040,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.).
@@ -1111,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 = ...
@@ -1437,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*.
@@ -1518,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:
@@ -1643,7 +1643,7 @@ 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/v7.0.0-beta.6/documentation/grdb/databaseschema) first.
To define a record type, define a type and extend it with protocols that come with focused sets of features.
@@ -1667,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.
@@ -1869,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:
@@ -1949,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:
@@ -2000,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.**
@@ -2431,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.
@@ -2439,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 {
@@ -2466,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
@@ -2645,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
@@ -2669,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).
@@ -2789,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
@@ -2969,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
@@ -3250,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/v7.0.0-beta.6/documentation/grdb/databaseschema)
- [Requests](#requests)
- [Expressions](#expressions)
- [SQL Operators](#sql-operators)
@@ -3269,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:
@@ -3325,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
@@ -3334,21 +3334,21 @@ 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.
- [`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
@@ -3358,7 +3358,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
@@ -3367,14 +3367,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)
@@ -3384,7 +3384,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
@@ -3394,7 +3394,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
@@ -3410,7 +3410,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'
@@ -3420,7 +3420,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
@@ -3429,7 +3429,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
@@ -3439,7 +3439,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.*
@@ -3450,7 +3450,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
@@ -3474,7 +3474,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
@@ -3488,7 +3488,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
@@ -3498,7 +3498,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.*
@@ -3507,7 +3507,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
@@ -3517,7 +3517,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
@@ -3530,7 +3530,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
@@ -3543,7 +3543,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:
@@ -3567,7 +3567,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)
@@ -3604,42 +3604,22 @@ 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. For example:
The default selection for a record type is controlled by the `databaseSelection` property:
```swift
// Select a limited set of columns
struct RestrictedPlayer : TableRecord {
static let databaseTableName = "player"
static var databaseSelection: [any SQLSelectable] {
[Column("id"), Column("name")]
}
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]
}
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
}
// SELECT id, name FROM player
let request = RestrictedPlayer.all()
// SELECT *, rowid FROM player
let request = ExtendedPlayer.all()
```
@@ -3654,7 +3634,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.
@@ -3924,7 +3904,7 @@ 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.
@@ -4501,7 +4481,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 {
@@ -4517,7 +4497,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
@@ -4588,7 +4568,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
@@ -4596,7 +4576,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
@@ -4623,7 +4603,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).
@@ -4778,7 +4758,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.
@@ -4940,7 +4920,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:
@@ -4972,7 +4952,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**.
@@ -5014,7 +4994,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:
@@ -5050,7 +5030,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"]
@@ -5295,7 +5275,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:
@@ -5354,7 +5334,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
@@ -5396,7 +5376,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
@@ -5434,7 +5414,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.
@@ -5471,7 +5451,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?
@@ -5776,7 +5756,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).
@@ -5851,15 +5831,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
@@ -5867,7 +5847,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
@@ -5883,27 +5863,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
@@ -5915,7 +5895,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
@@ -5933,19 +5913,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
@@ -5961,15 +5941,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
@@ -5981,23 +5961,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
@@ -6016,7 +5996,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
@@ -6026,40 +6006,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
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>7.0.0</string>
<string>7.0.0-beta.6</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -66,16 +66,6 @@ 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)
@@ -92,14 +82,6 @@ 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)
@@ -131,15 +113,6 @@ 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)
@@ -180,16 +153,6 @@ 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)
@@ -206,14 +169,6 @@ 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)
@@ -245,15 +200,6 @@ 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,8 +5,7 @@ import GRDB
private struct A : TableRecord {
static let databaseTableName = "a"
static let b = belongsTo(B.self)
static let restrictedB1 = belongsTo(RestrictedB1.self)
static let restrictedB2 = belongsTo(RestrictedB2.self)
static let restrictedB = belongsTo(RestrictedB.self)
static let extendedB = belongsTo(ExtendedB.self)
}
@@ -15,19 +14,14 @@ private struct B : TableRecord {
static let databaseTableName = "b"
}
private struct RestrictedB1 : TableRecord {
private struct RestrictedB : 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, .rowID] }
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
}
/// Test SQL generation
@@ -54,12 +48,7 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
FROM "a" \
JOIN "b" ON "b"."id" = "a"."bid"
""")
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), """
try assertEqualSQL(db, A.including(required: A.restrictedB), """
SELECT "a".*, "b"."name" \
FROM "a" \
JOIN "b" ON "b"."id" = "a"."bid"
@@ -87,8 +76,8 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
do {
let request = A.including(required: A.b
.select(
.allColumns,
.rowID))
AllColumns(),
Column.rowID))
try assertEqualSQL(db, request, """
SELECT "a".*, "b".*, "b"."rowid" \
FROM "a" \
@@ -100,9 +89,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,16 +76,6 @@ 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
@@ -149,16 +139,6 @@ 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
@@ -249,16 +229,6 @@ 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
@@ -322,16 +292,6 @@ 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
@@ -420,16 +380,6 @@ 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
@@ -493,16 +443,6 @@ 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
@@ -566,16 +506,6 @@ 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
@@ -669,16 +599,6 @@ 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
@@ -742,16 +662,6 @@ 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
@@ -815,17 +725,7 @@ 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
""")
@@ -888,16 +788,6 @@ 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
@@ -992,11 +882,6 @@ 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)
@@ -1106,11 +991,6 @@ 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)
@@ -1188,11 +1068,6 @@ 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)
@@ -1301,11 +1176,6 @@ 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)
@@ -1383,11 +1253,6 @@ 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)
@@ -1465,11 +1330,6 @@ 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)
@@ -1587,11 +1447,6 @@ 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)
@@ -1669,11 +1524,6 @@ 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)
@@ -1751,11 +1601,6 @@ 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)
@@ -1833,11 +1678,6 @@ 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)
@@ -1859,7 +1699,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
""")
@@ -2056,11 +1896,6 @@ 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
@@ -2124,11 +1959,6 @@ 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
@@ -2192,11 +2022,6 @@ 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,8 +5,7 @@ import GRDB
private struct A : TableRecord {
static let databaseTableName = "a"
static let b = hasOne(B.self)
static let restrictedB1 = hasOne(RestrictedB1.self)
static let restrictedB2 = hasOne(RestrictedB2.self)
static let restrictedB = hasOne(RestrictedB.self)
static let extendedB = hasOne(ExtendedB.self)
}
@@ -15,19 +14,14 @@ private struct B : TableRecord {
static let databaseTableName = "b"
}
private struct RestrictedB1 : TableRecord {
private struct RestrictedB : 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, .rowID] }
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
}
/// Test SQL generation
@@ -54,16 +48,11 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
FROM "a" \
JOIN "b" ON "b"."aid" = "a"."id"
""")
try assertEqualSQL(db, A.including(required: A.restrictedB1), """
try assertEqualSQL(db, A.including(required: A.restrictedB), """
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" \
@@ -87,8 +76,8 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
do {
let request = A.including(required: A.b
.select(
.allColumns,
.rowID))
AllColumns(),
Column.rowID))
try assertEqualSQL(db, request, """
SELECT "a".*, "b".*, "b"."rowid" \
FROM "a" \
@@ -100,9 +89,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,34 +4,27 @@ 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 restrictedC1 = hasOne(RestrictedC1.self, through: b, using: B.restrictedC1)
static let restrictedC2 = hasOne(RestrictedC2.self, through: b, using: B.restrictedC2)
static let restrictedC = hasOne(RestrictedC.self, through: b, using: B.restrictedC)
static let extendedC = hasOne(ExtendedC.self, through: b, using: B.extendedC)
}
private struct B: TableRecord {
static let c = belongsTo(C.self)
static let restrictedC1 = belongsTo(RestrictedC1.self)
static let restrictedC2 = belongsTo(RestrictedC2.self)
static let restrictedC = belongsTo(RestrictedC.self)
static let extendedC = belongsTo(ExtendedC.self)
}
private struct C: TableRecord {
}
private struct RestrictedC1 : TableRecord {
private struct RestrictedC : 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, .rowID] }
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
}
/// Test SQL generation
@@ -63,13 +56,7 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase {
JOIN "b" ON "b"."id" = "a"."bId" \
JOIN "c" ON "c"."id" = "b"."cId"
""")
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), """
try assertEqualSQL(db, A.including(required: A.restrictedC), """
SELECT "a".*, "c"."name" \
FROM "a" \
JOIN "b" ON "b"."id" = "a"."bId" \
@@ -100,8 +87,8 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase {
do {
let request = A.including(required: A.c
.select(
.allColumns,
.rowID))
AllColumns(),
Column.rowID))
try assertEqualSQL(db, request, """
SELECT "a".*, "c".*, "c"."rowid" \
FROM "a" \
+4 -4
View File
@@ -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"))
+1 -1
View File
@@ -19,7 +19,7 @@ extension Book : FetchableRecord {
extension Book : MutablePersistableRecord {
static let databaseTableName = "books"
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
func encode(to container: inout PersistenceContainer) {
container[.rowID] = id
+1 -1
View File
@@ -19,7 +19,7 @@ extension Book : FetchableRecord {
extension Book : MutablePersistableRecord {
static let databaseTableName = "books"
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
func encode(to container: inout PersistenceContainer) {
container[.rowID] = id
+1 -1
View File
@@ -20,7 +20,7 @@ extension Book : FetchableRecord {
extension Book : MutablePersistableRecord {
static let databaseTableName = "books"
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
func encode(to container: inout PersistenceContainer) {
container[.rowID] = id
+1 -19
View File
@@ -124,25 +124,7 @@
"hero" : "heroes",
"foot" : "feet",
"matrix" : "matrices",
"watch" : "watches",
"lens" : "lenses",
"focus" : "focuses",
"class" : "classes",
"glass" : "glasses",
"brush" : "brushes",
"match" : "matches",
"address" : "addresses",
"bias" : "biases",
"compass" : "compasses",
"crisis" : "crises",
"dress" : "dresses",
"gas" : "gases",
"guess" : "guesses",
"kiss" : "kisses",
"loss" : "losses",
"pass" : "passes",
"success" : "successes",
"witness" : "witnesses"
"watch" : "watches"
},
"Irregularities": {
File diff suppressed because it is too large. Load diff
@@ -1802,7 +1802,7 @@ extension MutablePersistableRecordTests {
try dbQueue.inDatabase { db in
var player = FullPlayer(id: 1, name: "Arthur", score: 1000)
do {
_ = try player.updateAndFetch(db, selection: [.allColumns]) { statement in
_ = try player.updateAndFetch(db, selection: [AllColumns()]) { statement in
try Row.fetchOne(statement)
}
XCTFail("Expected RecordError")
@@ -1813,7 +1813,7 @@ extension MutablePersistableRecordTests {
player.score = 0
do {
let row = try player.updateAndFetch(db, selection: [.allColumns]) { statement in
let row = try player.updateAndFetch(db, selection: [AllColumns()]) { statement in
try Row.fetchOne(statement)
}
XCTAssertEqual(row, ["id": 1, "name": "Barbara", "score": 0])
@@ -1856,7 +1856,7 @@ extension MutablePersistableRecordTests {
try dbQueue.inDatabase { db in
var player = FullPlayer(id: 1, name: "Arthur", score: 1000)
do {
_ = try player.updateAndFetch(db, columns: [Column("score")], selection: [.allColumns]) { statement in
_ = try player.updateAndFetch(db, columns: [Column("score")], selection: [AllColumns()]) { statement in
try Row.fetchOne(statement)
}
XCTFail("Expected RecordError")
@@ -1867,7 +1867,7 @@ extension MutablePersistableRecordTests {
player.score = 0
do {
let row = try player.updateAndFetch(db, columns: [Column("score")], selection: [.allColumns]) { statement in
let row = try player.updateAndFetch(db, columns: [Column("score")], selection: [AllColumns()]) { statement in
try Row.fetchOne(statement)
}
XCTAssertEqual(row, ["id": 1, "name": "Arthur", "score": 0])
@@ -2032,7 +2032,7 @@ extension MutablePersistableRecordTests {
var player = FullPlayer(id: 1, name: "Arthur", score: 1000)
do {
_ = try player.updateChangesAndFetch(
db, selection: [.allColumns],
db, selection: [AllColumns()],
fetch: { statement in try Row.fetchOne(statement) },
modify: { $0.name = "Barbara" })
XCTFail("Expected RecordError")
@@ -2043,7 +2043,7 @@ extension MutablePersistableRecordTests {
do {
// Update with no change
let update = try player.updateChangesAndFetch(
db, selection: [.allColumns],
db, selection: [AllColumns()],
fetch: { statement in
XCTFail("Should not be called")
return "ignored"
@@ -2054,7 +2054,7 @@ extension MutablePersistableRecordTests {
do {
let updatedRow = try player.updateChangesAndFetch(
db, selection: [.allColumns],
db, selection: [AllColumns()],
fetch: { statement in try Row.fetchOne(statement) },
modify: { $0.name = "Craig" })
XCTAssertEqual(updatedRow, ["id": 1, "name": "Craig", "score": 1000])
+2 -350
View File
@@ -1375,7 +1375,7 @@ extension PersistableRecordTests {
}
}
func test_insertAndFetch_selection_fetch_column() throws {
func test_insertAndFetch_selection_fetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -1423,104 +1423,6 @@ extension PersistableRecordTests {
}
}
}
func test_insertAndFetch_selection_fetch_allColumns() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
clearSQLQueries()
let partialPlayer = PartialPlayer(name: "Arthur")
let row = try partialPlayer.insertAndFetch(db, selection: [.allColumns]) { (statement: Statement) in
try Row.fetchOne(statement)!
}
XCTAssert(sqlQueries.contains("""
INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING *
"""), sqlQueries.joined(separator: "\n"))
XCTAssertEqual(row, ["id": 1, "name": "Arthur", "score": 1000])
XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0)
XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0)
}
}
}
func test_insertAndFetch_selection_fetch_allColumns_excluding() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
clearSQLQueries()
let partialPlayer = PartialPlayer(name: "Arthur")
let row = try partialPlayer.insertAndFetch(db, selection: [.allColumns(excluding: ["score"])]) { (statement: Statement) in
try Row.fetchOne(statement)!
}
XCTAssert(sqlQueries.contains("""
INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "id", "name"
"""), sqlQueries.joined(separator: "\n"))
XCTAssertEqual(row, ["id": 1, "name": "Arthur"])
XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0)
XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0)
}
}
}
}
// MARK: - Save and Fetch
@@ -1649,7 +1551,7 @@ extension PersistableRecordTests {
}
}
func test_saveAndFetch_selection_fetch_column() throws {
func test_saveAndFetch_selection_fetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
@@ -1771,256 +1673,6 @@ extension PersistableRecordTests {
}
}
}
func test_saveAndFetch_selection_fetch_allColumns() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
clearSQLQueries()
let partialPlayer = PartialPlayer(name: "Arthur")
let row = try partialPlayer.saveAndFetch(db, selection: [.allColumns]) { (
statement: Statement
) in
try Row.fetchOne(statement)
}
XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") })
XCTAssert(sqlQueries.contains("""
INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING *
"""), sqlQueries.joined(separator: "\n"))
XCTAssertEqual(row, ["id": 1, "name": "Arthur", "score": 1000])
XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0)
XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0)
}
do {
let partialPlayer = PartialPlayer(id: 1, name: "Arthur")
try partialPlayer.delete(db)
clearSQLQueries()
let row = try partialPlayer.saveAndFetch(db, selection: [.allColumns]) { (statement: Statement) in
try Row.fetchOne(statement)
}
XCTAssert(sqlQueries.contains("""
UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING *
"""), sqlQueries.joined(separator: "\n"))
XCTAssert(sqlQueries.contains("""
INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING *
"""), sqlQueries.joined(separator: "\n"))
XCTAssertEqual(row, ["id": 1, "name": "Arthur", "score": 1000])
XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0)
XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1)
}
do {
clearSQLQueries()
let partialPlayer = PartialPlayer(id: 1, name: "Arthur")
let row = try partialPlayer.saveAndFetch(db, selection: [.allColumns]) { (statement: Statement) in
try Row.fetchOne(statement)
}
XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") })
XCTAssert(sqlQueries.contains("""
UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING *
"""), sqlQueries.joined(separator: "\n"))
XCTAssertEqual(row, ["id": 1, "name": "Arthur", "score": 1000])
XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0)
XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0)
}
}
}
func test_saveAndFetch_selection_fetch_allColumns_excluding() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
clearSQLQueries()
let partialPlayer = PartialPlayer(name: "Arthur")
let row = try partialPlayer.saveAndFetch(db, selection: [.allColumns(excluding: ["score"])]) { (
statement: Statement
) in
try Row.fetchOne(statement)
}
XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") })
XCTAssert(sqlQueries.contains("""
INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "id", "name"
"""), sqlQueries.joined(separator: "\n"))
XCTAssertEqual(row, ["id": 1, "name": "Arthur"])
XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0)
XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0)
}
do {
let partialPlayer = PartialPlayer(id: 1, name: "Arthur")
try partialPlayer.delete(db)
clearSQLQueries()
let row = try partialPlayer.saveAndFetch(db, selection: [.allColumns(excluding: ["score"])]) { (statement: Statement) in
try Row.fetchOne(statement)
}
XCTAssert(sqlQueries.contains("""
UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "id", "name"
"""), sqlQueries.joined(separator: "\n"))
XCTAssert(sqlQueries.contains("""
INSERT INTO "player" ("id", "name") VALUES (1,'Arthur') RETURNING "id", "name"
"""), sqlQueries.joined(separator: "\n"))
XCTAssertEqual(row, ["id": 1, "name": "Arthur"])
XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 0)
XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 1)
}
do {
clearSQLQueries()
let partialPlayer = PartialPlayer(id: 1, name: "Arthur")
let row = try partialPlayer.saveAndFetch(db, selection: [.allColumns(excluding: ["score"])]) { (statement: Statement) in
try Row.fetchOne(statement)
}
XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") })
XCTAssert(sqlQueries.contains("""
UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING "id", "name"
"""), sqlQueries.joined(separator: "\n"))
XCTAssertEqual(row, ["id": 1, "name": "Arthur"])
XCTAssertEqual(partialPlayer.callbacks.willInsertCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertEnterCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundInsertExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didInsertCount, 0)
XCTAssertEqual(partialPlayer.callbacks.willUpdateCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundUpdateExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didUpdateCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveEnterCount, 1)
XCTAssertEqual(partialPlayer.callbacks.aroundSaveExitCount, 1)
XCTAssertEqual(partialPlayer.callbacks.didSaveCount, 1)
XCTAssertEqual(partialPlayer.callbacks.willDeleteCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteEnterCount, 0)
XCTAssertEqual(partialPlayer.callbacks.aroundDeleteExitCount, 0)
XCTAssertEqual(partialPlayer.callbacks.didDeleteCount, 0)
}
}
}
}
// MARK: - Upsert
@@ -28,7 +28,7 @@ private class Person : Record, Hashable {
// Record
override static var databaseSelection: [any SQLSelectable] {
[.allColumns, .rowID]
[AllColumns(), Column.rowID]
}
override class var databaseTableName: String {
+5 -43
View File
@@ -309,22 +309,10 @@ extension SQLLiteralTests {
try makeDatabaseQueue().inDatabase { db in
struct Player: TableRecord { }
struct AltPlayer: TableRecord {
static let databaseTableName: String = "player"
static var databaseSelection: [any SQLSelectable] {
[Column("id"), Column("name")]
}
}
struct RestrictedPlayer: TableRecord {
static let databaseTableName: String = "player"
static var databaseSelection: [any SQLSelectable] {
[.allColumns(excluding: ["name"])]
}
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
t.column("score", .integer)
}
do {
let query: SQL = """
SELECT \(columnsOf: Player.self)
@@ -359,7 +347,7 @@ extension SQLLiteralTests {
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "player"."id", "player"."name"
SELECT "altPlayer"."id", "altPlayer"."name"
FROM player
""")
XCTAssert(arguments.isEmpty)
@@ -377,32 +365,6 @@ extension SQLLiteralTests {
""")
XCTAssert(arguments.isEmpty)
}
do {
let query: SQL = """
SELECT \(columnsOf: RestrictedPlayer.self)
FROM player
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "player"."id", "player"."score"
FROM player
""")
XCTAssert(arguments.isEmpty)
}
do {
let query: SQL = """
SELECT \(columnsOf: RestrictedPlayer.self, tableAlias: "p")
FROM player p
"""
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "p"."id", "p"."score"
FROM player p
""")
XCTAssert(arguments.isEmpty)
}
}
}
@@ -678,7 +640,7 @@ extension SQLLiteralTests {
func testPlusOperatorWithInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
var query: SQL = "SELECT \(.allColumns) "
var query: SQL = "SELECT \(AllColumns()) "
query = query + "FROM player "
query = query + "WHERE id = \(1)"
@@ -692,7 +654,7 @@ extension SQLLiteralTests {
func testPlusEqualOperatorWithInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
var query: SQL = "SELECT \(.allColumns) "
var query: SQL = "SELECT \(AllColumns()) "
query += "FROM player "
query += "WHERE id = \(1)"
@@ -706,7 +668,7 @@ extension SQLLiteralTests {
func testAppendLiteralWithInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
var query: SQL = "SELECT \(.allColumns) "
var query: SQL = "SELECT \(AllColumns()) "
query.append(literal: "FROM player ")
query.append(literal: "WHERE id = \(1)")
@@ -720,7 +682,7 @@ extension SQLLiteralTests {
func testAppendRawSQLWithInterpolation() throws {
try makeDatabaseQueue().inDatabase { db in
var query: SQL = "SELECT \(.allColumns) "
var query: SQL = "SELECT \(AllColumns()) "
query.append(sql: "FROM player ")
query.append(sql: "WHERE score > \(1000) ")
query.append(sql: "AND \("name") = :name", arguments: ["name": "Arthur"])
@@ -71,32 +71,6 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase {
XCTAssertEqual(try Reader.select(max(Col.age)).group(Col.name).fetchCount(db), 0)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT MAX(\"age\") FROM \"readers\" GROUP BY \"name\")")
XCTAssertEqual(try Reader.select(.allColumns(excluding: [] as [String])).fetchCount(db), 0)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"")
XCTAssertEqual(try Reader.select(.allColumns(excluding: [] as [String])).distinct().fetchCount(db), 0)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT * FROM \"readers\")")
XCTAssertEqual(try Reader.select(.allColumns(excluding: ["name"])).fetchCount(db), 0)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"")
XCTAssertEqual(try Reader.select(.allColumns(excluding: ["name"])).distinct().fetchCount(db), 0)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT \"id\", \"age\" FROM \"readers\")")
XCTAssertEqual(try Reader.select(.allColumns(excluding: ["id", "name"])).fetchCount(db), 0)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"")
XCTAssertEqual(try Reader.select(.allColumns(excluding: ["id", "name"])).distinct().fetchCount(db), 0)
// This test tests for a missed optimization, because
// SELECT COUNT(DISTINCT age) FROM readers would be correct as well.
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT \"age\" FROM \"readers\")")
XCTAssertEqual(try Reader.select(.allColumns(excluding: ["unknown"])).fetchCount(db), 0)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"")
XCTAssertEqual(try Reader.select(.allColumns(excluding: ["unknown"])).distinct().fetchCount(db), 0)
XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT * FROM \"readers\")")
}
}
+6 -20
View File
@@ -238,24 +238,10 @@ class TableRecordDeleteTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
do {
let request = Person.all()
let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")])
XCTAssertEqual(statement.sql, "DELETE FROM \"persons\" RETURNING \"name\"")
XCTAssertEqual(statement.columnNames, ["name"])
}
do {
let request = Person.all()
let statement = try request.deleteAndFetchStatement(db, selection: [.allColumns])
XCTAssertEqual(statement.sql, "DELETE FROM \"persons\" RETURNING *")
XCTAssertEqual(statement.columnNames, ["id", "name", "email"])
}
do {
let request = Person.all()
let statement = try request.deleteAndFetchStatement(db, selection: [.allColumns(excluding: ["name"])])
XCTAssertEqual(statement.sql, "DELETE FROM \"persons\" RETURNING \"id\", \"email\"")
XCTAssertEqual(statement.columnNames, ["id", "email"])
}
let request = Person.all()
let statement = try request.deleteAndFetchStatement(db, selection: [AllColumns()])
XCTAssertEqual(statement.sql, "DELETE FROM \"persons\" RETURNING *")
XCTAssertEqual(statement.columnNames, ["id", "name", "email"])
}
}
@@ -493,7 +479,7 @@ class TableRecordDeleteTests: GRDBTestCase {
do {
let request = Player.including(required: Player.team)
let statement = try request.deleteAndFetchStatement(db, selection: [.allColumns])
let statement = try request.deleteAndFetchStatement(db, selection: [AllColumns()])
XCTAssertEqual(statement.sql, """
DELETE FROM "player" WHERE "id" IN (\
SELECT "player"."id" \
@@ -525,7 +511,7 @@ class TableRecordDeleteTests: GRDBTestCase {
}
do {
let request = Team.having(Team.players.isEmpty)
let statement = try request.deleteAndFetchStatement(db, selection: [.allColumns])
let statement = try request.deleteAndFetchStatement(db, selection: [AllColumns()])
XCTAssertEqual(statement.sql, """
DELETE FROM "team" WHERE "id" IN (\
SELECT "team"."id" \
+1 -16
View File
@@ -103,7 +103,7 @@ class TableRecordTests: GRDBTestCase {
func testExtendedDatabaseSelection() throws {
struct Record: TableRecord {
static let databaseTableName = "t1"
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -128,21 +128,6 @@ class TableRecordTests: GRDBTestCase {
}
}
func testRestrictedDatabaseSelectionWithAllColumnsExcluding() throws {
struct Record: TableRecord {
static let databaseTableName = "t1"
static var databaseSelection: [any SQLSelectable] {
[.allColumns(excluding: ["C"])]
}
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE TABLE t1(a,b,c)")
_ = try Row.fetchAll(db, Record.all())
XCTAssertEqual(lastSQLQuery, "SELECT \"a\", \"b\" FROM \"t1\"")
}
}
func testRecordInAttachedDatabase() throws {
#if GRDBCIPHER_USE_ENCRYPTION
// Avoid error due to key not being provided:
+5 -21
View File
@@ -129,27 +129,11 @@ class TableRecordUpdateTests: GRDBTestCase {
try Player.createTable(db)
let assignment = Columns.score.set(to: 0)
do {
let request = Player.all()
let statement = try request.updateAndFetchStatement(db, [assignment], selection: [Column("score")])
XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING \"score\"")
XCTAssertEqual(statement.arguments, [0])
XCTAssertEqual(statement.columnNames, ["score"])
}
do {
let request = Player.all()
let statement = try request.updateAndFetchStatement(db, [assignment], selection: [.allColumns])
XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING *")
XCTAssertEqual(statement.arguments, [0])
XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"])
}
do {
let request = Player.all()
let statement = try request.updateAndFetchStatement(db, [assignment], selection: [.allColumns(excluding: ["name"])])
XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING \"id\", \"score\", \"bonus\"")
XCTAssertEqual(statement.arguments, [0])
XCTAssertEqual(statement.columnNames, ["id", "score", "bonus"])
}
let request = Player.all()
let statement = try request.updateAndFetchStatement(db, [assignment], selection: [AllColumns()])
XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING *")
XCTAssertEqual(statement.arguments, [0])
XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"])
}
}
-6
View File
@@ -44,12 +44,6 @@ class TableTests: GRDBTestCase {
try assertEqualSQL(db, t.select([Column("id"), Column("name")]), """
SELECT "id", "name" FROM "player"
""")
try assertEqualSQL(db, t.select(.allColumns), """
SELECT * FROM "player"
""")
try assertEqualSQL(db, t.select(.allColumns(excluding: ["name"])), """
SELECT "id" FROM "player"
""")
try assertEqualSQL(db, t.select(sql: "id, ?", arguments: ["O'Brien"]), """
SELECT id, 'O''Brien' FROM "player"
""")
+1 -1
View File
@@ -371,7 +371,7 @@ class TransactionDateTests: GRDBTestCase {
// The protocol in RecordTimestamps.md
/// 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 }
@@ -29,6 +29,7 @@
5690AFD92120589A001530EA /* InsertRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFD72120589A001530EA /* InsertRecordEncodableTests.swift */; };
5690AFDB212058CB001530EA /* FetchRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */; };
5690AFDC212058CB001530EA /* FetchRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */; };
56A3FEA827A85F4800B0292E /* Realm in Frameworks */ = {isa = PBXBuildFile; productRef = 56A3FEA727A85F4800B0292E /* Realm */; };
56A3FEAA27A85F4800B0292E /* RealmSwift in Frameworks */ = {isa = PBXBuildFile; productRef = 56A3FEA927A85F4800B0292E /* RealmSwift */; };
56A6F4AC29BBC8E200E22662 /* ArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A6F4AB29BBC8E200E22662 /* ArgumentsTests.swift */; };
56B6D0E52618BF78003CC455 /* FetchRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */; };
@@ -133,6 +134,7 @@
561C25942439C942001227F2 /* FMDB in Frameworks */,
5679870523A37A790076902D /* GRDB.framework in Frameworks */,
56439B431F4CA1DC0066043F /* CoreData.framework in Frameworks */,
56A3FEA827A85F4800B0292E /* Realm in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
@@ -253,6 +255,7 @@
packageProductDependencies = (
561C25902439C92D001227F2 /* SQLite */,
561C25932439C942001227F2 /* FMDB */,
56A3FEA727A85F4800B0292E /* Realm */,
56A3FEA927A85F4800B0292E /* RealmSwift */,
);
productName = GRDBOSXTests;
@@ -633,7 +636,7 @@
repositoryURL = "https://github.com/stephencelis/SQLite.swift.git";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 0.15.3;
minimumVersion = 0.12.2;
};
};
561C25922439C942001227F2 /* XCRemoteSwiftPackageReference "fmdb" */ = {
@@ -641,7 +644,7 @@
repositoryURL = "https://github.com/ccgus/fmdb.git";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 2.7.12;
minimumVersion = 2.7.0;
};
};
56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */ = {
@@ -649,7 +652,7 @@
repositoryURL = "https://github.com/realm/realm-swift.git";
requirement = {
kind = upToNextMajorVersion;
minimumVersion = 20.0.1;
minimumVersion = 10.22.0;
};
};
/* End XCRemoteSwiftPackageReference section */
@@ -665,6 +668,11 @@
package = 561C25922439C942001227F2 /* XCRemoteSwiftPackageReference "fmdb" */;
productName = FMDB;
};
56A3FEA727A85F4800B0292E /* Realm */ = {
isa = XCSwiftPackageProductDependency;
package = 56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */;
productName = Realm;
};
56A3FEA927A85F4800B0292E /* RealmSwift */ = {
isa = XCSwiftPackageProductDependency;
package = 56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */;
@@ -6,8 +6,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/ccgus/fmdb.git",
"state" : {
"revision" : "1227a3fa2b9916bfd75fe380eb45cd210e69e251",
"version" : "2.7.12"
"revision" : "47a2fa12a242b5a2fe13b916c22f2212e426055c",
"version" : "2.7.9"
}
},
{
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/realm/realm-core.git",
"state" : {
"revision" : "15493076ad9fef22c16cc64cbfbf9e5b65c385f9",
"version" : "20.1.0"
"revision" : "374dd672af357732dccc135fecc905406fec3223",
"version" : "14.4.1"
}
},
{
@@ -24,8 +24,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/realm/realm-swift.git",
"state" : {
"revision" : "bae6c4be7df169fdb047d0ad63f902c1e2665e83",
"version" : "20.0.1"
"revision" : "e0c2fbb442979fbf1e4be80e01d142f310a9c762",
"version" : "10.49.1"
}
},
{
@@ -33,8 +33,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/stephencelis/SQLite.swift.git",
"state" : {
"revision" : "a95fc6df17d108bd99210db5e8a9bac90fe984b8",
"version" : "0.15.3"
"revision" : "e78ae0220e17525a15ac68c697a155eb7a672a8e",
"version" : "0.15.0"
}
}
],
@@ -9,16 +9,16 @@ import RealmSwift
// MARK:- SQLite
let itemTable = Table("item")
let i0Column = SQLite.Expression<Int>("i0")
let i1Column = SQLite.Expression<Int>("i1")
let i2Column = SQLite.Expression<Int>("i2")
let i3Column = SQLite.Expression<Int>("i3")
let i4Column = SQLite.Expression<Int>("i4")
let i5Column = SQLite.Expression<Int>("i5")
let i6Column = SQLite.Expression<Int>("i6")
let i7Column = SQLite.Expression<Int>("i7")
let i8Column = SQLite.Expression<Int>("i8")
let i9Column = SQLite.Expression<Int>("i9")
let i0Column = Expression<Int>("i0")
let i1Column = Expression<Int>("i1")
let i2Column = Expression<Int>("i2")
let i3Column = Expression<Int>("i3")
let i4Column = Expression<Int>("i4")
let i5Column = Expression<Int>("i5")
let i6Column = Expression<Int>("i6")
let i7Column = Expression<Int>("i7")
let i8Column = Expression<Int>("i8")
let i9Column = Expression<Int>("i9")
// MARK: - Realm
+1 -1
View File
@@ -35,7 +35,7 @@ samples = JSON.parse(STDIN.read)
# have checkouts for all dependencies.
# BUILD_ROOT
exit 1 unless `xcodebuild -showBuildSettings -project Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj -scheme GRDBOSXPerformanceComparisonTests -disableAutomaticPackageResolution` =~ /BUILD_ROOT = (.*)$/
exit 1 unless `xcodebuild -showBuildSettings -project Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj -target GRDBOSXPerformanceComparisonTests -disableAutomaticPackageResolution` =~ /BUILD_ROOT = (.*)$/
BUILD_ROOT = $1
# DERIVED_DATA