Compare commits

..
Author SHA1 Message Date
Gwendal Roué 63590ede60 Association limit WIP 2025-03-01 13:20:23 +01:00
Gwendal Roué 6eba24d169 Merge branch 'development' 2025-02-23 19:53:59 +01:00
Gwendal Roué bd3ac9ef75 v7.3.0 2025-02-23 18:44:22 +01:00
Gwendal Roué 392137c357 XCTestExpectation is Sendable starting Xcode 16.3 beta 2025-02-23 18:43:45 +01:00
Gwendal Roué b48a56ae03 Revert "Merge pull request #1732 from groue/dev/sending-closures"
This reverts commit bbd1eab402, reversing
changes made to 9b09c5342e.
2025-02-23 18:43:45 +01:00
Gwendal Roué bbd1eab402 Merge pull request #1732 from groue/dev/sending-closures
Async database accesses no longer require Sendable closures.
2025-02-23 15:33:54 +01:00
Gwendal Roué 53c9d12d29 Async database access no longer require Sendable closures. 2025-02-23 15:16:36 +01:00
Gwendal Roué 9b09c5342e Merge pull request #1731 from groue/dev/virtual-table-options
Support for temporary virtual tables
2025-02-23 13:59:48 +01:00
Gwendal Roué aed22fe0bc Support for temporary virtual tables. 2025-02-23 13:45:46 +01:00
Gwendal Roué eec220b652 Merge pull request #1730 from groue/dev/issue-1728
Undeprecate Date coding strategies based on DateFormatter
2025-02-23 11:13:02 +01:00
Gwendal Roué 79a782038e Undeprecate Date coding strategies based on DateFormatter
https://github.com/swiftlang/swift/issues/78635#issuecomment-2676324549
> DateFormatter is indeed thread safe and its conformance to Sendable is correct
2025-02-23 11:12:24 +01:00
Gwendal Roué 618e72d153 Merge pull request #1729 from groue/dev/issue-1728
Deprecate Date coding strategies based on DateFormatter
2025-02-22 14:29:08 +01:00
Gwendal Roué 824100990f Deprecate Date coding strategies based on DateFormatter
Fix #1728
2025-02-22 13:45:42 +01:00
Gwendal Roué c7205b172f Merge branch 'development' 2025-02-12 08:49:02 +01:00
Gwendal Roué 49d14e6b66 v7.2.0 2025-02-12 08:48:52 +01:00
Gwendal Roué 54ed7ec611 Merge pull request #1719 from groue/dev/selectID
Select ids with selectID()
2025-02-12 08:46:40 +01:00
Gwendal Roué 68e17351ff CI: iPhone 15 Pro simulator is no longer available 2025-02-12 08:31:34 +01:00
Gwendal Roué 494e697e94 Warn against selectID() when the ID type is an optional. 2025-02-12 08:25:27 +01:00
Gwendal Roué 87b236dfe0 selectID
This reverts 7ffc332327

At the time, selectID was replaced with selectPrimaryKey(as:) because:

> Since Optional is a database value like others, selectID would be a request of optionals for records with an optional ID type:
>
>     struct Player: Identifiable, MutablePersistableRecord {
>         var id: Int64?
>     }
>
>     Player.selectID() // QueryInterface<Int64?>
>
> This is not good, because primary keys are not null. And those requests would fetch impractical types such as [Int64?], Set<Int64?>, Int64??.

This problem is reintroduced, but we now recommend against optional ids in https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices. And record with optional ids can use selectPrimaryKey(as:).
2025-02-11 20:47:49 +01:00
Gwendal Roué ea6d8e0123 Merge branch 'development' 2025-02-05 15:34:18 +01:00
Gwendal Roué 073209f1dc v7.1.0 2025-02-05 15:34:09 +01:00
Gwendal Roué 430530f5f1 CHANGELOG 2025-02-05 14:08:28 +01:00
Gwendal Roué a716915280 Merge pull request #1717 from groue/dev/RxGRDB
Allow RxGRDB to compile without warning
2025-02-05 13:58:25 +01:00
Gwendal Roué ef36727d9a 🎵 Whatever Lola wants, Lola gets
Address https://github.com/RxSwiftCommunity/RxGRDB/issues/72

Based on https://github.com/swiftlang/swift-evolution/blob/main/proposals/0337-support-incremental-migration-to-concurrency-checking.md#preconcurrency-attribute-on-nominal-declarations

See also https://www.massicotte.org/preconcurrency#working-with-swift-5

"Whatever Lola wants, Lola gets" because the Swift language is a blind and cruel mistress.
2025-02-05 13:38:19 +01:00
Gwendal Roué 78b2796f46 CHANGELOG 2025-02-05 08:00:29 +01:00
Gwendal Roué 3535a42c53 Merge pull request #1716 from groue/dev/issue-1715
Fix: DatabaseQueue restores its read/write abilities when an async read-only database access is cancelled.
2025-02-04 20:51:58 +01:00
Gwendal Roué 5a4d9b5cb9 Let PRAGMA QUERY_ONLY statements run from a cancelled database access
Fix #1715
2025-02-04 19:35:39 +01:00
Gwendal Roué a64b09d121 Failing test for #1715 2025-02-04 19:35:39 +01:00
Gwendal Roué 287c4be82d Merge pull request #1713 from groue/dev/sqliteLibVersionNumber
Expose `sqlite3_libversion_number` as `Database.sqliteLibVersionNumber`
2025-02-01 12:59:42 +01:00
Gwendal Roué 32c9ba24ba Replace sqlite3_libversion_number() with Database.sqliteLibVersionNumber
and remove SQLite imports that are no longer necessary.
2025-02-01 12:19:11 +01:00
Gwendal Roué 0401d449bb Database.sqliteLibVersionNumber 2025-02-01 12:01:41 +01:00
Gwendal Roué 4de97e6903 Merge branch 'development' 2025-01-26 16:30:56 +01:00
Gwendal Roué 676636bae4 7.0.0 2025-01-26 16:30:06 +01:00
Gwendal Roué 8e7cbf098f Fix Realm integration 2025-01-26 16:29:51 +01:00
Gwendal Roué 7250d759fe Fix generatePerformanceReport.rb script 2025-01-26 16:29:51 +01:00
Gwendal Roué fe7b9955b1 Upgrade performance tests dependencies 2025-01-26 16:29:51 +01:00
Gwendal Roué 6df8e2bd34 Fix casing of swiftpackageindex.com urls 2025-01-26 15:31:12 +01:00
Gwendal Roué 81cd33b71c CHANGELOG 2025-01-26 15:26:01 +01:00
Gwendal Roué 2e2c0eaec1 Merge pull request #1699 from groue/dev/jsonb
Support for JSONB expressions
2025-01-26 15:22:25 +01:00
Gwendal Roué ed17710694 Add tests of JSON_GROUP_ARRAY output, from both JSON and JSONB input 2025-01-26 14:44:27 +01:00
Gwendal Roué 0f68d8b684 JSON_VALID options 2025-01-26 14:21:35 +01:00
Gwendal Roué 367f8f7e37 Add missing imports for C SQLite functions 2025-01-26 14:21:35 +01:00
Gwendal Roué 831e79ee82 JSONB functions and tests 2025-01-26 14:21:35 +01:00
Gwendal Roué 8b3f9c0936 Prefer JSONB when building JSON 2025-01-26 14:21:35 +01:00
Gwendal Roué 950db13d46 Declare JSONB functions behavior 2025-01-26 14:21:35 +01:00
Gwendal Roué 0e664cf22e Not only pluralization can be a problem 2025-01-23 08:10:36 +01:00
Gwendal Roué 1e5602ca9d Merge pull request #1703 from groue/dev/inflections-fixes
Fix pluralization of Bias, Focus, Gas, and Lens
2025-01-22 21:29:31 +01:00
Gwendal Roué 8147811ab4 Mention Bias, Focus, Gas, and Lens in the GRDB 7 Migration Guide 2025-01-22 21:02:09 +01:00
Gwendal Roué 4c9b0eb90e Fix failing tests for inflections 2025-01-22 20:41:55 +01:00
Gwendal Roué b63d75da21 Failing tests for inflections
- bias/biases
- focus/focuses
- gas/gases
- lens/lenses
2025-01-22 20:41:39 +01:00
Gwendal Roué 5a3db29e21 Remove link to X account 2025-01-21 13:14:03 +01:00
Gwendal Roué fa0985eb01 Documentation: add @retroactive to Tagged extensions 2025-01-21 08:03:46 +01:00
Gwendal Roué 495e76bb1a Fix performance tests for SQLite.swift 2025-01-20 08:51:01 +01:00
Gwendal Roué bbf39353b5 Merge branch 'development' 2025-01-19 18:20:47 +01:00
Gwendal Roué 442b8b0589 7.0.0-beta.7 2025-01-19 17:30:17 +01:00
Gwendal Roué 2c85bc2cfc CHANGELOG 2025-01-19 16:57:34 +01:00
Gwendal Roué 3f56bc8199 Merge pull request #1700 from groue/dev/all-columns-excluding
Select all columns from a table, but a few ones
2025-01-19 16:50:48 +01:00
Gwendal Roué 37ea21eb96 Test AllColumnsExcluding and Table 2025-01-19 16:26:59 +01:00
Gwendal Roué 96c9eb5699 Enhance documentation of generated columns 2025-01-19 16:26:59 +01:00
Gwendal Roué 33103bb373 AllColumnsExcluding tests 2025-01-19 16:26:59 +01:00
Gwendal Roué 6b23181337 Use .allColumns and .rowID instead of AllColumns() and Column.rowID 2025-01-19 16:26:59 +01:00
Gwendal Roué c5366f4a01 AllColumnsExcluding documentation 2025-01-19 16:26:59 +01:00
Gwendal Roué a642ac51aa AllColumnsExcluding 2025-01-19 16:26:59 +01:00
Gwendal Roué d03208b33a Remove unused code 2025-01-19 16:26:59 +01:00
Gwendal Roué a4132a00db Clarify code that aims at fixing #1357 2025-01-19 16:26:59 +01:00
Gwendal Roué 61c7fdf81b Github CI: use tvOS 18.1 2025-01-19 16:26:29 +01:00
108 changed files with 4615 additions and 696 deletions

No files matched your search

+2 -2
View File
@@ -46,11 +46,11 @@ jobs:
name: "macOS"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "OS=18.1,name=iPhone 15 Pro"
destination: "OS=18.1,name=iPhone 16 Pro"
name: "iOS"
- xcode: "Xcode_16.1.app"
runsOn: macOS-14
destination: "OS=18.0,name=Apple TV"
destination: "OS=18.1,name=Apple TV"
name: "tvOS"
steps:
- uses: actions/checkout@v4
+73 -29
View File
@@ -7,7 +7,11 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.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.3.x` Releases - [7.3.0](#730)
- `7.2.x` Releases - [7.2.0](#720)
- `7.1.x` Releases - [7.1.0](#710)
- `7.0.x` Releases - [7.0.0](#700)
- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6) - [7.0.0-beta.7](#700-beta7)
#### 6.x Releases
@@ -131,6 +135,46 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 7.3.0
Released February 23, 2025
- **New**: Support for temporary virtual tables by [@groue](https://github.com/groue) in [#1731](https://github.com/groue/GRDB.swift/pull/1731)
- Fixed a compiler error in Xcode 16.3 beta ([#1729](https://github.com/groue/GRDB.swift/pull/1729), [#1730](https://github.com/groue/GRDB.swift/pull/1730))
## 7.2.0
Released February 12, 2025
- **New**: Select ids with selectID() by [@groue](https://github.com/groue) in [#1719](https://github.com/groue/GRDB.swift/pull/1719)
## 7.1.0
Released February 5, 2025
- **New**: Expose `sqlite3_libversion_number` as `Database.sqliteLibVersionNumber` by [@groue](https://github.com/groue) in [#1713](https://github.com/groue/GRDB.swift/pull/1713)
- **Fixed**: DatabaseQueue restores its read/write abilities when an async read-only database access is cancelled by [@groue](https://github.com/groue) in [#1716](https://github.com/groue/GRDB.swift/pull/1716)
- **New**: Allow RxGRDB to compile without warning by [@groue](https://github.com/groue) in [#1717](https://github.com/groue/GRDB.swift/pull/1717)
## 7.0.0
Released January 26, 2025
- **New**: Support for JSONB expressions by [@groue](https://github.com/groue) in [#1699](https://github.com/groue/GRDB.swift/pull/1699)
- **Breaking Change**: Fix inflections of Bias, Focus, Gas, and Lens by [@groue](https://github.com/groue) in [#1703](https://github.com/groue/GRDB.swift/pull/1703)
## 7.0.0-beta.7
Released January 19, 2025
- **New**: Select all columns from a table, but a few ones by [@groue](https://github.com/groue) in [#1700](https://github.com/groue/GRDB.swift/pull/1700)
- **Fixed**: Fix typo in Readme.md by [@kevinlg](https://github.com/kevinlg) in [#1697](https://github.com/groue/GRDB.swift/pull/1697)
- **New**: Bump custom SQLite to 3.47.2 by [@groue](https://github.com/groue) in [#1696](https://github.com/groue/GRDB.swift/pull/1696)
- **Fixed**: Update LICENSE, fix copyright license year by [@JasonnnW3000](https://github.com/JasonnnW3000) in [#1695](https://github.com/groue/GRDB.swift/pull/1695)
- **Fixed**: Core: import `ucrt` on Windows for `strcmp` by [@compnerd](https://github.com/compnerd) in [#1662](https://github.com/groue/GRDB.swift/pull/1662)
- **Fixed**: Foundation: elide extensions on Windows to match Linux by [@compnerd](https://github.com/compnerd) in [#1661](https://github.com/groue/GRDB.swift/pull/1661)
- **Fixed**: Docs: fixes typos "FST"->"FTS" by [@nylki](https://github.com/nylki) in [#1660](https://github.com/groue/GRDB.swift/pull/1660)
## 7.0.0-beta.6
Released October 13, 2024
@@ -172,7 +216,7 @@ Released September 29, 2024
[Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) describes in detail how to bump the GRDB version in your application.
The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
The [demo app](Documentation/DemoApps/) was rewritten from scratch in a brand new Xcode 16 project.
@@ -231,8 +275,8 @@ Released July 11, 2024
Released April 21, 2024
- **Fixed**: [#1533](https://github.com/groue/GRDB.swift/pull/1533) by [@groue](https://github.com/groue): Fix a bug in Decodable support
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide was updated with guidance about default configuration values.
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
- **Documentation Update**: [#1534](https://github.com/groue/GRDB.swift/pull/1534) The [Single-Row Tables](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/singlerowtables) guide was updated with guidance about default configuration values.
- **Documentation Update**: [#1535](https://github.com/groue/GRDB.swift/pull/1535) The [ValueObservation Scheduling](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation#ValueObservation-Scheduling) documentation chapter explains the default behavior of `ValueObservation` fetches, and explains how to make sure they are never performed on the main thread.
## 6.26.0
@@ -257,7 +301,7 @@ Released February 25, 2024
Released January 21, 2024
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
- **Documentation Update**: [#1485](https://github.com/groue/GRDB.swift/pull/1485) The [Sharing a Database](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing) guide was updated with a new recommendation for databases shared between multiple processes. Writers should always perform IMMEDIATE transactions in order to avoid the `SQLITE_BUSY` error that can occur when transactions overlap. The new recommendation fits in a single line of code: `configuration.defaultTransactionKind = .immediate`.
- **New**: Associations that involve views instead of tables were already supported, with an explicit `ForeignKey` in their definition. When the foreign key is missing, a clear diagnostic message is now emitted, instead of an unhelpful "no such table" runtime error.
## 6.24.1
@@ -284,7 +328,7 @@ Released November 26, 2023
- **New**: [#1452](https://github.com/groue/GRDB.swift/pull/1452) by [@groue](https://github.com/groue): SQLite 3.44.0, FILTER and ORDER BY clauses in aggregate functions
- **New**: [#1460](https://github.com/groue/GRDB.swift/pull/1460) by [@groue](https://github.com/groue): Explicit change notifications help applications deal with undetected database changes.
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
- **Documentation Update**: The documentations of [`ValueObservation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation), [`DatabaseRegionObservation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation), and [`TransactionObserver`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver) have a new "Dealing with Undetected Changes" that documents possible strategies for notifying applications of undetected database changes.
## 6.21.0
@@ -320,8 +364,8 @@ Released October 4, 2023 &bull; [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
@@ -345,14 +389,14 @@ Released July 9, 2023 &bull; [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
@@ -369,7 +413,7 @@ Released June 2, 2023 &bull; [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
@@ -404,7 +448,7 @@ Released April 17, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compar
Released April 10, 2023 &bull; [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
@@ -431,8 +475,8 @@ Released March 14, 2023 &bull; [diff](https://github.com/groue/GRDB.swift/compar
Released March 12, 2023 &bull; [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
@@ -441,9 +485,9 @@ Released March 12, 2023 &bull; [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
@@ -451,7 +495,7 @@ Released February 24, 2023 &bull; [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
@@ -462,7 +506,7 @@ Released February 19, 2023 &bull; [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
@@ -492,11 +536,11 @@ Released November 28, 2022 &bull; [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.
+5 -5
View File
@@ -91,7 +91,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
**FTS3 and FTS4 full-text tables store and index textual content.**
Create tables with the `create(virtualTable:using:)` method:
Create tables with the `create(virtualTable:options:using:_:)` method:
```swift
// CREATE VIRTUAL TABLE document USING fts3(content)
@@ -301,7 +301,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
```swift
let documents = try Document.fetchAll(db,
@@ -326,7 +326,7 @@ let documents = try Document.filter(Column("content").match(pattern)).fetchAll(d
To use FTS5, you'll need a [custom SQLite build] that activates the `SQLITE_ENABLE_FTS5` compilation option.
Create FTS5 tables with the `create(virtualTable:using:)` method:
Create FTS5 tables with the `create(virtualTable:options:using:_:)` method:
```swift
// CREATE VIRTUAL TABLE document USING fts5(content)
@@ -550,7 +550,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
```swift
let documents = try Document.fetchAll(db,
@@ -689,7 +689,7 @@ let books = Book.fetchAll(db, sql: sql, arguments: [pattern])
**You can define [record](../README.md#records) types around the full-text virtual tables.**
The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) for more information.
The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) for more information.
## Unicode Full-Text Gotchas
+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:
+55 -7
View File
@@ -10,6 +10,7 @@ Migrating From GRDB 6 to GRDB 7
- [Column Coding Strategies](#column-coding-strategies)
- [Cancellable Async Database Accesses](#cancellable-async-database-accesses)
- [Default Transaction Kind](#default-transaction-kind)
- [Associations to record types named Bias, Focus, Gas, and Lens](#associations-to-record-types-named-bias-focus-gas-and-lens)
- [ValueObservation and the Main Actor](#valueobservation-and-the-main-actor)
- [Access to SQLite C functions](#access-to-sqlite-c-functions)
- [The Record Base Class is Discouraged](#the-record-base-class-is-discouraged)
@@ -96,6 +97,53 @@ try await task.value
Other asynchronous database accesses, such as methods accepting a completion blocks (`asyncRead`, etc.), Combine publishers, RxSwift observables, do not handle cancellation and will proceed to completion by default.
## Associations to record types named Bias, Focus, Gas, and Lens
GRDB 7 has fixed its singularization and pluralization rules for database tables named "bias", "focus", "gas", and "lens".
If your application defines associations to those tables, you can now rely on proper inflections (pluralization and singularization).
With GRDB 7, you can remove custom association keys:
```swift
struct Camera: TableRecord {
// GRDB 6: fix incorrect GRDB inflection
static let lenses = hasMany(Lens.self).forKey("lenses")
// GRDB 7
static let lenses = hasMany(Lens.self)
}
```
If your application was not specifying custom association keys in order to fix the wrong inflections, then it may define types that will no longer decode their properties as intended:
```swift
// Works in GRDB 6, breaks in GRDB 7
struct CameraWithLenses: Decodable, FetchableRecord {
var camera: Camera
var lens: [Lens] // <- incorrect pluralization
}
let results = Camera
.including(all: Camera.lenses)
.asRequest(of: CameraWithLenses.self)
.fetchAll(db)
```
There are two possible solutions. One is to rename properties, the other is to keep on using the wrong inflection (it's your call):
```swift
// GRDB 7, alternative 1
struct CameraWithLenses: Decodable, FetchableRecord {
var camera: Camera
var lenses: [Lens] // <- fixed pluralization
}
// GRDB 7, alternative 2
struct Camera: TableRecord {
// Use "lens" instead of "lenses" for GRDB 6 compatibility.
static let lenses = hasMany(Lens.self).forKey("lens")
}
```
## Default Transaction Kind
Some applications specify a default transaction kind, which was previously recommended in the [Sharing a Database] guide:
@@ -114,7 +162,7 @@ You can still specify a transaction kind explicitly when necessary. See [Transac
In GRDB 7, `ValueObservation` fosters the main actor, because it is frequently used to automatically update database values on screen.
By default, its [`start`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be started on the main actor, and its notification callbacks run on the main actor as well.
By default, its [`start`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be started on the main actor, and its notification callbacks run on the main actor as well.
It is not necessary to call `MainActor.assumeIsolated` in `ValueObservation` callbacks:
@@ -221,14 +269,14 @@ Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non
## Other Changes
- `DatabasePool.concurrentRead` has been removed. Use [`asyncConcurrentRead`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool/asyncconcurrentread(_:)) instead.
- `DatabasePool.concurrentRead` has been removed. Use [`asyncConcurrentRead`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool/asyncconcurrentread(_:)) instead.
- The `PersistenceContainer` subscript no longer guarantees that the value returned is the same as what was previously set. It only guarantees that both values are encoded identically in the database.
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/grdb.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/GRDB.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide
[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/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
[Sharing a Database]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing
[Transaction Kinds]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactions#Transaction-Kinds
[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/swiftconcurrency
[Record]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/record
@@ -1,4 +1,4 @@
Good Practices for Designing Record Types
=========================================
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
This guide [has moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
+1 -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-beta.6'
s.version = '7.3.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+25
View File
@@ -121,6 +121,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
/// - ``clearSchemaCache()``
/// - ``logError``
/// - ``releaseMemory()``
/// - ``sqliteLibVersionNumber``
/// - ``trace(options:_:)``
///
/// ### Supporting Types
@@ -302,6 +303,21 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
}
}
/// An integer equal to [`SQLITE_VERSION_NUMBER`](https://www.sqlite.org/c3ref/c_source_id.html).
///
/// This property returns the result of `sqlite3_libversion_number()`.
///
/// ```swift
/// // Prints, for example, "3048000"
/// print(Database.sqliteLibVersionNumber)
/// ```
@inline(__always)
@inlinable
public static var sqliteLibVersionNumber: CInt {
sqlite3_libversion_number()
}
/// Whether the database region selected by statement execution is
/// recorded into `selectedRegion` by `track(_:)`.
///
@@ -1272,6 +1288,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
return
}
// Suspension should not prevent adjusting the read-only mode.
// See <https://github.com/groue/GRDB.swift/issues/1715>.
if statement.isQueryOnlyPragma {
return
}
// How should we interrupt the statement?
enum Interrupt {
case abort // Rollback and throw SQLITE_ABORT
@@ -2058,6 +2080,9 @@ extension Database {
/// That's the reason why it is recommended to store JSON as text.
public static let jsonText = ColumnType(rawValue: "TEXT")
/// The `BLOB` column type, suitable for JSONB columns.
public static let jsonb = ColumnType(rawValue: "BLOB")
/// The `INTEGER` column type.
public static let integer = ColumnType(rawValue: "INTEGER")
@@ -83,6 +83,7 @@ extension DatabaseRegionObservation {
/// - parameter onChange: The closure to execute when a transaction has
/// modified the observed region.
/// - returns: A DatabaseCancellable that can stop the observation.
@preconcurrency // For RxGRDB, see <https://github.com/RxSwiftCommunity/RxGRDB/issues/72#issuecomment-2631125658>
public func start(
in writer: any DatabaseWriter,
onError: @escaping @Sendable (Error) -> Void,
+5
View File
@@ -172,6 +172,11 @@ public struct SQL: Sendable {
self.init(elements: [.expression(expression.sqlExpression)])
}
/// Creates an `SQL` literal from an SQL ordering term.
public init(_ ordering: some SQLOrderingTerm) {
self.init(elements: [.ordering(ordering.sqlOrdering)])
}
/// Returns true if this literal generates an empty SQL string
public var isEmpty: Bool {
elements.allSatisfy(\.isEmpty)
+4
View File
@@ -92,6 +92,9 @@ public final class Statement {
/// The effects on the database (reported by `sqlite3_set_authorizer`).
private(set) var authorizerEventKinds: [DatabaseEventKind] = []
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
private(set) var isQueryOnlyPragma = false
/// A boolean value indicating if the prepared statement makes no direct
/// changes to the content of the database file.
///
@@ -160,6 +163,7 @@ public final class Statement {
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
self.transactionEffect = authorizer.transactionEffect
self.authorizerEventKinds = authorizer.databaseEventKinds
self.isQueryOnlyPragma = authorizer.isQueryOnlyPragma
}
deinit {
+9
View File
@@ -41,6 +41,9 @@ final class StatementAuthorizer {
/// savepoint statement.
var transactionEffect: Statement.TransactionEffect?
/// If true, the statement executes is a `PRAGMA QUERY_ONLY` statement.
var isQueryOnlyPragma = false
private var isDropStatement = false
init(_ database: Database) {
@@ -67,6 +70,7 @@ final class StatementAuthorizer {
databaseEventKinds = []
invalidatesDatabaseSchemaCache = false
transactionEffect = nil
isQueryOnlyPragma = false
isDropStatement = false
}
@@ -192,6 +196,11 @@ final class StatementAuthorizer {
}
return SQLITE_OK
case SQLITE_PRAGMA:
if let cString1 {
isQueryOnlyPragma = sqlite3_stricmp(cString1, "query_only") == 0
}
return SQLITE_OK
default:
return SQLITE_OK
}
+4 -10
View File
@@ -4,17 +4,11 @@ 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.
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.
It is extended with three articles that focus on particular aspects of concurrency:
**In all cases, and first and foremost, follow the <doc:Concurrency#Concurrency-Rules> right from the start.**
- <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.
The other chapters cover, with more details, the fundamentals of SQLite concurrency, and how GRDB makes it manageable from your Swift code.
## Concurrency Rules
@@ -328,7 +322,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
@@ -252,8 +252,8 @@ Unique constraints and unique indexes are somewhat different: don't miss the tip
- ``Database/alter(table:body:)``
- ``Database/create(table:options:body:)``
- ``Database/create(virtualTable:ifNotExists:using:)``
- ``Database/create(virtualTable:ifNotExists:using:_:)``
- ``Database/create(virtualTable:options:using:)``
- ``Database/create(virtualTable:options:using:_:)``
- ``Database/drop(table:)``
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
@@ -265,6 +265,7 @@ Unique constraints and unique indexes are somewhat different: don't miss the tip
- ``TableDefinition``
- ``TableOptions``
- ``VirtualTableModule``
- ``VirtualTableOptions``
### Database Views
@@ -288,3 +289,5 @@ Those are legacy interfaces that are preserved for backwards compatibility. Thei
- ``Database/create(index:on:columns:unique:ifNotExists:condition:)``
- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)``
- ``Database/create(virtualTable:ifNotExists:using:)``
- ``Database/create(virtualTable:ifNotExists:using:_:)``
@@ -151,7 +151,7 @@ extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
static var databaseSelection: [any SQLSelectable] {
[AllColumns(), Column.rowID]
[.allColumns, .rowID]
}
// Update id upon successful insertion
@@ -107,10 +107,10 @@ import GRDB
import Tagged
// Add database support to Tagged values
extension Tagged: SQLExpressible where RawValue: SQLExpressible { }
extension Tagged: StatementBinding where RawValue: StatementBinding { }
extension Tagged: StatementColumnConvertible where RawValue: StatementColumnConvertible { }
extension Tagged: DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
extension Tagged: @retroactive SQLExpressible where RawValue: SQLExpressible { }
extension Tagged: @retroactive StatementBinding where RawValue: StatementBinding { }
extension Tagged: @retroactive StatementColumnConvertible where RawValue: StatementColumnConvertible { }
extension Tagged: @retroactive DatabaseValueConvertible where RawValue: DatabaseValueConvertible { }
```
This makes it possible to use `Tagged` values in all the expected places:
-30
View File
@@ -1,30 +0,0 @@
# 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@-->
@@ -393,16 +393,16 @@ Extensions to the `DerivableRequest` protocol can not change the type of request
```swift
extension QueryInterfaceRequest<Author> {
// Selects author ids
func selectId() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey(as: Int64.self)
// Selects authors' name
func selectName() -> QueryInterfaceRequest<String> {
select(Author.Columns.name)
}
}
// The ids of Japanese authors
let ids: Set<Int64> = try Author.all()
// The names of Japanese authors
let names: Set<String> = try Author.all()
.filter(countryCode: "JP")
.selectId()
.selectName()
.fetchSet(db)
```
+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,8 +4,6 @@ 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.
+1 -1
View File
@@ -326,7 +326,7 @@ extension Database {
private func isShadowTable(_ tableName: String) throws -> Bool {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Maybe SQLCipher is too old: check actual version
if sqlite3_libversion_number() >= 3037000 {
if Database.sqliteLibVersionNumber >= 3037000 {
guard let table = try table(tableName) else {
// Not a table
return false
+3 -3
View File
@@ -1,7 +1,7 @@
/// The virtual table module for the FTS3 full-text engine.
///
/// To create FTS3 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
/// ``Database/create(virtualTable:options:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts3(content)
@@ -63,7 +63,7 @@ public struct FTS3 {
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
/// Returns an array of tokens found in the string argument.
@@ -143,7 +143,7 @@ extension FTS3: VirtualTableModule {
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
/// ``Database/create(virtualTable:options:using:_:)`` method:
///
/// ```swift
/// try db.create(virtualTable: "document", using: FTS3()) { t in // t is FTS3TableDefinition
+2 -2
View File
@@ -106,13 +106,13 @@ public struct FTS3TokenizerDescriptor: Sendable {
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
arguments.append("separators=" + separators.sorted().map { String($0) }.joined())
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
arguments.append("tokenchars=" + tokenCharacters.sorted().map { String($0) }.joined())
}
return FTS3TokenizerDescriptor("unicode61", arguments: arguments)
+13 -3
View File
@@ -1,7 +1,7 @@
/// The virtual table module for the FTS4 full-text engine.
///
/// To create FTS4 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
/// ``Database/create(virtualTable:options:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts4(content)
@@ -31,7 +31,7 @@ public struct FTS4 {
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
}
@@ -102,6 +102,16 @@ extension FTS4: VirtualTableModule {
case .synchronized(let contentTable):
// https://www.sqlite.org/fts3.html#_external_content_fts4_tables_
if definition.configuration.temporary {
// SQLite can't rebuild the index of temporary tables:
//
// sqlite> CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
// sqlite> CREATE VIRTUAL TABLE temp.ft USING fts4(content="t", b, c);
// sqlite> INSERT INTO ft(ft) VALUES('rebuild');
// Runtime error: SQL logic error
fatalError("Temporary external content FTS4 tables are not supported.")
}
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
@@ -149,7 +159,7 @@ extension FTS4: VirtualTableModule {
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
/// ``Database/create(virtualTable:options:using:_:)`` method:
///
/// ```swift
/// try db.create(virtualTable: "document", using: FTS4()) { t in // t is FTS4TableDefinition
+15 -5
View File
@@ -13,7 +13,7 @@ import Foundation
/// The virtual table module for the FTS5 full-text engine.
///
/// To create FTS5 tables, use the ``Database`` method
/// ``Database/create(virtualTable:ifNotExists:using:_:)``:
/// ``Database/create(virtualTable:options:using:_:)``:
///
/// ```swift
/// // CREATE VIRTUAL TABLE document USING fts5(content)
@@ -85,7 +85,7 @@ public struct FTS5 {
/// }
/// ```
///
/// See ``Database/create(virtualTable:ifNotExists:using:_:)``
/// See ``Database/create(virtualTable:options:using:_:)``
public init() { }
// Support for FTS5Pattern initializers. Don't make public. Users tokenize
@@ -143,7 +143,7 @@ extension FTS5: VirtualTableModule {
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
/// See Database.create(virtualTable:options:using:_:)
public func makeTableDefinition(configuration: VirtualTableConfiguration) -> FTS5TableDefinition {
FTS5TableDefinition(configuration: configuration)
}
@@ -219,7 +219,7 @@ extension FTS5: VirtualTableModule {
/// Reserved; part of the VirtualTableModule protocol.
///
/// See Database.create(virtualTable:using:)
/// See Database.create(virtualTable:options:using:_:)
public func database(_ db: Database, didCreate tableName: String, using definition: FTS5TableDefinition) throws {
switch definition.contentMode {
case .raw:
@@ -227,6 +227,16 @@ extension FTS5: VirtualTableModule {
case .synchronized(let contentTable):
// https://sqlite.org/fts5.html#external_content_tables
if definition.configuration.temporary {
// SQLite can't rebuild the index of temporary tables:
//
// sqlite> CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
// sqlite> CREATE VIRTUAL TABLE temp.ft USING fts5(content="t",content_rowid="a",b,c);
// sqlite> INSERT INTO ft(ft) VALUES('rebuild');
// Runtime error: SQL logic error
fatalError("Temporary external content FTS5 tables are not supported.")
}
let rowIDColumn = try db.primaryKey(contentTable).rowIDColumn ?? Column.rowID.name
let ftsTable = tableName.quotedDatabaseIdentifier
let content = contentTable.quotedDatabaseIdentifier
@@ -274,7 +284,7 @@ extension FTS5: VirtualTableModule {
/// virtual table.
///
/// You don't create instances of this class. Instead, you use the `Database`
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` method:
/// ``Database/create(virtualTable:options:using:_:)`` method:
///
/// ```swift
/// try db.create(virtualTable: "document", using: FTS5()) { t in // t is FTS5TableDefinition
+4 -4
View File
@@ -112,14 +112,14 @@ public struct FTS5TokenizerDescriptor: Sendable {
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
components.append("separators")
components.append(separators.sorted().map { String($0) }.joined())
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
components.append("tokenchars")
components.append(tokenCharacters.sorted().map { String($0) }.joined())
}
@@ -197,14 +197,14 @@ public struct FTS5TokenizerDescriptor: Sendable {
if !separators.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as separators, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
components.append("separators")
components.append(separators.sorted().map { String($0) }.joined())
}
if !tokenCharacters.isEmpty {
// TODO: test "=" and "\"", "(" and ")" as tokenCharacters, with
// both FTS3Pattern(matchingAnyTokenIn:tokenizer:)
// and Database.create(virtualTable:using:)
// and Database.create(virtualTable:options:using:_:)
components.append("tokenchars")
components.append(tokenCharacters.sorted().map { String($0) }.joined())
}
+337 -2
View File
@@ -1,4 +1,6 @@
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// MARK: - JSON
extension Database {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
@@ -339,8 +341,19 @@ extension Database {
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jvalid>
public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression {
.function("JSON_VALID", [value.sqlExpression])
///
/// - parameter value: The tested value.
/// - parameter options: See eventual second argument of the
/// `JSON_VALID` function. See <https://www.sqlite.org/json1.html#the_json_valid_function>.
public static func jsonIsValid(
_ value: some SQLExpressible,
options: JSONValidationOptions? = nil
) -> SQLExpression {
if let options {
.function("JSON_VALID", [value.sqlExpression, options.rawValue.sqlExpression])
} else {
.function("JSON_VALID", [value.sqlExpression])
}
}
/// The `JSON_QUOTE` SQL function.
@@ -419,7 +432,329 @@ extension Database {
isJSONValue: true)
}
}
// MARK: - JSONB
extension Database {
public struct JSONValidationOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
public static let json = JSONValidationOptions(rawValue: 1)
public static let json5 = JSONValidationOptions(rawValue: 2)
public static let probablyJSONB = JSONValidationOptions(rawValue: 4)
public static let jsonb = JSONValidationOptions(rawValue: 8)
}
/// Validates and returns a binary JSONB representation of the provided
/// JSON, with the `JSONB` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB(' { "a": [ "test" ] } ') → '{"a":["test"]}'
/// Database.jsonb(#" { "a": [ "test" ] } "#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jmini>
public static func jsonb(_ value: some SQLExpressible) -> SQLExpression {
.function("JSONB", [value.sqlExpression])
}
/// Creates a binary JSONB array with the `JSONB_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_ARRAY(1, 2, 3, 4) → '[1,2,3,4]'
/// Database.jsonbArray(1...4)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
public static func jsonbArray(
_ values: some Collection<some SQLExpressible>
) -> SQLExpression {
.function("JSONB_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
}
/// Creates a binary JSONB array with the `JSONB_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_ARRAY(1, 2, '3', 4) → '[1,2,"3",4]'
/// Database.jsonbArray([1, 2, "3", 4])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jarray>
public static func jsonbArray(
_ values: some Collection<any SQLExpressible>
) -> SQLExpression {
.function("JSONB_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression))
}
/// The `JSONB_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_EXTRACT('{"a":123}', '$.a') → 123
/// Database.jsonbExtract(#"{"a":123}"#, atPath: "$.a")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - Parameters:
/// - value: A JSON value.
/// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSONB_EXTRACT", [value.sqlExpression, path.sqlExpression])
}
/// The `JSONB_EXTRACT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_EXTRACT('{"a":2,"c":[4,5]}','$.c','$.a') → '[[4,5],2]'
/// Database.jsonbExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jex>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbExtract(
_ value: some SQLExpressible,
atPaths paths: some Collection<some SQLExpressible>
) -> SQLExpression {
.function("JSONB_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression))
}
/// The `JSONB_INSERT` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_INSERT('[1,2,3,4]','$[#]',99) → '[1,2,3,4,99]'
/// Database.jsonbInsert("[1,2,3,4]", ["$[#]": value: 99])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jinsb>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbInsert(
_ value: some SQLExpressible,
_ assignments: some Collection<(key: String, value: any SQLExpressible)>
) -> SQLExpression {
.function("JSONB_INSERT", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSONB_REPLACE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_REPLACE('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
/// Database.jsonbReplace(#"{"a":2,"c":4}"#, ["$.a": 99])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jinsb>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbReplace(
_ value: some SQLExpressible,
_ assignments: some Collection<(key: String, value: any SQLExpressible)>
) -> SQLExpression {
.function("JSONB_REPLACE", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSONB_SET` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_SET('{"a":2,"c":4}', '$.a', 99) → '{"a":99,"c":4}'
/// Database.jsonbSet(#"{"a":2,"c":4}"#, ["$.a": 99]])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jinsb>
///
/// - Parameters:
/// - value: A JSON value.
/// - assignments: A collection of key/value pairs, where keys are
/// [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbSet(
_ value: some SQLExpressible,
_ assignments: some Collection<(key: String, value: any SQLExpressible)>
) -> SQLExpression {
.function("JSONB_SET", [value.sqlExpression] + assignments.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// Creates a binary JSONB object with the `JSONB_OBJECT` SQL function.
/// Pass key/value pairs with a Swift collection such as a `Dictionary`.
///
/// For example:
///
/// ```swift
/// // JSONB_OBJECT('c', '{"e":5}') → '{"c":"{\"e\":5}"}'
/// Database.jsonbObject([
/// "c": #"{"e":5}"#,
/// ])
///
/// // JSONB_OBJECT('c', JSONB_OBJECT('e', 5)) → '{"c":{"e":5}}'
/// Database.jsonbObject([
/// "c": Database.jsonbObject(["e": 5])),
/// ])
///
/// // JSONB_OBJECT('c', JSONB('{"e":5}')) → '{"c":{"e":5}}'
/// Database.jsonbObject([
/// "c": Database.jsonb(#"{"e":5}"#),
/// ])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jobj>
public static func jsonbObject(
_ elements: some Collection<(key: String, value: any SQLExpressible)>
) -> SQLExpression {
.function("JSONB_OBJECT", elements.flatMap {
[$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression]
})
}
/// The `JSONB_PATCH` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_PATCH('{"a":1,"b":2}','{"c":3,"d":4}') → '{"a":1,"b":2,"c":3,"d":4}'
/// Database.jsonbPatch(#"{"a":1,"b":2}"#, #"{"c":3,"d":4}"#)
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jpatch>
public static func jsonbPatch(
_ value: some SQLExpressible,
with patch: some SQLExpressible)
-> SQLExpression
{
.function("JSONB_PATCH", [value.sqlExpression, patch.sqlExpression])
}
/// The `JSONB_REMOVE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_REMOVE('[0,1,2,3,4]', '$[2]') → '[0,1,3,4]'
/// Database.jsonbRemove("[0,1,2,3,4]", atPath: "$[2]")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression {
.function("JSONB_REMOVE", [value.sqlExpression, path.sqlExpression])
}
/// The `JSONB_REMOVE` SQL function.
///
/// For example:
///
/// ```swift
/// // JSONB_REMOVE('[0,1,2,3,4]', '$[2]','$[0]') → '[1,3,4]'
/// Database.jsonbRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"])
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jrm>
///
/// - Parameters:
/// - value: A JSON value.
/// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments).
public static func jsonbRemove(
_ value: some SQLExpressible,
atPaths paths: some Collection<some SQLExpressible>
) -> SQLExpression {
.function("JSONB_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression))
}
/// The `JSONB_GROUP_ARRAY` SQL function.
///
/// For example:
///
/// ```swift
/// // SELECT JSONB_GROUP_ARRAY(name) FROM player
/// Player.select(Database.jsonbGroupArray(Column("name")))
///
/// // SELECT JSONB_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
/// Player.select(Database.jsonbGroupArray(Column("name"), filter: Column("score") > 0))
///
/// // SELECT JSONB_GROUP_ARRAY(name ORDER BY name) FROM player
/// Player.select(Database.jsonbGroupArray(Column("name"), orderBy: Column("name")))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
public static func jsonbGroupArray(
_ value: some SQLExpressible,
orderBy ordering: (any SQLOrderingTerm)? = nil,
filter: (any SQLSpecificExpressible)? = nil)
-> SQLExpression {
.aggregateFunction(
"JSONB_GROUP_ARRAY",
[value.sqlExpression.jsonBuilderExpression],
ordering: ordering?.sqlOrdering,
filter: filter?.sqlExpression,
isJSONValue: true)
}
/// The `JSONB_GROUP_OBJECT` SQL function.
///
/// For example:
///
/// ```swift
/// // SELECT JSONB_GROUP_OBJECT(name, score) FROM player
/// Player.select(Database.jsonbGroupObject(
/// key: Column("name"),
/// value: Column("score")))
///
/// // SELECT JSONB_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
/// Player.select(Database.jsonbGroupObject(
/// key: Column("name"),
/// value: Column("score"),
/// filter: Column("score") > 0))
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
public static func jsonbGroupObject(
key: some SQLExpressible,
value: some SQLExpressible,
filter: (any SQLSpecificExpressible)? = nil
) -> SQLExpression {
.aggregateFunction(
"JSONB_GROUP_OBJECT",
[key.sqlExpression, value.sqlExpression.jsonBuilderExpression],
filter: filter?.sqlExpression,
isJSONValue: true)
}
}
#else
// MARK: - JSON
extension Database {
/// Validates and minifies a JSON string, with the `JSON` SQL function.
///
@@ -281,6 +281,12 @@ extension Association {
relation.ctes[cte.tableName] = cte.cte
}
}
public func limit(_ limit: Int, offset: Int? = nil) -> Self {
withDestinationRelation { relation in
relation.limit = SQLLimit(limit: limit, offset: offset)
}
}
}
// MARK: - AssociationToOne
@@ -56,6 +56,7 @@
/// - ``select(_:as:)-3o8qw``
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectID()``
/// - ``selectPrimaryKey(as:)``
///
/// ### Batch Delete
@@ -237,7 +238,7 @@ extension QueryInterfaceRequest: SelectionRequest {
select(sqlLiteral, as: type)
}
/// Selects the primary key.
/// Returns a request that selects the primary key.
///
/// All primary keys are supported:
///
@@ -281,6 +282,46 @@ extension QueryInterfaceRequest: SelectionRequest {
.asRequest(of: PrimaryKey.self)
}
/// Returns a request that selects the primary key.
///
/// For example:
///
/// ```swift
/// // SELECT id FROM player WHERE ...
/// let request = try Player.filter(...).selectID()
/// ```
///
/// **Important**: if the record type has an `ID` type that is an
/// optional, such as `Int64?`, it is recommended to prefer
/// ``selectPrimaryKey(as:)`` instead:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64?
/// }
///
/// // NOT RECOMMENDED: Set<Int64?>
/// let ids = try Player.filter(...)
/// .selectID()
/// .fetchSet(db)
///
/// // BETTER: Set<Int64>
/// let ids = try Player.filter(...)
/// .selectPrimaryKey(as: Int64.self)
/// .fetchSet(db)
/// ```
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
{
selectWhenConnected { db in
let primaryKey = try db.primaryKey(self.databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"selectID requires a single-column primary key in the table \(self.databaseTableName)")
return [Column(primaryKey.columns[0])]
}.asRequest(of: RowDecoder.ID.self)
}
public func annotatedWhenConnected(
with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable])
-> Self
@@ -1477,7 +1518,7 @@ private func prefetch(
fatalError("Not implemented: prefetch association without any foreign key")
case let .foreignKey(pivotForeignKey):
let originTable = originRelation.source.tableName
let originTable = originRelation.source.associationOriginTable ?? originRelation.source.tableName
let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable)
let pivotColumns = pivotMapping.map(\.right)
let leftColumns = pivotMapping.map(\.left)
@@ -1610,7 +1651,7 @@ func makePrefetchRequest(
// Author.including(all: Author.books)
let pivotAlias = TableAlias()
let prefetchRelation = association
var prefetchRelation = association
.with {
$0.pivot.relation = $0.pivot.relation
.aliased(pivotAlias)
@@ -1619,7 +1660,52 @@ func makePrefetchRequest(
.destinationRelation()
.annotated(with: pivotColumns.map { pivotAlias[$0].forKey("grdb_\($0)") })
return QueryInterfaceRequest<Row>(relation: prefetchRelation)
if let limit = prefetchRelation.limit {
let baseName = "grdb_" + association.destination.key.name(singular: true)
let cteName = baseName + "_limited"
let rowNumberName = "rowNumber"
let ordering = prefetchRelation.ordering
let rowNumberFilter: SQLExpression
if let offset = limit.offset {
rowNumberFilter = ((offset + 1)..<(offset + 1 + limit.limit)).contains(Column(rowNumberName)).sqlExpression
} else {
rowNumberFilter = (Column(rowNumberName) <= limit.limit).sqlExpression
}
#warning("TODO: the order clause may refer to stuff inside the CTE.")
var limitedPrefetchRelation = prefetchRelation
// Annotate with the row number
.annotatedWhenConnected { db in
var sql: SQL = "ROW_NUMBER() OVER (PARTITION BY "
sql.append(literal: pivotColumns
.map { SQL(Column($0)) }
.joined(separator: ", "))
let orderings = try ordering.resolve(db)
if !orderings.isEmpty {
sql.append(sql: " ORDER BY ")
sql.append(literal: orderings
.map { SQL($0) }
.joined(separator: ", "))
}
sql.append(sql: ")")
return [sql.forKey(rowNumberName)]
}
// Limit is applied below, with the rowNumber filter
.unlimited()
// Turn into a CTE so that we can filter by rowNumber
.asCommonTableExpression(named: cteName)
// Reapply order
.orderWhenConnected { try ordering.resolve($0) }
// Turnt the limit into a rowNumber filter
.filter(rowNumberFilter)
return QueryInterfaceRequest<Row>(relation: limitedPrefetchRelation)
} else {
return QueryInterfaceRequest<Row>(relation: prefetchRelation)
}
}
// CAUTION: Keep this code in sync with prefetch(_:associations:in:)
+7
View File
@@ -61,6 +61,13 @@ extension ColumnExpression {
extension ColumnExpression where Self == Column {
/// The hidden rowID column.
///
/// For example:
///
/// ```swift
/// // SELECT rowid FROM player
/// let rowids = try Player.select(.rowID).fetchSet(db)
/// ```
public static var rowID: Self { Column.rowID }
}
+33 -3
View File
@@ -954,6 +954,17 @@ extension SQLExpression {
"JSON_REPLACE",
"JSON_SET",
"JSON_QUOTE",
"JSONB",
"JSONB_ARRAY",
"JSONB_EXTRACT",
"JSONB_GROUP_ARRAY",
"JSONB_GROUP_OBJECT",
"JSONB_INSERT",
"JSONB_OBJECT",
"JSONB_PATCH",
"JSONB_REMOVE",
"JSONB_REPLACE",
"JSONB_SET",
"LENGTH",
"LIKE",
"LIKELIHOOD",
@@ -1005,6 +1016,16 @@ extension SQLExpression {
"JSON_REPLACE",
"JSON_SET",
"JSON_QUOTE",
"JSONB",
"JSONB_ARRAY",
"JSONB_GROUP_ARRAY",
"JSONB_GROUP_OBJECT",
"JSONB_INSERT",
"JSONB_OBJECT",
"JSONB_PATCH",
"JSONB_REMOVE",
"JSONB_REPLACE",
"JSONB_SET",
]
/// The `COUNT(*)` expression.
@@ -2099,8 +2120,9 @@ extension SQLExpression {
case .jsonValue:
if isJSONValue {
return self
} else if Database.sqliteLibVersionNumber >= 3045000 {
return .function("JSONB", [self])
} else {
// Needs explicit call to JSON()
return .function("JSON", [self])
}
}
@@ -2116,8 +2138,9 @@ extension SQLExpression {
case .jsonValue:
if isJSONValue {
return self
} else if Database.sqliteLibVersionNumber >= 3045000 {
return .function("JSONB", [self])
} else {
// Needs explicit call to JSON()
return .function("JSON", [self])
}
}
@@ -2136,7 +2159,14 @@ public protocol SQLExpressible {
}
extension SQLExpressible where Self == Column {
/// The hidden rowID column
/// The hidden rowID column.
///
/// For example:
///
/// ```swift
/// // SELECT rowid FROM player
/// let rowids = try Player.select(.rowID).fetchSet(db)
/// ```
public static var rowID: Self { Column.rowID }
}
+54 -1
View File
@@ -282,6 +282,12 @@ extension SQLRelation: Refinable {
}
}
func unlimited() -> Self {
with {
$0.limit = nil
}
}
func withStableOrder() -> Self {
with { relation in
relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in
@@ -636,7 +642,7 @@ extension SQLRelation {
}
// <https://github.com/groue/GRDB.swift/issues/1357>
guard selection.allSatisfy(\.isTriviallyCountable) else {
if selection.contains(where: \.requiresTrivialCount) {
return try fetchTrivialCount(db)
}
@@ -655,6 +661,47 @@ extension SQLRelation {
}
}
extension SQLRelation {
#warning("TODO: the order clause may refer to stuff inside the CTE.")
#warning("TODO: Try to leave the ordering inside the CTE")
func asCommonTableExpression(named tableName: String) -> Self {
with { relation in
GRDBPrecondition(ctes[tableName] == nil, """
Can't turn relation into a Common Table Expression because \
CTE '\(tableName)' is already defined. Please file a bug \
at https://github.com/groue/GRDB.swift/issues/new
""")
relation.ctes[tableName] = SQLCTE(
tableName: tableName,
columns: nil,
sqlSubquery: .relation(
self
.unorderedUnlessLimited() // only preserve ordering in the CTE if limited
.removingPrefetchedAssociations()),
isRecursive: false)
relation.source = SQLSource(
tableName: tableName,
associationOriginTable: relation.source.associationOriginTable ?? relation.source.tableName)
relation.selectionPromise = DatabasePromise { _ in [.allColumns] }
relation.filterPromise = nil
relation.isDistinct = false
relation.groupPromise = nil
relation.havingExpressionPromise = nil
relation.limit = nil
relation = relation.filteringChildren { child in
switch child.kind {
case .all, .bridge: true
case .oneOptional, .oneRequired: false
}
}
}
}
}
// MARK: - SQLLimit
struct SQLLimit {
@@ -673,9 +720,15 @@ struct SQLLimit {
// MARK: - SQLSource
struct SQLSource: Sendable {
/// The name of a database table to select from.
var tableName: String
var alias: TableAlias?
/// When not nil, use this table name instead of `tableName` when looking
/// for foreign keys on this source. This string is not nil when an
/// `SQLRelation` has been turned into a common table expression.
var associationOriginTable: String?
func aliased(_ alias: TableAlias) -> SQLSource {
if let sourceAlias = self.alias {
alias.becomeProxy(of: sourceAlias)
+211 -45
View File
@@ -26,6 +26,12 @@ public struct SQLSelection: Sendable {
/// All columns, qualified: `player.*`
case qualifiedAllColumns(TableAlias)
/// All columns but the specified ones
case allColumnsExcluding(Set<CaseInsensitiveIdentifier>)
/// All columns but the specified ones, qualified.
case qualifiedAllColumnsExcluding(TableAlias, Set<CaseInsensitiveIdentifier>)
/// An expression
case expression(SQLExpression)
@@ -41,11 +47,21 @@ public struct SQLSelection: Sendable {
/// All columns: `*`
static let allColumns = SQLSelection(impl: .allColumns)
/// All columns but the specified ones.
static func allColumnsExcluding(_ excludedColumns: Set<CaseInsensitiveIdentifier>) -> Self {
SQLSelection(impl: .allColumnsExcluding(excludedColumns))
}
/// All columns, qualified: `player.*`
static func qualifiedAllColumns(_ alias: TableAlias) -> Self {
self.init(impl: .qualifiedAllColumns(alias))
}
/// All columns but the specified ones, qualified.
static func qualifiedAllColumnsExcluding(_ alias: TableAlias, _ excludedColumns: Set<CaseInsensitiveIdentifier>) -> Self {
self.init(impl: .qualifiedAllColumnsExcluding(alias, excludedColumns))
}
/// An expression
static func expression(_ expression: SQLExpression) -> Self {
self.init(impl: .expression(expression))
@@ -70,13 +86,16 @@ extension SQLSelection {
/// Returns nil when the number of columns is unknown.
func columnCount(_ context: SQLGenerationContext) throws -> Int? {
switch impl {
case .allColumns:
case .allColumns, .allColumnsExcluding:
// Likely a GRDB bug: we can't count the number of columns in an
// unqualified table.
return nil
case let .qualifiedAllColumns(alias):
return try context.columnCount(in: alias.tableName)
return try context.columnCount(in: alias.tableName, excluding: [])
case let .qualifiedAllColumnsExcluding(alias, excludedColumns):
return try context.columnCount(in: alias.tableName, excluding: excludedColumns)
case .expression,
.aliasedExpression:
@@ -104,7 +123,28 @@ extension SQLSelection {
// SELECT COUNT(*) FROM tableName ...
return .all
case .qualifiedAllColumns:
case .allColumnsExcluding:
// SELECT DISTINCT a, b, c FROM tableName ...
if distinct {
// TODO: if the selection were qualified, and if we had a
// database connection, we could detect the case where there
// remains only one column, and we could perform a
// SELECT COUNT(DISTINCT remainingColumn) FROM tableName
//
// Since most people will not use `.allColumns(excluding:)`
// when they want to select only one column, I guess that
// this optimization has little chance to be needed.
//
// Can't count
return nil
}
// SELECT a, b, c FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
return .all
case .qualifiedAllColumns, .qualifiedAllColumnsExcluding:
return nil
case let .expression(expression),
@@ -126,41 +166,6 @@ extension SQLSelection {
}
}
/// Returns the SQL that feeds the argument of the `COUNT` function.
///
/// For example:
///
/// COUNT(*)
/// COUNT(id)
/// ^---- countedSQL
///
/// - parameter context: An SQL generation context which accepts
/// statement arguments.
func countedSQL(_ context: SQLGenerationContext) throws -> String {
switch impl {
case .allColumns:
return "*"
case let .qualifiedAllColumns(alias):
if context.qualifier(for: alias) != nil {
// SELECT COUNT(t.*) is invalid SQL
fatalError("Not implemented, or invalid query")
}
return "*"
case let .expression(expression),
let .aliasedExpression(expression, _):
return try expression.sql(context)
case .literal:
fatalError("""
Selection literals can't be counted. \
To resolve this error, select one or several literal expressions instead. \
See SQL.sqlExpression.
""")
}
}
/// Returns the SQL that feeds the selection of a `SELECT` statement.
///
/// For example:
@@ -179,11 +184,38 @@ extension SQLSelection {
case .allColumns:
return "*"
case .allColumnsExcluding:
// Likely a GRDB bug: we don't know the table name so we can't
// load remaining columns. This selection should have been
// turned into a `.qualifiedAllColumnsExcluding`.
fatalError("Not implemented, or invalid query")
case let .qualifiedAllColumns(alias):
if let qualifier = context.qualifier(for: alias) {
return qualifier.quotedDatabaseIdentifier + ".*"
}
return "*"
case let .qualifiedAllColumnsExcluding(alias, excludedColumns):
let columnsNames = try context.columnNames(in: alias.tableName)
let remainingColumnsNames = if excludedColumns.isEmpty {
columnsNames
} else {
columnsNames.filter {
!excludedColumns.contains(CaseInsensitiveIdentifier(rawValue: $0))
}
}
if columnsNames.count == remainingColumnsNames.count {
// We're not excluding anything
if let qualifier = context.qualifier(for: alias) {
return qualifier.quotedDatabaseIdentifier + ".*"
}
return "*"
} else {
return try remainingColumnsNames
.map { try SQLExpression.column($0).qualified(with: alias).sql(context) }
.joined(separator: ", ")
}
case let .expression(expression):
return try expression.sql(context)
@@ -228,12 +260,15 @@ extension SQLSelection {
/// Returns a qualified selection
func qualified(with alias: TableAlias) -> SQLSelection {
switch impl {
case .qualifiedAllColumns:
case .qualifiedAllColumns, .qualifiedAllColumnsExcluding:
return self
case .allColumns:
return .qualifiedAllColumns(alias)
case let .allColumnsExcluding(excludedColumns):
return .qualifiedAllColumnsExcluding(alias, excludedColumns)
case let .expression(expression):
return .expression(expression.qualified(with: alias))
@@ -245,15 +280,27 @@ extension SQLSelection {
}
}
/// Returns whether this selection MUST be counted with a "trivial"
/// count: `SELECT COUNT(*) FROM (SELECT ...)`.
///
/// Supports SQLRelation.fetchCount.
///
/// See <https://github.com/groue/GRDB.swift/issues/1357>
var isTriviallyCountable: Bool {
var requiresTrivialCount: Bool {
switch impl {
case .aliasedExpression, .literal:
return false
case .allColumns, .qualifiedAllColumns, .expression:
// Trivial count is required.
//
// For example, the WHERE clause here requires the aliased
// column to be preserved in the counting request:
// SELECT *, column AS alt FROM player WHERE alt
return true
case .allColumns, .qualifiedAllColumns:
return false
case .allColumnsExcluding, .qualifiedAllColumnsExcluding:
return false
case .expression:
return false
}
}
}
@@ -297,15 +344,41 @@ enum SQLCount {
///
/// ## Topics
///
/// ### Standard Selections
///
/// - ``rowID``
/// - ``allColumns``
/// - ``allColumns(excluding:)-3sg4w``
/// - ``allColumns(excluding:)-3blq4``
///
/// ### Supporting Types
///
/// - ``AllColumns``
/// - ``AllColumnsExcluding``
/// - ``SQLSelection``
public protocol SQLSelectable {
/// Returns an SQL selection.
var sqlSelection: SQLSelection { get }
}
extension SQLSelectable where Self == Column {
/// The hidden rowID column.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns, .rowID]
/// }
/// }
///
/// // SELECT *, rowid FROM player
/// Player.fetchAll(db)
/// ```
public static var rowID: Self { Column.rowID }
}
extension SQLSelection: SQLSelectable {
// Not a real deprecation, just a usage warning
@available(*, deprecated, message: "Already SQLSelection")
@@ -319,10 +392,14 @@ extension SQLSelection: SQLSelectable {
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// // SELECT * FROM player
/// let players = try Player.select(AllColumns()).fetchAll(db)
/// struct Player: FetchableRecord, TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns, .rowID]
/// }
/// }
///
/// // SELECT *, rowid FROM player
/// Player.fetchAll(db)
/// ```
public struct AllColumns: Sendable {
/// The `*` selection.
@@ -334,3 +411,92 @@ extension AllColumns: SQLSelectable {
.allColumns
}
}
extension SQLSelectable where Self == AllColumns {
/// All columns of the requested table.
///
/// For example:
///
/// ```swift
/// struct Player: FetchableRecord, TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns, .rowID]
/// }
/// }
///
/// // SELECT *, rowid FROM player
/// Player.fetchAll(db)
/// ```
public static var allColumns: AllColumns { AllColumns() }
}
// MARK: - AllColumnsExcluding
/// `AllColumnsExcluding` selects all columns in a database table, but the
/// ones you specify.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns(excluding: ["generatedColumn"])]
/// }
/// }
///
/// // SELECT id, name, score FROM player
/// Player.fetchAll(db)
/// ```
public struct AllColumnsExcluding: Sendable {
var excludedColumns: Set<CaseInsensitiveIdentifier>
public init(_ excludedColumns: some Collection<String>) {
self.excludedColumns = Set(excludedColumns.lazy.map {
CaseInsensitiveIdentifier(rawValue: $0)
})
}
}
extension AllColumnsExcluding: SQLSelectable {
public var sqlSelection: SQLSelection {
.allColumnsExcluding(excludedColumns)
}
}
extension SQLSelectable where Self == AllColumnsExcluding {
/// All columns of the requested table, excluding the provided columns.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns(excluding: ["generatedColumn"])]
/// }
/// }
///
/// // SELECT id, name, score FROM player
/// Player.fetchAll(db)
/// ```
public static func allColumns(excluding excludedColumns: some Collection<String>) -> Self {
AllColumnsExcluding(excludedColumns)
}
/// All columns of the requested table, excluding the provided columns.
///
/// For example:
///
/// ```swift
/// struct Player: TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns(excluding: [Column("generatedColumn")])]
/// }
/// }
///
/// // SELECT id, name, score FROM player
/// Player.fetchAll(db)
/// ```
public static func allColumns(excluding excludedColumns: some Collection<any ColumnExpression>) -> Self {
AllColumnsExcluding(excludedColumns.map(\.name))
}
}
+35
View File
@@ -94,6 +94,7 @@
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectID()``
/// - ``selectPrimaryKey(as:)``
/// - ``with(_:)``
///
@@ -424,6 +425,40 @@ extension Table {
all().selectPrimaryKey(as: type)
}
/// Returns a request that selects the primary key.
///
/// For example:
///
/// ```swift
/// let table = Table<Player>("player")
///
/// // SELECT id FROM player
/// let request = try table.selectID()
/// ```
///
/// **Important**: if the record type has an `ID` type that is an
/// optional, such as `Int64?`, it is recommended to prefer
/// ``selectPrimaryKey(as:)`` instead:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64?
/// }
///
/// let table = Table<Player>("player")
///
/// // NOT RECOMMENDED: Set<Int64?>
/// let ids = try table.selectID().fetchSet(db)
///
/// // BETTER: Set<Int64>
/// let ids = try table.selectPrimaryKey(as: Int64.self).fetchSet(db)
/// ```
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
where RowDecoder: Identifiable
{
all().selectID()
}
/// Returns a request with the provided result columns appended to the
/// table columns.
///
@@ -153,15 +153,50 @@ final class SQLGenerationContext {
return nil
}
func columnCount(in tableName: String) throws -> Int {
/// Return the number of columns in the table or CTE identified
/// by `tableName`.
///
/// - parameter tableName: The table name.
/// - parameter excludedColumns: The eventual set of excluded columns.
func columnCount(
in tableName: String,
excluding excludedColumns: Set<CaseInsensitiveIdentifier>
) throws -> Int {
if let cte = ownCTEs[tableName.lowercased()] {
return try cte.columnCount(db)
if excludedColumns.isEmpty {
return try cte.columnCount(db)
} else {
fatalError("Not implemented: counting CTE columns with excluded columns")
}
}
switch parent {
case let .context(context):
return try context.columnCount(in: tableName)
return try context.columnCount(in: tableName, excluding: excludedColumns)
case let .none(db: db, argumentsSink: _):
return try db.columns(in: tableName).count
if excludedColumns.isEmpty {
return try db.columns(in: tableName).count
} else {
return try db
.columns(in: tableName)
.filter { !excludedColumns.contains(CaseInsensitiveIdentifier(rawValue: $0.name)) }
.count
}
}
}
/// Return the names of the columns in the table or CTE identified
/// by `tableName`.
///
/// - parameter tableName: The table name.
func columnNames(in tableName: String) throws -> [String] {
if ownCTEs[tableName.lowercased()] != nil {
fatalError("Not implemented: extracing CTE column names")
}
switch parent {
case let .context(context):
return try context.columnNames(in: tableName)
case let .none(db: db, argumentsSink: _):
return try db.columns(in: tableName).map(\.name)
}
}
}
@@ -138,7 +138,7 @@ struct SQLQueryGenerator: Refinable {
let region = try prefetchedRegion(
db,
associations: prefetchedAssociations,
from: relation.source.tableName)
from: relation.source.associationOriginTable ?? relation.source.tableName)
statement.databaseRegion.formUnion(region)
}
@@ -235,7 +235,11 @@ struct SQLQueryGenerator: Refinable {
sql += " LIMIT " + limit.sql
}
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
return try makeStatement(
db, sql: sql,
arguments: context.arguments,
returning: selection,
from: relation.source.tableName)
case .unique:
return try makeTrivialDeleteStatement(db, selection: selection)
@@ -264,7 +268,11 @@ struct SQLQueryGenerator: Refinable {
sql += try selectPrimaryKey.requestSQL(subqueryContext)
sql += ")"
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
return try makeStatement(
db, sql: sql,
arguments: context.arguments,
returning: selection,
from: tableName)
}
/// Returns an `UPDATE` statement, with `RETURNING` clause if `selection`
@@ -323,7 +331,11 @@ struct SQLQueryGenerator: Refinable {
sql += " LIMIT " + limit.sql
}
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
return try makeStatement(
db, sql: sql,
arguments: context.arguments,
returning: selection,
from: relation.source.tableName)
case .unique:
return try makeTrivialUpdateStatement(
@@ -380,7 +392,11 @@ struct SQLQueryGenerator: Refinable {
sql += try selectPrimaryKey.requestSQL(subqueryContext)
sql += ")"
return try makeStatement(db, sql: sql, arguments: context.arguments, returning: selection)
return try makeStatement(
db, sql: sql,
arguments: context.arguments,
returning: selection,
from: tableName)
}
// Support for the RETURNING clause
@@ -388,7 +404,8 @@ struct SQLQueryGenerator: Refinable {
_ db: Database,
sql: String,
arguments: StatementArguments,
returning selection: [any SQLSelectable])
returning selection: [any SQLSelectable],
from tableName: String)
throws -> Statement
{
if selection.isEmpty {
@@ -396,12 +413,17 @@ struct SQLQueryGenerator: Refinable {
statement.arguments = arguments
return statement
} else {
let context = SQLGenerationContext(db)
// Generate the RETURNING clause by turning selection into SQL.
// Make sure the selection is qualified with a table alias, so
// that selectables such as `.allColumns(excluding:)` can query
// the database about the database table.
let alias = TableAlias(tableName: tableName)
let context = SQLGenerationContext(db, aliases: [alias])
var sql = sql
var arguments = arguments
sql += " RETURNING "
sql += try selection
.map { try $0.sqlSelection.sql(context) }
.map { try $0.sqlSelection.qualified(with: alias).sql(context) }
.joined(separator: ", ")
arguments += context.arguments
let statement = try db.makeStatement(sql: sql)
@@ -719,9 +741,15 @@ private struct SQLQualifiedSource {
var tableName: String
var alias: TableAlias
/// When not nil, use this table name instead of `tableName` when looking
/// for foreign keys on this source. This string is not nil when an
/// `SQLRelation` has been turned into a common table expression.
var associationOriginTable: String?
init(_ source: SQLSource) {
self.tableName = source.tableName
self.alias = source.alias ?? TableAlias(tableName: source.tableName)
self.associationOriginTable = source.associationOriginTable
assert(alias.tableName == tableName)
}
@@ -67,7 +67,12 @@ extension SQLInterpolation {
/// let player: Player = ...
/// let request: SQLRequest<Player> = "SELECT \(columnsOf: Player.self, tableAlias: "p") FROM player p"
public mutating func appendInterpolation(columnsOf recordType: (some TableRecord).Type, tableAlias: String? = nil) {
let alias = TableAlias(name: tableAlias ?? recordType.databaseTableName)
// Make sure we provide the tableName, so that we can interpolate
// the columns of a type whose `databaseSelection` contains an
// instance of `AllColumnsExcluding`.
let alias = TableAlias(
tableName: recordType.databaseTableName,
userName: tableAlias ?? recordType.databaseTableName)
elements.append(contentsOf: recordType.databaseSelection
.map { CollectionOfOne(.selection($0.sqlSelection.qualified(with: alias))) }
.joined(separator: CollectionOfOne(.sql(", "))))
@@ -79,7 +84,7 @@ extension SQLInterpolation {
///
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = """
/// SELECT \(AllColumns()) FROM player
/// SELECT \(.allColumns) FROM player
/// """
public mutating func appendInterpolation(_ selection: some SQLSelectable) {
elements.append(.selection(selection.sqlSelection))
@@ -89,7 +94,7 @@ extension SQLInterpolation {
///
/// // SELECT * FROM player
/// let request: SQLRequest<Player> = """
/// SELECT \(AllColumns()) FROM player
/// SELECT \(.allColumns) FROM player
/// """
@_disfavoredOverload
public mutating func appendInterpolation(_ selection: (any SQLSelectable)?) {
@@ -370,6 +370,32 @@ public final class ColumnDefinition {
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
/// // No property for `totalScore`
/// var id: Int64
/// var score: Int
/// var bonus: Int
/// }
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
@@ -409,6 +435,32 @@ public final class ColumnDefinition {
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
/// // No property for `totalScore`
/// var id: Int64
/// var score: Int
/// var bonus: Int
/// }
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
@@ -447,6 +499,32 @@ public final class ColumnDefinition {
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
/// // No property for `totalScore`
/// var id: Int64
/// var score: Int
/// var bonus: Int
/// }
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
@@ -487,6 +565,32 @@ public final class ColumnDefinition {
/// }
/// ```
///
/// To remove the generated columns from the selection of record types,
/// define their `databaseSelection`:
///
/// ```swift
/// struct Player: Codable {
/// // No property for `totalScore`
/// var id: Int64
/// var score: Int
/// var bonus: Int
/// }
///
/// extension Player: FetchableRecord, PersistableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// // Option 1
/// [Column("id"), Column("score"), Column("bonus")]
/// // Option 2
/// [.allColumns(excluding: ["totalScore"])]
/// }
/// }
///
/// // SELECT id, score, bonus FROM player
/// let players = try dbQueue.read { db in
/// try Player.fetchAll(db)
/// }
/// ```
///
/// Related SQLite documentation: <https://sqlite.org/gencol.html>
///
/// - parameters:
@@ -1,7 +1,7 @@
/// The protocol for SQLite virtual table modules.
///
/// The protocol can define a DSL for the
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` `Database` method:
/// ``Database/create(virtualTable:options:using:_:)`` `Database` method:
///
/// ```swift
/// let module = ...
@@ -20,7 +20,7 @@
/// - ``VirtualTableConfiguration``
public protocol VirtualTableModule {
/// The type of the argument in the
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` closure.
/// ``Database/create(virtualTable:options:using:_:)`` closure.
///
/// For example:
///
@@ -35,7 +35,7 @@ public protocol VirtualTableModule {
var moduleName: String { get }
/// Returns a table definition that is passed as the argument in the
/// ``Database/create(virtualTable:ifNotExists:using:_:)`` closure.
/// ``Database/create(virtualTable:options:using:_:)`` closure.
///
/// For example:
///
@@ -54,10 +54,29 @@ public protocol VirtualTableModule {
func database(_ db: Database, didCreate tableName: String, using definition: TableDefinition) throws
}
// TODO: Question the existence of this API. VirtualTableConfiguration was
// never able to be used by user-defined VirtualTableModule types, because
// `ifNotExists` has never been public.
public struct VirtualTableConfiguration {
/// If true, existing objects must not be replaced, or generate any error
/// (even if they do not match the objects that would be created otherwise.)
var ifNotExists: Bool
/// If true, new objects must be created in the temp schema.
var temporary: Bool
}
/// Virtual table creation options.
public struct VirtualTableOptions: OptionSet, Sendable {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
/// Only creates the table if it does not already exist.
public static let ifNotExists = VirtualTableOptions(rawValue: 1 << 0)
/// Creates a temporary table.
public static let temporary = VirtualTableOptions(rawValue: 1 << 1)
}
extension Database {
@@ -77,18 +96,24 @@ extension Database {
///
/// - parameters:
/// - name: The table name.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - options: Table creation options.
/// - module: The name of an SQLite virtual table module.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
public func create(
virtualTable name: String,
options: VirtualTableOptions = [],
using module: String
) throws {
var chunks: [String] = []
chunks.append("CREATE VIRTUAL TABLE")
if ifNotExists {
if options.contains(.ifNotExists) {
chunks.append("IF NOT EXISTS")
}
chunks.append(name.quotedDatabaseIdentifier)
if options.contains(.temporary) {
chunks.append("temp.\(name.quotedDatabaseIdentifier)")
} else {
chunks.append(name.quotedDatabaseIdentifier)
}
chunks.append("USING")
chunks.append(module)
let sql = chunks.joined(separator: " ")
@@ -114,21 +139,21 @@ extension Database {
///
/// - parameters:
/// - tableName: The table name.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - options: Table creation options.
/// - module: a virtual module.
/// - body: An optional closure that defines the virtual table.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public func create<Module: VirtualTableModule>(
virtualTable tableName: String,
ifNotExists: Bool = false,
options: VirtualTableOptions = [],
using module: Module,
_ body: ((Module.TableDefinition) throws -> Void)? = nil)
throws
{
// Define virtual table
let configuration = VirtualTableConfiguration(ifNotExists: ifNotExists)
let configuration = VirtualTableConfiguration(
ifNotExists: options.contains(.ifNotExists),
temporary: options.contains(.temporary))
let definition = module.makeTableDefinition(configuration: configuration)
if let body {
try body(definition)
@@ -137,10 +162,14 @@ extension Database {
// Create virtual table
var chunks: [String] = []
chunks.append("CREATE VIRTUAL TABLE")
if ifNotExists {
if options.contains(.ifNotExists) {
chunks.append("IF NOT EXISTS")
}
chunks.append(tableName.quotedDatabaseIdentifier)
if options.contains(.temporary) {
chunks.append("temp.\(tableName.quotedDatabaseIdentifier)")
} else {
chunks.append(tableName.quotedDatabaseIdentifier)
}
chunks.append("USING")
let arguments = try module.moduleArguments(for: definition, in: self)
if arguments.isEmpty {
@@ -156,4 +185,78 @@ extension Database {
return .commit
}
}
/// Creates a virtual database table.
///
/// For example:
///
/// ```swift
/// // CREATE VIRTUAL TABLE vocabulary USING spellfix1
/// try db.create(virtualTable: "vocabulary", using: "spellfix1")
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html>
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``create(virtualTable:options:using:)`` instead.
///
/// - parameters:
/// - name: The table name.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - module: The name of an SQLite virtual table module.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@_disfavoredOverload
public func create(virtualTable name: String, ifNotExists: Bool = false, using module: String) throws {
try create(
virtualTable: name,
options: ifNotExists ? .ifNotExists : [],
using: module)
}
/// Creates a virtual database table.
///
/// The type of the argument of the `body` function depends on the type of
/// the `module` argument: refer to this module's documentation.
///
/// You can use this method to create full-text virtual tables:
///
/// ```swift
/// try db.create(virtualTable: "book", using: FTS4()) { t in
/// t.column("title")
/// t.column("author")
/// t.column("body")
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/lang_createtable.html>
///
/// - warning: This is a legacy interface that is preserved for backwards
/// compatibility. Use of this interface is not recommended: prefer
/// ``create(virtualTable:options:using:_:)`` instead.
///
/// - parameters:
/// - tableName: The table name.
/// - ifNotExists: If false (the default), an error is thrown if the
/// table already exists. Otherwise, the table is created unless it
/// already exists.
/// - module: a virtual module.
/// - body: An optional closure that defines the virtual table.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
@_disfavoredOverload
public func create<Module: VirtualTableModule>(
virtualTable tableName: String,
ifNotExists: Bool = false,
using module: Module,
_ body: ((Module.TableDefinition) throws -> Void)? = nil)
throws
{
try create(
virtualTable: tableName,
options: ifNotExists ? .ifNotExists : [],
using: module,
body)
}
}
@@ -251,6 +251,36 @@ extension TableRecord {
all().selectPrimaryKey(as: type)
}
/// Returns a request that selects the primary key.
///
/// For example:
///
/// ```swift
/// // SELECT id FROM player
/// let request = try Player.selectID()
/// ```
///
/// **Important**: if the record type has an `ID` type that is an
/// optional, such as `Int64?`, it is recommended to prefer
/// ``selectPrimaryKey(as:)`` instead:
///
/// ```swift
/// struct Player: Identifiable {
/// var id: Int64?
/// }
///
/// // NOT RECOMMENDED: Set<Int64?>
/// let ids = try Player.selectID().fetchSet(db)
///
/// // BETTER: Set<Int64>
/// let ids = try Player.selectPrimaryKey(as: Int64.self).fetchSet(db)
/// ```
public static func selectID() -> QueryInterfaceRequest<Self.ID>
where Self: Identifiable
{
all().selectID()
}
/// Returns a request with the provided result columns appended to the
/// record selection.
///
+6 -1
View File
@@ -524,7 +524,12 @@ public enum DatabaseDataEncodingStrategy: Sendable {
/// var creationDate: Date
/// }
/// ```
public enum DatabaseDateEncodingStrategy: Sendable {
public enum DatabaseDateEncodingStrategy: @unchecked Sendable {
// @unchecked Sendable because of `DateFormatter`, which lost its
// `Sendable` conformance with Xcode 16.3 beta. See
// <https://github.com/swiftlang/swift/issues/78635>.
// TODO: remove @unchecked when the compiler issue is fixed.
/// The strategy that uses formatting from the Date structure.
///
/// It encodes dates using the format "YYYY-MM-DD HH:MM:SS.SSS" in the
+6 -1
View File
@@ -929,7 +929,12 @@ public enum DatabaseDataDecodingStrategy: Sendable {
/// var name: String
/// var registrationDate: Date // decoded from epoch timestamp
/// }
public enum DatabaseDateDecodingStrategy: Sendable {
public enum DatabaseDateDecodingStrategy: @unchecked Sendable {
// @unchecked Sendable because of `DateFormatter`, which lost its
// `Sendable` conformance with Xcode 16.3 beta. See
// <https://github.com/swiftlang/swift/issues/78635>.
// TODO: remove @unchecked when the compiler issue is fixed.
/// The strategy that uses formatting from the Date structure.
///
/// It decodes numeric values as a number of seconds since Epoch
@@ -249,12 +249,17 @@ final class DAO<Record: MutablePersistableRecord> {
statement.setUncheckedArguments(arguments)
return statement
} else {
let context = SQLGenerationContext(db)
// Generate the RETURNING clause by turning selection into SQL.
// Make sure the selection is qualified with a table alias, so
// that selectables such as `.allColumns(excluding:)` can query
// the database about the database table.
let alias = TableAlias(tableName: databaseTableName)
let context = SQLGenerationContext(db, aliases: [alias])
var sql = sql
var arguments = arguments
sql += " RETURNING "
sql += try selection
.map { try $0.sqlSelection.sql(context) }
.map { try $0.sqlSelection.qualified(with: alias).sql(context) }
.joined(separator: ", ")
arguments += context.arguments
let statement = try db.internalCachedStatement(sql: sql)
+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.
+15 -4
View File
@@ -98,6 +98,7 @@ import Foundation
/// - ``select(literal:as:)``
/// - ``select(sql:arguments:)``
/// - ``select(sql:arguments:as:)``
/// - ``selectID()``
/// - ``selectPrimaryKey(as:)``
/// - ``with(_:)``
///
@@ -134,8 +135,9 @@ public protocol TableRecord {
///
/// ```swift
/// struct Player: TableRecord {
/// // This is the default
/// static var databaseSelection: [any SQLSelectable] {
/// [AllColumns()]
/// [.allColumns]
/// }
/// }
///
@@ -146,11 +148,20 @@ public protocol TableRecord {
/// }
/// }
///
/// struct Team: TableRecord {
/// static var databaseSelection: [any SQLSelectable] {
/// [.allColumns(excluding: ["generatedColumn"])]
/// }
/// }
///
/// // SELECT * FROM player
/// try Player.fetchAll(db)
///
/// // SELECT id, name FROM player
/// try PartialPlayer.fetchAll(db)
///
/// // SELECT id, name, color FROM team
/// try Team.fetchAll(db)
/// ```
///
/// > Important: Make sure the `databaseSelection` property is
@@ -168,7 +179,7 @@ public protocol TableRecord {
/// > // concurrency-safe because non-'Sendable' type
/// > // '[any SQLSelectable]' may have shared
/// > // mutable state.
/// > static let databaseSelection: [any SQLSelectable] = [AllColumns()]
/// > static let databaseSelection: [any SQLSelectable] = [.allColumns]
/// > ```
static var databaseSelection: [any SQLSelectable] { get }
}
@@ -215,9 +226,9 @@ extension TableRecord {
defaultDatabaseTableName
}
/// The default selection is all columns: `[AllColumns()]`.
/// The default selection is all columns: `[.allColumns]`.
public static var databaseSelection: [any SQLSelectable] {
[AllColumns()]
[.allColumns]
}
}
+2 -3
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|status)$", "$1es")
inflections.plural("(alias|bias|canvas|focus|gas|lens|status)$", "$1es")
inflections.plural("(bu)s$", "$1ses")
inflections.plural("(buffal|tomat|her)o$", "$1oes")
inflections.plural("([ti])um$", "$1a")
@@ -102,13 +102,12 @@ extension Inflections {
inflections.singular("(cris|test)(is|es)$", "$1is")
inflections.singular("^(a)x[ie]s$", "$1xis")
inflections.singular("(octop|vir)(us|i)$", "$1us")
inflections.singular("(alias|status)(es)?$", "$1")
inflections.singular("(alias|bias|canvas|focus|gas|lens|status)(es)?$", "$1")
inflections.singular("^(ox)en$", "$1")
inflections.singular("(vert|ind)ices$", "$1ex")
inflections.singular("(matr)ices$", "$1ix")
inflections.singular("(quiz)zes$", "$1")
inflections.singular("(database)s$", "$1")
inflections.singular("(canvas)(es)?$", "$1")
inflections.uncountableWords([
"advice",
+155 -125
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**: 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)
**Latest release**: February 23, 2025 • [version 7.3.0](https://github.com/groue/GRDB.swift/tree/v7.3.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ &bull; SQLite 3.20.0+ &bull; Swift 6+ / Xcode 16+
**Contact**:
- Release announcements and usage tips: follow [@groue](http://twitter.com/groue) on Twitter, [@groue@hachyderm.io](https://hachyderm.io/@groue) on Mastodon.
- Release announcements and usage tips: follow [@groue@hachyderm.io](https://hachyderm.io/@groue) on Mastodon.
- Report bugs in a [Github issue](https://github.com/groue/GRDB.swift/issues/new). Make sure you check the [existing issues](https://github.com/groue/GRDB.swift/issues?q=is%3Aopen) first.
- A question? Looking for advice? Do you wonder how to contribute? Fancy a chat? Go to the [GitHub discussions](https://github.com/groue/GRDB.swift/discussions), or the [GRDB forums](https://forums.swift.org/c/related-projects/grdb).
@@ -281,7 +281,7 @@ Documentation
#### Reference
- 📖 [GRDB Reference](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/)
- 📖 [GRDB Reference](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/)
#### Getting Started
@@ -295,7 +295,7 @@ Documentation
#### Records and the Query Interface
- [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies
- [Query Interface](#the-query-interface): A swift way to generate SQL &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)
- [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)
#### 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/v7.0.0-beta.6/documentation/grdb/databaseschemaintrospection)
- [Row Adapters](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter)
- [Database Schema Introspection](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschemaintrospection)
- [Row Adapters](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter)
- [Raw SQLite Pointers](#raw-sqlite-pointers)
## Executing Updates
Once granted with a [database connection], the [`execute(sql:arguments:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/execute(sql:arguments:)) method executes the SQL statements that do not return any database row, such as `CREATE TABLE`, `INSERT`, `DELETE`, `ALTER`, etc.
Once granted with a [database connection], the [`execute(sql:arguments:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/execute(sql:arguments:)) method executes the SQL statements that do not return any database row, such as `CREATE TABLE`, `INSERT`, `DELETE`, `ALTER`, etc.
For example:
@@ -474,7 +474,7 @@ try dbQueue.write { db in
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [`StatementArguments`] for a detailed documentation of SQLite arguments.
You can also embed query arguments right into your SQL queries, with [`execute(literal:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/execute(literal:)), as in the example below. See [SQL Interpolation] for more details.
You can also embed query arguments right into your SQL queries, with [`execute(literal:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/execute(literal:)), as in the example below. See [SQL Interpolation] for more details.
```swift
try dbQueue.write { db in
@@ -526,7 +526,7 @@ try db.execute(literal: """
When you want to make sure that a single statement is executed, use a prepared [`Statement`].
**After an INSERT statement**, you can get the row ID of the inserted row with [`lastInsertedRowID`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/lastinsertedrowid):
**After an INSERT statement**, you can get the row ID of the inserted row with [`lastInsertedRowID`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/lastinsertedrowid):
```swift
try db.execute(
@@ -626,7 +626,7 @@ try Row.fetchOne(...) // Row?
### Cursors
📖 [`Cursor`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/cursor)
📖 [`Cursor`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/cursor)
**Whenever you consume several rows from the database, you can fetch an Array, a Set, or a Cursor**.
@@ -712,7 +712,7 @@ try dbQueue.read { db in
let dictionary = try Dictionary(uniqueKeysWithValues: cursor)
```
- **Cursors adopt the [Cursor](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/cursor) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
- **Cursors adopt the [Cursor](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/cursor) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
```swift
// Prints all Github links
@@ -753,7 +753,7 @@ If you don't see, or don't care about the difference, use arrays. If you care ab
- [Column Values](#column-values)
- [DatabaseValue](#databasevalue)
- [Rows as Dictionaries](#rows-as-dictionaries)
- 📖 [`Row`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/row)
- 📖 [`Row`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/row)
#### Fetching Rows
@@ -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/v7.0.0-beta.6/documentation/grdb/databaseschema) first.
Of course, you need to open a [database connection], and [create database tables](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) first.
To define a record type, define a type and extend it with protocols that come with focused sets of features.
@@ -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/v7.0.0-beta.6/documentation/grdb/databaseschema)
- [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/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,31 @@ You can now build requests with the following methods: `all`, `none`, `select`,
By default, all columns are selected. See [Columns Selected by a Request].
- [`select(...)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/selectionrequest/select(_:)-30yzl) and [`select(..., as:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/queryinterfacerequest/select(_:as:)-282xc) define the selected columns. See [Columns Selected by a Request].
- [`select(...)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/selectionrequest/select(_:)-30yzl) and [`select(..., as:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/select(_:as:)-282xc) define the selected columns. See [Columns Selected by a Request].
```swift
// SELECT name FROM player
Player.select(nameColumn, as: String.self)
```
- [`annotated(with: expression...)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/selectionrequest/annotated(with:)-6ehs4) extends the selection.
- [`selectID()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/selectID()) is available on [Identifiable Records]. It supports all tables that have a single-column primary key:
```swift
// SELECT id FROM player
Player.selectID()
// SELECT id FROM player WHERE name IS NOT NULL
Player.filter(nameColumn != nil).selectID()
```
- [`annotated(with: expression...)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/selectionrequest/annotated(with:)-6ehs4) extends the selection.
```swift
// SELECT *, (score + bonus) AS total FROM player
Player.annotated(with: (scoreColumn + bonusColumn).forKey("total"))
```
- [`annotated(with: aggregate)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/derivablerequest/annotated(with:)-74xfs) extends the selection with [association aggregates](Documentation/AssociationsBasics.md#association-aggregates).
- [`annotated(with: aggregate)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/derivablerequest/annotated(with:)-74xfs) extends the selection with [association aggregates](Documentation/AssociationsBasics.md#association-aggregates).
```swift
// SELECT team.*, COUNT(DISTINCT player.id) AS playerCount
@@ -3358,7 +3368,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Team.annotated(with: Team.players.count)
```
- [`annotated(withRequired: association)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/annotated(withrequired:)) and [`annotated(withOptional: association)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/annotated(withoptional:)) extends the selection with [Associations].
- [`annotated(withRequired: association)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/annotated(withrequired:)) and [`annotated(withOptional: association)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/annotated(withoptional:)) extends the selection with [Associations].
```swift
// SELECT player.*, team.color
@@ -3367,14 +3377,14 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.annotated(withRequired: Player.team.select(colorColumn))
```
- [`distinct()`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/derivablerequest/distinct()) performs uniquing.
- [`distinct()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/derivablerequest/distinct()) performs uniquing.
```swift
// SELECT DISTINCT name FROM player
Player.select(nameColumn, as: String.self).distinct()
```
- [`filter(expression)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/filteredrequest/filter(_:)) applies conditions.
- [`filter(expression)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/filteredrequest/filter(_:)) applies conditions.
```swift
// SELECT * FROM player WHERE id IN (1, 2, 3)
@@ -3384,7 +3394,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.filter(nameColumn != nil && heightColumn > 1.75)
```
- [`filter(id:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/filter(id:)) and [`filter(ids:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/filter(ids:)) are type-safe methods available on [Identifiable Records]:
- [`filter(id:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/filter(id:)) and [`filter(ids:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/filter(ids:)) are type-safe methods available on [Identifiable Records]:
```swift
// SELECT * FROM player WHERE id = 1
@@ -3394,7 +3404,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Country.filter(ids: ["FR", "US"])
```
- [`filter(key:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/filter(key:)-1p9sq) and [`filter(keys:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/filter(keys:)-6ggt1) apply conditions on primary and unique keys:
- [`filter(key:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/filter(key:)-1p9sq) and [`filter(keys:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/filter(keys:)-6ggt1) apply conditions on primary and unique keys:
```swift
// SELECT * FROM player WHERE id = 1
@@ -3410,7 +3420,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.filter(key: ["email": "arthur@example.com"])
```
- `matching(pattern)` ([FTS3](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/matching(_:)-3s3zr), [FTS5](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/matching(_:)-7c1e8)) performs [full-text search](Documentation/FullTextSearch.md).
- `matching(pattern)` ([FTS3](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/matching(_:)-3s3zr), [FTS5](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/matching(_:)-7c1e8)) performs [full-text search](Documentation/FullTextSearch.md).
```swift
// SELECT * FROM document WHERE document MATCH 'sqlite database'
@@ -3420,7 +3430,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
When the pattern is nil, no row will match.
- [`group(expression, ...)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/aggregatingrequest/group(_:)-edak) groups rows.
- [`group(expression, ...)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/aggregatingrequest/group(_:)-edak) groups rows.
```swift
// SELECT name, MAX(score) FROM player GROUP BY name
@@ -3429,7 +3439,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
.group(nameColumn)
```
- [`having(expression)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/aggregatingrequest/having(_:)) applies conditions on grouped rows.
- [`having(expression)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/aggregatingrequest/having(_:)) applies conditions on grouped rows.
```swift
// SELECT team, MAX(score) FROM player GROUP BY team HAVING MIN(score) >= 1000
@@ -3439,7 +3449,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
.having(min(scoreColumn) >= 1000)
```
- [`having(aggregate)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/derivablerequest/having(_:)) applies conditions on grouped rows, according to an [association aggregate](Documentation/AssociationsBasics.md#association-aggregates).
- [`having(aggregate)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/derivablerequest/having(_:)) applies conditions on grouped rows, according to an [association aggregate](Documentation/AssociationsBasics.md#association-aggregates).
```swift
// SELECT team.*
@@ -3450,7 +3460,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Team.having(Team.players.count >= 5)
```
- [`order(ordering, ...)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/orderedrequest/order(_:)-63rzl) sorts.
- [`order(ordering, ...)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/orderedrequest/order(_:)-63rzl) sorts.
```swift
// SELECT * FROM player ORDER BY name
@@ -3474,7 +3484,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.order(scoreColumn).order(nameColumn)
```
- [`reversed()`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/orderedrequest/reversed()) reverses the eventual orderings.
- [`reversed()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/orderedrequest/reversed()) reverses the eventual orderings.
```swift
// SELECT * FROM player ORDER BY score ASC, name DESC
@@ -3488,7 +3498,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.all().reversed()
```
- [`limit(limit, offset: offset)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/queryinterfacerequest/limit(_:offset:)) limits and pages results.
- [`limit(limit, offset: offset)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/limit(_:offset:)) limits and pages results.
```swift
// SELECT * FROM player LIMIT 5
@@ -3498,7 +3508,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.limit(5, offset: 10)
```
- [`joining(required:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/joining(required:)), [`joining(optional:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/joining(optional:)), [`including(required:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/including(required:)), [`including(optional:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/including(optional:)), and [`including(all:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/joinablerequest/including(all:)) fetch and join records through [Associations].
- [`joining(required:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/joining(required:)), [`joining(optional:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/joining(optional:)), [`including(required:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/including(required:)), [`including(optional:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/including(optional:)), and [`including(all:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/joinablerequest/including(all:)) fetch and join records through [Associations].
```swift
// SELECT player.*, team.*
@@ -3507,7 +3517,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Player.including(required: Player.team)
```
- [`with(cte)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/derivablerequest/with(_:)) embeds a [common table expression]:
- [`with(cte)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/derivablerequest/with(_:)) embeds a [common table expression]:
```swift
// WITH ... SELECT * FROM player
@@ -3517,7 +3527,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
- Other requests that involve the primary key:
- [`selectPrimaryKey(as:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/queryinterfacerequest/selectprimarykey(as:)) selects the primary key.
- [`selectPrimaryKey(as:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/selectprimarykey(as:)) selects the primary key.
```swift
// SELECT id FROM player
@@ -3530,7 +3540,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Citizenship.selectPrimaryKey(as: Row.self) // QueryInterfaceRequest<Row>
```
- [`orderByPrimaryKey()`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/orderbyprimarykey()) sorts by primary key.
- [`orderByPrimaryKey()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/orderbyprimarykey()) sorts by primary key.
```swift
// SELECT * FROM player ORDER BY id
@@ -3543,7 +3553,7 @@ You can now build requests with the following methods: `all`, `none`, `select`,
Citizenship.orderByPrimaryKey()
```
- [`groupByPrimaryKey()`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tablerequest/groupbyprimarykey()) groups rows by primary key.
- [`groupByPrimaryKey()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tablerequest/groupbyprimarykey()) groups rows by primary key.
You can refine requests by chaining those methods:
@@ -3567,7 +3577,7 @@ Player // SELECT * FROM player
```
Raw SQL snippets are also accepted, with eventual [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments):
Raw SQL snippets are also accepted, with eventual [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -3604,21 +3614,41 @@ let request = Player.select(max(Column("score")), as: Int.self)
let maxScore = try request.fetchOne(db) // Int?
```
The default selection for a record type is controlled by the `databaseSelection` property:
The default selection for a record type is controlled by the `databaseSelection` property. For example:
```swift
// Select a limited set of columns
struct RestrictedPlayer : TableRecord {
static let databaseTableName = "player"
static var databaseSelection: [any SQLSelectable] { [Column("id"), Column("name")] }
}
struct ExtendedPlayer : TableRecord {
static let databaseTableName = "player"
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
static var databaseSelection: [any SQLSelectable] {
[Column("id"), Column("name")]
}
}
// SELECT id, name FROM player
let request = RestrictedPlayer.all()
```
```swift
// Select all but a few columns
struct Player : TableRecord {
static var databaseSelection: [any SQLSelectable] {
[.allColumns(excluding: ["generatedColumn"])]
}
}
// SELECT id, name FROM player
let request = RestrictedPlayer.all()
```
```swift
// Select all columns are more
struct ExtendedPlayer : TableRecord {
static let databaseTableName = "player"
static var databaseSelection: [any SQLSelectable] {
[.allColumns, .rowID]
}
}
// SELECT *, rowid FROM player
let request = ExtendedPlayer.all()
@@ -3634,7 +3664,7 @@ Feed [requests](#requests) with SQL expressions built from your Swift code:
### SQL Operators
📖 [`SQLSpecificExpressible`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sqlspecificexpressible)
📖 [`SQLSpecificExpressible`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/sqlspecificexpressible)
GRDB comes with a Swift version of many SQLite [built-in operators](https://sqlite.org/lang_expr.html#operators), listed below. But not all: see [Embedding SQL in Query Interface Requests] for a way to add support for missing SQL operators.
@@ -3904,7 +3934,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.
@@ -4481,7 +4511,7 @@ try Player.customRequest().fetchAll(db) // [Player]
}
```
- The [`asRequest(of:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/queryinterfacerequest/asrequest(of:)) method changes the type fetched by the request. It is useful, for example, when you use [Associations]:
- The [`asRequest(of:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/asrequest(of:)) method changes the type fetched by the request. It is useful, for example, when you use [Associations]:
```swift
struct BookInfo: FetchableRecord, Decodable {
@@ -4497,7 +4527,7 @@ try Player.customRequest().fetchAll(db) // [Player]
try request.fetchAll(db)
```
- The [`adapted(_:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/fetchrequest/adapted(_:)) method eases the consumption of complex rows with row adapters. See [`RowAdapter`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter) and [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:)) for a sample code that uses `adapted(_:)`.
- The [`adapted(_:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/fetchrequest/adapted(_:)) method eases the consumption of complex rows with row adapters. See [`RowAdapter`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter) and [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:)) for a sample code that uses `adapted(_:)`.
Encryption
@@ -4568,7 +4598,7 @@ See [SQLCipher 4.0.0 Release](https://www.zetetic.net/blog/2018/11/30/sqlcipher-
**You can change the passphrase** of an already encrypted database.
When you use a [database queue](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue), open the database with the old passphrase, and then apply the new passphrase:
When you use a [database queue](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue), open the database with the old passphrase, and then apply the new passphrase:
```swift
try dbQueue.write { db in
@@ -4576,7 +4606,7 @@ try dbQueue.write { db in
}
```
When you use a [database pool](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool), make sure that no concurrent read can happen by changing the passphrase within the `barrierWriteWithoutTransaction` block. You must also ensure all future reads open a new database connection by calling the `invalidateReadOnlyConnections` method:
When you use a [database pool](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool), make sure that no concurrent read can happen by changing the passphrase within the `barrierWriteWithoutTransaction` block. You must also ensure all future reads open a new database connection by calling the `invalidateReadOnlyConnections` method:
```swift
try dbPool.barrierWriteWithoutTransaction { db in
@@ -4603,7 +4633,7 @@ try dbPool.barrierWriteWithoutTransaction { db in
> }
> ```
> **Note**: The `DatabasePool.barrierWriteWithoutTransaction` method does not prevent [database snapshots](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshot) from accessing the database during the passphrase change, or after the new passphrase has been applied to the database. Those database accesses may throw errors. Applications should provide their own mechanism for invalidating open snapshots before the passphrase is changed.
> **Note**: The `DatabasePool.barrierWriteWithoutTransaction` method does not prevent [database snapshots](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesnapshot) from accessing the database during the passphrase change, or after the new passphrase has been applied to the database. Those database accesses may throw errors. Applications should provide their own mechanism for invalidating open snapshots before the passphrase is changed.
> **Note**: Instead of changing the passphrase "in place" as described here, you can also export the database in a new encrypted database that uses the new passphrase. See [Exporting a Database to an Encrypted Database](#exporting-a-database-to-an-encrypted-database).
@@ -4758,7 +4788,7 @@ try source.backup(to: destination)
The `backup` method blocks the current thread until the destination database contains the same contents as the source database.
When the source is a [database pool](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool), concurrent writes can happen during the backup. Those writes may, or may not, be reflected in the backup, but they won't trigger any error.
When the source is a [database pool](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool), concurrent writes can happen during the backup. Those writes may, or may not, be reflected in the backup, but they won't trigger any error.
`Database` has an analogous `backup` method.
@@ -4920,7 +4950,7 @@ Considering that a local database is not some JSON loaded from a remote server,
### DatabaseError
📖 [`DatabaseError`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseerror)
📖 [`DatabaseError`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseerror)
**DatabaseError** are thrown on SQLite errors:
@@ -4952,7 +4982,7 @@ do {
}
```
If you want to see statement arguments in the error description, [make statement arguments public](https://swiftpackageindex.com/groue/grdb.swift/configuration/publicstatementarguments).
If you want to see statement arguments in the error description, [make statement arguments public](https://swiftpackageindex.com/groue/GRDB.swift/configuration/publicstatementarguments).
**SQLite uses [results codes](https://www.sqlite.org/rescode.html) to distinguish between various errors**.
@@ -4994,7 +5024,7 @@ Each DatabaseError has two codes: an `extendedResultCode` (see [extended result
### RecordError
📖 [`RecordError`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recorderror)
📖 [`RecordError`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recorderror)
**RecordError** is thrown by the [PersistableRecord] protocol when the `update` method could not find any row to update:
@@ -5030,7 +5060,7 @@ They uncover programmer errors, false assumptions, and prevent misuses. Here are
let name: String = row["name"]
```
Solution: fix the contents of the database, use [NOT NULL constraints](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/columndefinition/notnull(onconflict:)), or load an optional:
Solution: fix the contents of the database, use [NOT NULL constraints](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/columndefinition/notnull(onconflict:)), or load an optional:
```swift
let name: String? = row["name"]
@@ -5275,7 +5305,7 @@ dbPool.releaseMemoryEventually()
**The iOS operating system likes applications that do not consume much memory.**
[Database queues] and [pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool) automatically free non-essential memory when the application receives a memory warning, and when the application enters background.
[Database queues] and [pools](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool) automatically free non-essential memory when the application receives a memory warning, and when the application enters background.
You can opt out of this automatic memory management:
@@ -5334,7 +5364,7 @@ FAQ
First choose a proper location for the database file. Document-based applications will let the user pick a location. Apps that use the database as a global storage will prefer the Application Support directory.
The sample code below creates or opens a database file inside its dedicated directory (a [recommended practice](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections)). On the first run, a new empty database file is created. On subsequent runs, the database file already exists, so it just opens a connection:
The sample code below creates or opens a database file inside its dedicated directory (a [recommended practice](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections)). On the first run, a new empty database file is created. On subsequent runs, the database file already exists, so it just opens a connection:
```swift
// HOW TO create an empty database, or open an existing database file
@@ -5376,7 +5406,7 @@ if let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite") {
Database connections are automatically closed when `DatabaseQueue` or `DatabasePool` instances are deinitialized.
If the correct execution of your program depends on precise database closing, perform an explicit call to [`close()`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasereader/close()). This method may fail and create zombie connections, so please check its detailed documentation.
If the correct execution of your program depends on precise database closing, perform an explicit call to [`close()`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasereader/close()). This method may fail and create zombie connections, so please check its detailed documentation.
## FAQ: SQL
@@ -5414,7 +5444,7 @@ try dbQueue.read { db in
}
```
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](https://swiftpackageindex.com/groue/grdb.swift/configuration/publicstatementarguments).
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](https://swiftpackageindex.com/groue/GRDB.swift/configuration/publicstatementarguments).
> **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output.
@@ -5451,7 +5481,7 @@ try dbQueue.read { db in
}
```
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](https://swiftpackageindex.com/groue/grdb.swift/configuration/publicstatementarguments).
If you want to see statement arguments such as `'arthur@example.com'` in the logged statements, [make statement arguments public](https://swiftpackageindex.com/groue/GRDB.swift/configuration/publicstatementarguments).
### What Are Experimental Features?
@@ -5756,7 +5786,7 @@ When this is the case, there are two possible explanations:
try db.execute(sql: "UPDATE player SET name = ?", arguments: [name])
```
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#double_quoted_string_literals_are_accepted), and [Configuration.acceptsDoubleQuotedStringLiterals](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/acceptsdoublequotedstringliterals).
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#double_quoted_string_literals_are_accepted), and [Configuration.acceptsDoubleQuotedStringLiterals](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/configuration/acceptsdoublequotedstringliterals).
@@ -5831,15 +5861,15 @@ This chapter was renamed to [Embedding SQL in Query Interface Requests].
#### Advanced DatabasePool
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
#### After Commit Hook
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)).
#### Asynchronous APIs
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
#### Changes Tracking
@@ -5847,7 +5877,7 @@ This chapter has been renamed [Record Comparison].
#### Concurrency
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
#### Custom Value Types
@@ -5863,27 +5893,27 @@ This chapter was replaced with [Persistence Callbacks].
#### Database Changes Observation
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation).
#### Database Configuration
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/configuration).
#### Database Queues
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue).
#### Database Pools
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool).
#### Database Snapshots
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
#### DatabaseWriter and DatabaseReader Protocols
This chapter was removed. See the references of [DatabaseReader](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasereader) and [DatabaseWriter](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasewriter).
This chapter was removed. See the references of [DatabaseReader](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasereader) and [DatabaseWriter](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasewriter).
#### Date and UUID Coding Strategies
@@ -5895,7 +5925,7 @@ This chapter has been superseded by the [Sharing a Database] guide.
#### Differences between Database Queues and Pools
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
#### Enabling FTS5 Support
@@ -5913,19 +5943,19 @@ This chapter has [moved](Documentation/FullTextSearch.md).
#### Guarantees and Rules
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
#### Joined Queries Support
This chapter was replaced with the documentation of [splittingRowAdapters(columnCounts:)](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:)).
This chapter was replaced with the documentation of [splittingRowAdapters(columnCounts:)](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:)).
#### List of Record Methods
See [Records and the Query Interface](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/queryinterface).
See [Records and the Query Interface](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterface).
#### Migrations
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations).
#### NSNumber and NSDecimalNumber
@@ -5941,15 +5971,15 @@ This error was renamed to [RecordError].
#### Prepared Statements
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statement).
#### Record Class
The [`Record`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/record) class is a legacy GRDB type. Since GRDB 7, it is not recommended to define record types by subclassing the `Record` class.
The [`Record`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/record) class is a legacy GRDB type. Since GRDB 7, it is not recommended to define record types by subclassing the `Record` class.
#### Row Adapters
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter).
#### RowConvertible Protocol
@@ -5961,23 +5991,23 @@ This protocol has been renamed [TableRecord] in GRDB 3.0.
#### Transactions and Savepoints
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactions).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactions).
#### Transaction Hook
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/afternexttransaction(oncommit:onrollback:)).
#### TransactionObserver Protocol
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver).
#### Unsafe Concurrency APIs
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency).
#### ValueObservation
This chapter has [moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
This chapter has [moved](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation).
#### ValueObservation and DatabaseRegionObservation
@@ -5996,7 +6026,7 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
[Fetching from Requests]: #fetching-from-requests
[Embedding SQL in Query Interface Requests]: #embedding-sql-in-query-interface-requests
[Full-Text Search]: Documentation/FullTextSearch.md
[Migrations]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
[Migrations]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations
[The userInfo Dictionary]: #the-userinfo-dictionary
[JSON Columns]: #json-columns
[FetchableRecord]: #fetchablerecord-protocol
@@ -6006,40 +6036,40 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
[Record Customization Options]: #record-customization-options
[Persistence Callbacks]: #persistence-callbacks
[persistence callbacks]: #persistence-callbacks
[Record Timestamps and Transaction Date]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps
[Record Timestamps and Transaction Date]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps
[TableRecord]: #tablerecord-protocol
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation
[ValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation
[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[DatabaseRegion]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregion
[DatabaseRegion]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregion
[SQL Interpolation]: Documentation/SQLInterpolation.md
[custom SQLite build]: Documentation/CustomSQLiteBuilds.md
[Combine]: https://developer.apple.com/documentation/combine
[Combine Support]: Documentation/Combine.md
[Concurrency]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
[Concurrency]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency
[Demo Applications]: Documentation/DemoApps
[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing
[Sharing a Database]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing
[FAQ]: #faq
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[SQLRequest]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sqlrequest
[Database Observation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation
[SQLRequest]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/sqlrequest
[SQL literal]: Documentation/SQLInterpolation.md#sql-literal
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
[Query Interface Organization]: Documentation/QueryInterfaceOrganization.md
[Database Configuration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration
[Database Configuration]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/configuration
[Persistence Methods]: #persistence-methods
[persistence methods]: #persistence-methods
[Persistence Methods and the `RETURNING` clause]: #persistence-methods-and-the-returning-clause
[RecordError]: #recorderror
[Transactions and Savepoints]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactions
[`DatabaseQueue`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue
[Database queues]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue
[`DatabasePool`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
[database pools]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool
[`DatabaseValueConvertible`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible
[`StatementArguments`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments
[Prepared Statements]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement
[prepared statements]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement
[`Statement`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement
[Transactions and Savepoints]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactions
[`DatabaseQueue`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue
[Database queues]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue
[`DatabasePool`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool
[database pools]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool
[`DatabaseValueConvertible`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasevalueconvertible
[`StatementArguments`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments
[Prepared Statements]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statement
[prepared statements]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statement
[`Statement`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statement
[Database Connections]: #database-connections
[Database connections]: #database-connections
[database connection]: #database-connections
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>7.0.0-beta.6</string>
<string>7.3.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -66,6 +66,16 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[0].scopes["team"]!, ["id":1, "name":"Reds"])
}
func testDefaultScopeIncludingRequiredRestrictedSelection() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.select(.allColumns(excluding: ["name"])).including(required: Player.defaultTeam)
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1])
XCTAssertEqual(Set(rows[0].scopes.names), ["team"])
XCTAssertEqual(rows[0].scopes["team"]!, ["id":1, "name":"Reds"])
}
func testDefaultScopeAnnotatedWithRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withRequired: Player.defaultTeam)
@@ -82,6 +92,14 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"])
}
func testDefaultScopeAnnotatedWithRequiredRestrictedSelection() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withRequired: Player.defaultTeam.select(.allColumns(excluding: ["name"])))
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1])
}
func testDefaultScopeIncludingOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.including(optional: Player.defaultTeam)
@@ -113,6 +131,15 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "teamName":nil])
}
func testDefaultScopeAnnotatedWithOptionalRestrictedSelection() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withOptional: Player.defaultTeam.select(.allColumns(excluding: ["name"])))
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1])
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "id":nil])
}
func testDefaultScopeJoiningRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.joining(required: Player.defaultTeam)
@@ -153,6 +180,16 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"])
}
func testCustomScopeIncludingRequiredRestrictedSelection() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.select(.allColumns(excluding: ["name"])).including(required: Player.customTeam)
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(rows[0].unscoped, ["id":1, "teamId":1])
XCTAssertEqual(Set(rows[0].scopes.names), ["customTeam"])
XCTAssertEqual(rows[0].scopes["customTeam"]!, ["id":1, "name":"Reds"])
}
func testCustomScopeAnnotatedWithRequired() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withRequired: Player.customTeam)
@@ -169,6 +206,14 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "teamName":"Reds"])
}
func testCustomScopeAnnotatedWithRequiredRestrictedSelection() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withRequired: Player.customTeam.select(.allColumns(excluding: ["name"])))
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1])
}
func testCustomScopeIncludingOptional() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.including(optional: Player.customTeam)
@@ -200,6 +245,15 @@ class AssociationBelongsToRowScopeTests: GRDBTestCase {
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "teamName":nil])
}
func testCustomScopeAnnotatedWithOptionalRestrictedSelection() throws {
let dbQueue = try makeDatabaseQueue()
let request = Player.annotated(withOptional: Player.customTeam.select(.allColumns(excluding: ["name"])))
let rows = try dbQueue.inDatabase { try Row.fetchAll($0, request) }
XCTAssertEqual(rows.count, 2)
XCTAssertEqual(rows[0], ["id":1, "teamId":1, "name":"Arthur", "id":1])
XCTAssertEqual(rows[1], ["id":2, "teamId":nil, "name":"Barbara", "id":nil])
}
func testCustomPluralScopeIncludingRequired() throws {
// Make sure explicit plural keys are preserved
let dbQueue = try makeDatabaseQueue()
@@ -5,7 +5,8 @@ import GRDB
private struct A : TableRecord {
static let databaseTableName = "a"
static let b = belongsTo(B.self)
static let restrictedB = belongsTo(RestrictedB.self)
static let restrictedB1 = belongsTo(RestrictedB1.self)
static let restrictedB2 = belongsTo(RestrictedB2.self)
static let extendedB = belongsTo(ExtendedB.self)
}
@@ -14,14 +15,19 @@ private struct B : TableRecord {
static let databaseTableName = "b"
}
private struct RestrictedB : TableRecord {
private struct RestrictedB1 : TableRecord {
static let databaseTableName = "b"
static var databaseSelection: [any SQLSelectable] { [Column("name")] }
}
private struct RestrictedB2 : TableRecord {
static let databaseTableName = "b"
static var databaseSelection: [any SQLSelectable] { [.allColumns(excluding: ["id"])] }
}
private struct ExtendedB : TableRecord {
static let databaseTableName = "b"
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
}
/// Test SQL generation
@@ -48,7 +54,12 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
FROM "a" \
JOIN "b" ON "b"."id" = "a"."bid"
""")
try assertEqualSQL(db, A.including(required: A.restrictedB), """
try assertEqualSQL(db, A.including(required: A.restrictedB1), """
SELECT "a".*, "b"."name" \
FROM "a" \
JOIN "b" ON "b"."id" = "a"."bid"
""")
try assertEqualSQL(db, A.including(required: A.restrictedB2), """
SELECT "a".*, "b"."name" \
FROM "a" \
JOIN "b" ON "b"."id" = "a"."bid"
@@ -76,8 +87,8 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
do {
let request = A.including(required: A.b
.select(
AllColumns(),
Column.rowID))
.allColumns,
.rowID))
try assertEqualSQL(db, request, """
SELECT "a".*, "b".*, "b"."rowid" \
FROM "a" \
@@ -89,9 +100,9 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
let request = A
.aliased(aAlias)
.including(required: A.b
.select(
Column("name"),
(Column("id") + aAlias[Column("id")]).forKey("foo")))
.select(
Column("name"),
(Column("id") + aAlias[Column("id")]).forKey("foo")))
try assertEqualSQL(db, request, """
SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \
FROM "a" \
@@ -76,6 +76,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "children".*, "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."rowid" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "rowid" = 1
@@ -139,6 +149,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "children".*, "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -229,6 +249,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "children".*, "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -292,6 +322,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "children".*, "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -380,6 +420,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "children".*, "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -443,6 +493,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "children".*, "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -506,6 +566,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "children".*, "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -599,6 +669,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "children".*, "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -662,6 +742,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "children".*, "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent1Id"
""")
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 1
@@ -725,7 +815,17 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "children".*, "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 2
""")
@@ -788,6 +888,16 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns)), """
SELECT "children".*, "parents".* \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "children".*, "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON "parents"."id" = "children"."parent2Id"
""")
try assertEqualSQL(db, Child(parent1ID: 1, parent2ID: 2).request(for: association), """
SELECT * FROM "parents" WHERE "id" = 2
@@ -882,6 +992,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
SELECT "children".*, "parents"."b", "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -991,6 +1106,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
SELECT "children".*, "parents"."b", "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1068,6 +1188,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
SELECT "children".*, "parents"."b", "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1176,6 +1301,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
SELECT "children".*, "parents"."b", "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1253,6 +1383,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
SELECT "children".*, "parents"."b", "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1330,6 +1465,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
SELECT "children".*, "parents"."b", "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parentA") AND ("parents"."b" = "children"."parentB")
""")
try assertEqualSQL(db, Child(parentA: 1, parentB: 2).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1447,6 +1587,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
SELECT "children".*, "parents"."b", "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
""")
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1524,6 +1669,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
SELECT "children".*, "parents"."b", "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent1A") AND ("parents"."b" = "children"."parent1B")
""")
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 1) AND ("b" = 2)
@@ -1601,6 +1751,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
SELECT "children".*, "parents"."b", "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
""")
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 3) AND ("b" = 4)
@@ -1678,6 +1833,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["a"]))), """
SELECT "children".*, "parents"."b", "parents"."name" \
FROM "children" \
LEFT JOIN "parents" ON ("parents"."a" = "children"."parent2A") AND ("parents"."b" = "children"."parent2B")
""")
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: 3, parent2B: 4).request(for: association), """
SELECT * FROM "parents" WHERE ("a" = 3) AND ("b" = 4)
@@ -1699,7 +1859,7 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: 4).request(for: association).aliased(TableAlias(name: "custom")), """
SELECT "custom".* FROM "parents" "custom" WHERE 0
""")
try assertEqualSQL(db, Child(parent1A: 1, parent1B: 2, parent2A: nil, parent2B: nil).request(for: association), """
SELECT * FROM "parents" WHERE 0
""")
@@ -1896,6 +2056,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "CHILDREN".*, "PARENTS"."name" \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "PARENTS" WHERE "id" = 1
@@ -1959,6 +2124,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "CHILDREN".*, "PARENTS"."name" \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."id" = "CHILDREN"."parentId"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "PARENTS" WHERE "id" = 1
@@ -2022,6 +2192,11 @@ class AssociationBelongsToSQLTests: GRDBTestCase {
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
""")
try assertEqualSQL(db, Child.annotated(withOptional: association.select(.allColumns(excluding: ["id"]))), """
SELECT "CHILDREN".*, "PARENTS"."name" \
FROM "CHILDREN" \
LEFT JOIN "PARENTS" ON "PARENTS"."ID" = "CHILDREN"."PARENTID"
""")
try assertEqualSQL(db, Child(parentID: 1).request(for: association), """
SELECT * FROM "PARENTS" WHERE "ID" = 1
@@ -5,7 +5,8 @@ import GRDB
private struct A : TableRecord {
static let databaseTableName = "a"
static let b = hasOne(B.self)
static let restrictedB = hasOne(RestrictedB.self)
static let restrictedB1 = hasOne(RestrictedB1.self)
static let restrictedB2 = hasOne(RestrictedB2.self)
static let extendedB = hasOne(ExtendedB.self)
}
@@ -14,14 +15,19 @@ private struct B : TableRecord {
static let databaseTableName = "b"
}
private struct RestrictedB : TableRecord {
private struct RestrictedB1 : TableRecord {
static let databaseTableName = "b"
static var databaseSelection: [any SQLSelectable] { [Column("name")] }
}
private struct RestrictedB2 : TableRecord {
static let databaseTableName = "b"
static var databaseSelection: [any SQLSelectable] { [.allColumns(excluding: ["id"])] }
}
private struct ExtendedB : TableRecord {
static let databaseTableName = "b"
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
}
/// Test SQL generation
@@ -48,11 +54,16 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
FROM "a" \
JOIN "b" ON "b"."aid" = "a"."id"
""")
try assertEqualSQL(db, A.including(required: A.restrictedB), """
try assertEqualSQL(db, A.including(required: A.restrictedB1), """
SELECT "a".*, "b"."name" \
FROM "a" \
JOIN "b" ON "b"."aid" = "a"."id"
""")
try assertEqualSQL(db, A.including(required: A.restrictedB2), """
SELECT "a".*, "b"."aid", "b"."name" \
FROM "a" \
JOIN "b" ON "b"."aid" = "a"."id"
""")
try assertEqualSQL(db, A.including(required: A.extendedB), """
SELECT "a".*, "b".*, "b"."rowid" \
FROM "a" \
@@ -76,8 +87,8 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
do {
let request = A.including(required: A.b
.select(
AllColumns(),
Column.rowID))
.allColumns,
.rowID))
try assertEqualSQL(db, request, """
SELECT "a".*, "b".*, "b"."rowid" \
FROM "a" \
@@ -89,9 +100,9 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
let request = A
.aliased(aAlias)
.including(required: A.b
.select(
Column("name"),
(Column("id") + aAlias[Column("id")]).forKey("foo")))
.select(
Column("name"),
(Column("id") + aAlias[Column("id")]).forKey("foo")))
try assertEqualSQL(db, request, """
SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \
FROM "a" \
@@ -4,27 +4,34 @@ import GRDB
private struct A: TableRecord {
static let b = belongsTo(B.self)
static let c = hasOne(C.self, through: b, using: B.c)
static let restrictedC = hasOne(RestrictedC.self, through: b, using: B.restrictedC)
static let restrictedC1 = hasOne(RestrictedC1.self, through: b, using: B.restrictedC1)
static let restrictedC2 = hasOne(RestrictedC2.self, through: b, using: B.restrictedC2)
static let extendedC = hasOne(ExtendedC.self, through: b, using: B.extendedC)
}
private struct B: TableRecord {
static let c = belongsTo(C.self)
static let restrictedC = belongsTo(RestrictedC.self)
static let restrictedC1 = belongsTo(RestrictedC1.self)
static let restrictedC2 = belongsTo(RestrictedC2.self)
static let extendedC = belongsTo(ExtendedC.self)
}
private struct C: TableRecord {
}
private struct RestrictedC : TableRecord {
private struct RestrictedC1 : TableRecord {
static let databaseTableName = "c"
static var databaseSelection: [any SQLSelectable] { [Column("name")] }
}
private struct RestrictedC2 : TableRecord {
static let databaseTableName = "c"
static var databaseSelection: [any SQLSelectable] { [.allColumns(excluding: ["id"])] }
}
private struct ExtendedC : TableRecord {
static let databaseTableName = "c"
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
}
/// Test SQL generation
@@ -56,7 +63,13 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase {
JOIN "b" ON "b"."id" = "a"."bId" \
JOIN "c" ON "c"."id" = "b"."cId"
""")
try assertEqualSQL(db, A.including(required: A.restrictedC), """
try assertEqualSQL(db, A.including(required: A.restrictedC1), """
SELECT "a".*, "c"."name" \
FROM "a" \
JOIN "b" ON "b"."id" = "a"."bId" \
JOIN "c" ON "c"."id" = "b"."cId"
""")
try assertEqualSQL(db, A.including(required: A.restrictedC2), """
SELECT "a".*, "c"."name" \
FROM "a" \
JOIN "b" ON "b"."id" = "a"."bId" \
@@ -87,8 +100,8 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase {
do {
let request = A.including(required: A.c
.select(
AllColumns(),
Column.rowID))
.allColumns,
.rowID))
try assertEqualSQL(db, request, """
SELECT "a".*, "c".*, "c"."rowid" \
FROM "a" \
@@ -157,6 +157,110 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasMany_limit() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(B.self)
.orderByPrimaryKey()
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
WITH "grdb_bs_limited" AS (\
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
FROM "b" \
WHERE "colb2" IN (1, 2, 3)\
) \
SELECT * FROM "grdb_bs_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "colb1"
"""])
}
// Request with avoided prefetch
do {
let request = A
.none()
.including(all: A
.hasMany(B.self)
.orderByPrimaryKey()
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM \"a\" WHERE 0 ORDER BY \"cola1\"
"""])
}
// Request with filters
do {
let request = A
.filter(Column("cola1") != 3)
.including(all: A
.hasMany(B.self)
.filter(Column("colb1") == 4)
.orderByPrimaryKey()
.forKey("bs1")
.limit(3))
.including(all: A
.hasMany(B.self)
.filter(Column("colb1") != 4)
.orderByPrimaryKey()
.forKey("bs2")
.limit(5, offset: 2))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" \
WHERE "cola1" <> 3 \
ORDER BY "cola1"
""",
"""
WITH "grdb_bs1_limited" AS (\
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
FROM "b" \
WHERE ("colb1" = 4) AND ("colb2" IN (1, 2))\
) \
SELECT * FROM "grdb_bs1_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "colb1"
""",
"""
WITH "grdb_bs2_limited" AS (\
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
FROM "b" \
WHERE ("colb1" <> 4) AND ("colb2" IN (1, 2))\
) \
SELECT * FROM "grdb_bs2_limited" \
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8) \
ORDER BY "colb1"
"""])
}
}
}
func testIncludingAllHasManyScalar() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
@@ -188,6 +292,42 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasManyScalar_limit() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(B.self)
.select(Column("colb2"))
.distinct()
.order(Column("colb2"))
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
WITH "grdb_bs_limited" AS (\
SELECT DISTINCT "colb2", "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb2") AS "rowNumber" \
FROM "b" \
WHERE "colb2" IN (1, 2, 3)\
) \
SELECT * FROM "grdb_bs_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "colb2"
"""])
}
}
}
func testIncludingAllHasManyWithCompoundForeignKey() throws {
// We can use the CTE technique
let dbQueue = try makeDatabaseQueue()
@@ -304,6 +444,141 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasManyWithCompoundForeignKey_limit() throws {
// We can use the CTE technique
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "parent") { t in
t.column("parentA", .text)
t.column("parentB", .text)
t.primaryKey(["parentA", "parentB"])
}
try db.create(table: "child") { t in
t.column("pA", .text)
t.column("pB", .text)
t.column("name", .text)
t.foreignKey(["pA", "pB"], references: "parent")
}
try db.execute(sql: """
INSERT INTO parent (parentA, parentB) VALUES ('foo', 'bar');
INSERT INTO parent (parentA, parentB) VALUES ('baz', 'qux');
INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar1');
INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar2');
INSERT INTO child (pA, pB, name) VALUES ('baz', 'qux', 'bazqux1');
""")
struct Parent: TableRecord { }
struct Child: TableRecord { }
// Plain request
do {
let request = Parent
.including(all: Parent
.hasMany(Child.self)
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" ORDER BY "parentA", "parentB"
""",
"""
WITH "grdb_children_limited" AS (\
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
FROM "child" \
WHERE ("pA", "pB") IN "grdb_base"\
), \
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \
SELECT * \
FROM "grdb_children_limited" \
WHERE "rowNumber" <= 3
"""])
}
// Request with avoided prefetch
do {
let request = Parent
.none()
.including(all: Parent
.hasMany(Child.self)
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" WHERE 0 ORDER BY "parentA", "parentB"
"""])
}
// Request with filters
do {
let request = Parent
.including(all: Parent
.hasMany(Child.self)
.filter(Column("name") == "foo")
.limit(3))
.filter(Column("parentA") == "foo")
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" WHERE "parentA" = 'foo' ORDER BY "parentA", "parentB"
""",
"""
WITH "grdb_children_limited" AS (\
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
FROM "child" \
WHERE ("name" = 'foo') AND (("pA", "pB") IN "grdb_base")\
), \
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "parentA" = 'foo') \
SELECT * \
FROM "grdb_children_limited" \
WHERE "rowNumber" <= 3
"""])
}
// Limited ordered request (preserve both ordering and limit in the CTE)
do {
let request = Parent
.including(all: Parent
.hasMany(Child.self)
.limit(5, offset: 2))
.orderByPrimaryKey()
.limit(1)
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1
""",
"""
WITH "grdb_children_limited" AS (\
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
FROM "child" WHERE ("pA", "pB") IN "grdb_base"\
), \
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1) \
SELECT * FROM "grdb_children_limited" \
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8)
"""])
}
}
}
func testIncludingAllHasManyIncludingAllHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
@@ -455,6 +730,218 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasManyIncludingAllHasMany_limit() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(C.self)
.including(all: C
.hasMany(D.self)
.orderByPrimaryKey()
.limit(5, offset: 2))
.orderByPrimaryKey()
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
WITH "grdb_cs_limited" AS (\
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" ORDER BY "colc1") AS "rowNumber" \
FROM "c" \
WHERE "colc2" IN (1, 2, 3)\
) \
SELECT * \
FROM "grdb_cs_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "colc1"
""",
"""
WITH "grdb_ds_limited" AS (\
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" ORDER BY "cold1") AS "rowNumber" \
FROM "d" \
WHERE "cold2" IN (7, 8, 9)\
) \
SELECT * \
FROM "grdb_ds_limited" \
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8) \
ORDER BY "cold1"
"""])
}
// Request with avoided second-level prefetch
do {
let request = A
.including(all: A
.hasMany(C.self)
.none()
.including(all: C
.hasMany(D.self)
.orderByPrimaryKey()
.limit(5, offset: 2))
.orderByPrimaryKey()
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
WITH "grdb_cs_limited" AS (\
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" ORDER BY "colc1") AS "rowNumber" \
FROM "c" \
WHERE 0 AND ("colc2" IN (1, 2, 3))\
) \
SELECT * \
FROM "grdb_cs_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "colc1"
"""])
}
// Request with filters
do {
let request = A
.filter(Column("cola1") != 3)
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") > 7)
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.limit(1)
.forKey("ds1"))
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.limit(2)
.forKey("ds2"))
.orderByPrimaryKey()
.limit(3)
.forKey("cs1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") < 9)
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.limit(3)
.forKey("ds1"))
.including(all: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.limit(4)
.forKey("ds2"))
.orderByPrimaryKey()
.limit(5)
.forKey("cs2"))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * \
FROM "a" \
WHERE "cola1" <> 3 \
ORDER BY "cola1"
""",
"""
WITH "grdb_cs1_limited" AS (\
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" \
ORDER BY "colc1") AS "rowNumber" \
FROM "c" \
WHERE ("colc1" > 7) AND ("colc2" IN (1, 2))\
) \
SELECT * \
FROM "grdb_cs1_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "colc1"
""",
"""
WITH "grdb_ds1_limited" AS (\
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
ORDER BY "cold1") AS "rowNumber" \
FROM "d" \
WHERE ("cold1" = 11) AND ("cold2" IN (8, 9))\
) \
SELECT * \
FROM "grdb_ds1_limited" \
WHERE "rowNumber" <= 1 \
ORDER BY "cold1"
""",
"""
WITH "grdb_ds2_limited" AS (\
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
ORDER BY "cold1") AS "rowNumber" \
FROM "d" \
WHERE ("cold1" <> 11) AND ("cold2" IN (8, 9))\
) \
SELECT * \
FROM "grdb_ds2_limited" \
WHERE "rowNumber" <= 2 \
ORDER BY "cold1"
""",
"""
WITH "grdb_cs2_limited" AS (\
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" \
ORDER BY "colc1") AS "rowNumber" \
FROM "c" \
WHERE ("colc1" < 9) AND ("colc2" IN (1, 2))\
) \
SELECT * \
FROM "grdb_cs2_limited" \
WHERE "rowNumber" <= 5 \
ORDER BY "colc1"
""",
"""
WITH "grdb_ds1_limited" AS (\
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
ORDER BY "cold1") AS "rowNumber" \
FROM "d" \
WHERE ("cold1" = 11) AND ("cold2" IN (7, 8))\
) \
SELECT * \
FROM "grdb_ds1_limited" \
WHERE "rowNumber" <= 3 \
ORDER BY "cold1"
""",
"""
WITH "grdb_ds2_limited" AS (\
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
ORDER BY "cold1") AS "rowNumber" \
FROM "d" \
WHERE ("cold1" <> 11) AND ("cold2" IN (7, 8))\
) \
SELECT * \
FROM "grdb_ds2_limited" \
WHERE "rowNumber" <= 4 \
ORDER BY "cold1"
""",
])}
}
}
func testIncludingAllHasManyIncludingAllHasManyWithCompoundForeignKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
@@ -730,6 +1217,138 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasManyIncludingRequiredOrOptionalHasMany_limit() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
// Plain request
do {
let request = A
.including(all: A
.hasMany(C.self)
.including(required: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey()
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
#warning("TODO: ordering on D is lost")
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d".* \
FROM "c" \
JOIN "d" ON "d"."cold2" = "c"."colc1" \
WHERE "c"."colc2" IN (1, 2, 3) \
ORDER BY "c"."colc1", "d"."cold1"
"""])
}
// Request with avoided prefetch
do {
let request = A
.including(all: A
.hasMany(C.self)
.none()
.including(required: C
.hasMany(D.self)
.orderByPrimaryKey())
.orderByPrimaryKey()
.limit(3))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d".* \
FROM "c" \
JOIN "d" ON "d"."cold2" = "c"."colc1" \
WHERE 0 AND ("c"."colc2" IN (1, 2, 3)) \
ORDER BY "c"."colc1", "d"."cold1"
"""])
}
// Request with filters
do {
let request = A
.filter(Column("cola1") != 3)
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") > 7)
.including(optional: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.orderByPrimaryKey()
.limit(3)
.forKey("cs1"))
.including(all: A
.hasMany(C.self)
.filter(Column("colc1") < 9)
.including(optional: C
.hasMany(D.self)
.filter(Column("cold1") == 11)
.orderByPrimaryKey()
.forKey("d1"))
.including(required: C
.hasMany(D.self)
.filter(Column("cold1") != 11)
.orderByPrimaryKey()
.forKey("d2"))
.orderByPrimaryKey()
.limit(3)
.forKey("cs2"))
.orderByPrimaryKey()
clearSQLQueries()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * \
FROM "a" \
WHERE "cola1" <> 3 \
ORDER BY "cola1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
FROM "c" \
LEFT JOIN "d" "d1" ON ("d1"."cold2" = "c"."colc1") AND ("d1"."cold1" = 11) \
JOIN "d" "d2" ON ("d2"."cold2" = "c"."colc1") AND ("d2"."cold1" <> 11) \
WHERE ("c"."colc1" > 7) AND ("c"."colc2" IN (1, 2)) \
ORDER BY "c"."colc1", "d1"."cold1", "d2"."cold1"
""",
"""
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
FROM "c" \
LEFT JOIN "d" "d1" ON ("d1"."cold2" = "c"."colc1") AND ("d1"."cold1" = 11) \
JOIN "d" "d2" ON ("d2"."cold2" = "c"."colc1") AND ("d2"."cold1" <> 11) \
WHERE ("c"."colc1" < 9) AND ("c"."colc2" IN (1, 2)) \
ORDER BY "c"."colc1", "d1"."cold1", "d2"."cold1"
"""])
}
}
}
func testIncludingAllHasManyThroughHasManyUsingHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
@@ -1,12 +1,3 @@
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import XCTest
import GRDB
@@ -139,7 +130,7 @@ class DatabaseConfigurationTests: GRDBTestCase {
let foo = try dbQueue.inDatabase { db in
try String.fetchOne(db, sql: "SELECT \"foo\" FROM player")
}
if sqlite3_libversion_number() >= 3029000 {
if Database.sqliteLibVersionNumber >= 3029000 {
XCTFail("Expected error")
} else {
XCTAssertEqual(foo, "foo")
@@ -154,7 +145,7 @@ class DatabaseConfigurationTests: GRDBTestCase {
try dbQueue.inDatabase { db in
try db.execute(sql: "CREATE INDEX i ON player(\"foo\")")
}
if sqlite3_libversion_number() >= 3029000 {
if Database.sqliteLibVersionNumber >= 3029000 {
XCTFail("Expected error")
}
} catch let error as DatabaseError {
+2 -11
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
import XCTest
import GRDB
@@ -1282,7 +1273,7 @@ final class DatabaseDumpTests: GRDBTestCase {
}
func test_dumpSchema_ignores_shadow_tables() throws {
guard sqlite3_libversion_number() >= 3037000 else {
guard Database.sqliteLibVersionNumber >= 3037000 else {
throw XCTSkip("Can't detect shadow tables")
}
@@ -1486,7 +1477,7 @@ final class DatabaseDumpTests: GRDBTestCase {
}
func test_dumpContent_ignores_shadow_tables() throws {
guard sqlite3_libversion_number() >= 3037000 else {
guard Database.sqliteLibVersionNumber >= 3037000 else {
throw XCTSkip("Can't detect shadow tables")
}
+1 -10
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
import XCTest
@testable import GRDB
@@ -565,7 +556,7 @@ class DatabaseRegionTests : GRDBTestCase {
//
// See also testRowIdNameInUpdateStatement
guard sqlite3_libversion_number() < 3019003 else {
guard Database.sqliteLibVersionNumber < 3019003 else {
// This test fails on SQLite 3.19.3 (iOS 11.2) and SQLite 3.21.0 (custom build),
// but succeeds on SQLite 3.16.0 (iOS 10.3.1).
// TODO: evaluate the consequences
+53 -11
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
import XCTest
import GRDB
@@ -208,7 +199,7 @@ class DatabaseWriterTests : GRDBTestCase {
throw XCTSkip("VACUUM INTO is not available")
}
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3027000 else {
guard Database.sqliteLibVersionNumber >= 3027000 else {
throw XCTSkip("VACUUM INTO is not available")
}
@@ -373,7 +364,7 @@ class DatabaseWriterTests : GRDBTestCase {
@available(iOS 14, macOS 10.16, tvOS 14, *) // async + vacuum into
func testAsyncAwait_vacuumInto() async throws {
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3027000 else {
guard Database.sqliteLibVersionNumber >= 3027000 else {
throw XCTSkip("VACUUM INTO is not available")
}
@@ -424,6 +415,57 @@ class DatabaseWriterTests : GRDBTestCase {
// MARK: - Task Cancellation
// Regression test for <https://github.com/groue/GRDB.swift/issues/1715>.
func test_write_is_possible_after_read_cancelled_after_database_access() async throws {
// When a read access is cancelled, DatabaseQueue needs to execute
// `PRAGMA query_only=0` in order to restore the read/write access.
//
// Here we test that this pragma can run from a cancelled read.
//
// Small difficulty: some SQLite versions (seen with 3.43.2) execute
// the `query_only` pragma at compile time, not only at execution
// time (yeah, that's an SQLite bug). The problem of this bug is
// that even if the `PRAGMA query_only=0` is not executed due to
// Task cancellation, its side effect is still executed when it is
// compiled, unintentionally. A cancelled `PRAGMA query_only=0`
// still works!
//
// To avoid this SQLite bug from messing with our test, we perform
// two reads: one that compiles and cache `PRAGMA query_only`
// statements, and a second read that we cancel. This time the
// `PRAGMA query_only=0` triggers its side effect if and only if it
// is actually executed (the behavior we are testing).
func test(_ dbWriter: some DatabaseWriter) async throws {
let semaphore = AsyncSemaphore(value: 0)
let cancelledTaskMutex = Mutex<Task<Void, any Error>?>(nil)
let task = Task {
await semaphore.wait()
// First read, not cancelled, so that all `query_only`
// pragma statements are compiled (see above).
try await dbWriter.read { db in }
// Second read, cancelled.
try await dbWriter.read { db in
try XCTUnwrap(cancelledTaskMutex.load()).cancel()
}
}
cancelledTaskMutex.store(task)
semaphore.signal()
// Wait until reads are completed
try? await task.value
// Write access is restored after read cancellation (no error is thrown)
try await dbWriter.write { db in
try db.execute(sql: "CREATE TABLE test(a)")
}
}
try await test(makeDatabaseQueue())
try await test(makeDatabasePool())
try await test(AnyDatabaseWriter(makeDatabaseQueue()))
}
func test_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws {
func test(_ dbWriter: some DatabaseWriter) async throws {
let semaphore = AsyncSemaphore(value: 0)
+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(), Column.rowID] }
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
func encode(to container: inout PersistenceContainer) {
container[.rowID] = id
+23 -1
View File
@@ -13,7 +13,29 @@ class FTS3TableBuilderTests: GRDBTestCase {
}
}
func testOptions() throws {
func test_option_ifNotExists() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", options: .ifNotExists, using: FTS3())
assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"documents\" USING fts3")
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
}
}
func test_option_temporary() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", options: .temporary, using: FTS3())
assertDidExecute(sql: "CREATE VIRTUAL TABLE temp.\"documents\" USING fts3")
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
}
}
func testLegacyOptions() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", ifNotExists: true, using: FTS3())
+1 -1
View File
@@ -19,7 +19,7 @@ extension Book : FetchableRecord {
extension Book : MutablePersistableRecord {
static let databaseTableName = "books"
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
func encode(to container: inout PersistenceContainer) {
container[.rowID] = id
+27 -5
View File
@@ -13,7 +13,29 @@ class FTS4TableBuilderTests: GRDBTestCase {
}
}
func testOptions() throws {
func test_option_ifNotExists() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", options: .ifNotExists, using: FTS4())
assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"documents\" USING fts4")
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
}
}
func test_option_temporary() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", options: .temporary, using: FTS4())
assertDidExecute(sql: "CREATE VIRTUAL TABLE temp.\"documents\" USING fts4")
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
}
}
func testLegacyOptions() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", ifNotExists: true, using: FTS4())
@@ -193,8 +215,8 @@ class FTS4TableBuilderTests: GRDBTestCase {
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 1)
}
}
func testFTS4SynchronizationIfNotExists() throws {
func testFTS4Synchronization_with_ifNotExists_option() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.writeWithoutTransaction { db in
try db.create(table: "documents") { t in
@@ -202,7 +224,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
t.column("content", .text)
}
assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)")
try db.create(virtualTable: "ft_documents", ifNotExists: true, using: FTS4()) { t in
try db.create(virtualTable: "ft_documents", options: .ifNotExists, using: FTS4()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
@@ -210,7 +232,7 @@ class FTS4TableBuilderTests: GRDBTestCase {
assertDidExecute(sql: "CREATE TRIGGER IF NOT EXISTS \"__ft_documents_bu\" BEFORE UPDATE ON \"documents\" BEGIN\n DELETE FROM \"ft_documents\" WHERE docid=old.\"id\";\nEND")
}
}
func testFTS4SynchronizationCleanup() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
+1 -1
View File
@@ -20,7 +20,7 @@ extension Book : FetchableRecord {
extension Book : MutablePersistableRecord {
static let databaseTableName = "books"
static var databaseSelection: [any SQLSelectable] { [AllColumns(), Column.rowID] }
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
func encode(to container: inout PersistenceContainer) {
container[.rowID] = id
+31 -5
View File
@@ -16,7 +16,33 @@ class FTS5TableBuilderTests: GRDBTestCase {
}
}
func testOptions() throws {
func test_option_ifNotExists() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", options: .ifNotExists, using: FTS5()) { t in
t.column("content")
}
assertDidExecute(sql: "CREATE VIRTUAL TABLE IF NOT EXISTS \"documents\" USING fts5(content)")
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
}
}
func test_option_temporary() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", options: .temporary, using: FTS5()) { t in
t.column("content")
}
assertDidExecute(sql: "CREATE VIRTUAL TABLE temp.\"documents\" USING fts5(content)")
try db.execute(sql: "INSERT INTO documents VALUES (?)", arguments: ["abc"])
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM documents WHERE documents MATCH ?", arguments: ["abc"])!, 1)
}
}
func testLegacyOptions() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.create(virtualTable: "documents", ifNotExists: true, using: FTS5()) { t in
@@ -251,8 +277,8 @@ class FTS5TableBuilderTests: GRDBTestCase {
XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM ft_documents WHERE ft_documents MATCH ?", arguments: ["bar"])!, 1)
}
}
func testFTS5SynchronizationIfNotExists() throws {
func testFTS5Synchronization_with_ifNotExists_option() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.writeWithoutTransaction { db in
try db.create(table: "documents") { t in
@@ -260,7 +286,7 @@ class FTS5TableBuilderTests: GRDBTestCase {
t.column("content", .text)
}
assertDidExecute(sql: "CREATE TABLE \"documents\" (\"id\" INTEGER PRIMARY KEY, \"content\" TEXT)")
try db.create(virtualTable: "ft_documents", ifNotExists: true, using: FTS5()) { t in
try db.create(virtualTable: "ft_documents", options: .ifNotExists, using: FTS5()) { t in
t.synchronize(withTable: "documents")
t.column("content")
}
@@ -338,7 +364,7 @@ class FTS5TableBuilderTests: GRDBTestCase {
// Regression test for <https://github.com/groue/GRDB.swift/issues/1390>
func testIssue1390() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("UPSERT is not available")
}
#else
+2 -11
View File
@@ -1,13 +1,4 @@
#if SQLITE_ENABLE_FTS5
// Import C SQLite functions
#if SWIFT_PACKAGE
import GRDBSQLite
#elseif GRDBCIPHER
import SQLCipher
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
import XCTest
import GRDB
@@ -212,7 +203,7 @@ class FTS5TokenizerTests: GRDBTestCase {
// They were introduced on 2018-07-13 in https://sqlite.org/src/info/80d2b9e635e3100f
// Next version is 3.25.0.
// So we assume support for categories was introduced in SQLite 3.25.0.
guard sqlite3_libversion_number() >= 3025000 else {
guard Database.sqliteLibVersionNumber >= 3025000 else {
throw XCTSkip("FTS5 unicode61 tokenizer categories are not available")
}
@@ -372,7 +363,7 @@ class FTS5TokenizerTests: GRDBTestCase {
// They were introduced on 2018-07-13 in https://sqlite.org/src/info/80d2b9e635e3100f
// Next version is 3.25.0.
// So we assume support for categories was introduced in SQLite 3.25.0.
guard sqlite3_libversion_number() >= 3025000 else {
guard Database.sqliteLibVersionNumber >= 3025000 else {
throw XCTSkip("FTS5 unicode61 tokenizer categories are not available")
}
+3 -1
View File
@@ -269,5 +269,7 @@ struct AnyValueReducerFetcher<Fetched>: _ValueReducerFetcher {
}
}
// Assume this is correct :-/
#if compiler(<6.1)
// XCTestExpectation is Sendable starting Xcode 16.3 beta.
extension XCTestExpectation: @unchecked Sendable { }
#endif
+19 -1
View File
@@ -124,7 +124,25 @@
"hero" : "heroes",
"foot" : "feet",
"matrix" : "matrices",
"watch" : "watches"
"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"
},
"Irregularities": {
+3 -3
View File
@@ -5,7 +5,7 @@ final class JSONColumnTests: GRDBTestCase {
func test_JSONColumn_derived_from_CodingKey() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3038000 else {
guard Database.sqliteLibVersionNumber >= 3038000 else {
throw XCTSkip("JSON support is not available")
}
#else
@@ -47,7 +47,7 @@ final class JSONColumnTests: GRDBTestCase {
func test_JSON_EXTRACT() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3038000 else {
guard Database.sqliteLibVersionNumber >= 3038000 else {
throw XCTSkip("JSON_EXTRACT is not available")
}
#else
@@ -79,7 +79,7 @@ final class JSONColumnTests: GRDBTestCase {
func test_extraction_operators() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3038000 else {
guard Database.sqliteLibVersionNumber >= 3038000 else {
throw XCTSkip("JSON operators are not available")
}
#else
File diff suppressed because it is too large. Load diff
@@ -1249,7 +1249,7 @@ class MutablePersistableRecordTests: GRDBTestCase {
extension MutablePersistableRecordTests {
func test_insertAndFetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1270,7 +1270,7 @@ extension MutablePersistableRecordTests {
func test_insertAndFetch_as() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1320,7 +1320,7 @@ extension MutablePersistableRecordTests {
func test_insertAndFetch_selection_fetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1411,7 +1411,7 @@ extension MutablePersistableRecordTests {
extension MutablePersistableRecordTests {
func test_saveAndFetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1432,7 +1432,7 @@ extension MutablePersistableRecordTests {
func test_saveAndFetch_as() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1558,7 +1558,7 @@ extension MutablePersistableRecordTests {
func test_saveAndFetch_selection_fetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1688,7 +1688,7 @@ extension MutablePersistableRecordTests {
extension MutablePersistableRecordTests {
func test_updateAndFetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1739,7 +1739,7 @@ extension MutablePersistableRecordTests {
func test_updateAndFetch_as() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1789,7 +1789,7 @@ extension MutablePersistableRecordTests {
func test_updateAndFetch_selection_fetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -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])
@@ -1843,7 +1843,7 @@ extension MutablePersistableRecordTests {
func test_updateAndFetch_columns_selection_fetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -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])
@@ -1897,7 +1897,7 @@ extension MutablePersistableRecordTests {
func test_updateChangesAndFetch_modify() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1958,7 +1958,7 @@ extension MutablePersistableRecordTests {
func test_updateChangesAndFetch_as_modify() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -2018,7 +2018,7 @@ extension MutablePersistableRecordTests {
func test_updateChangesAndFetch_selection_fetch_modify() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -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])
@@ -2088,7 +2088,7 @@ extension MutablePersistableRecordTests {
extension MutablePersistableRecordTests {
func test_upsert() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("UPSERT is not available")
}
#else
@@ -2237,7 +2237,7 @@ extension MutablePersistableRecordTests {
func test_upsertAndFetch_do_update_set_where() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("UPSERT is not available")
}
#else
@@ -2393,7 +2393,7 @@ extension MutablePersistableRecordTests {
func test_upsertAndFetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("UPSERT is not available")
}
#else
@@ -2496,7 +2496,7 @@ extension MutablePersistableRecordTests {
func test_upsertAndFetch_as() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("UPSERT is not available")
}
#else
+358 -10
View File
@@ -1328,7 +1328,7 @@ extension PersistableRecordTests {
extension PersistableRecordTests {
func test_insertAndFetch_as() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1375,9 +1375,9 @@ extension PersistableRecordTests {
}
}
func test_insertAndFetch_selection_fetch() throws {
func test_insertAndFetch_selection_fetch_column() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1423,6 +1423,104 @@ extension PersistableRecordTests {
}
}
}
func test_insertAndFetch_selection_fetch_allColumns() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 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 Database.sqliteLibVersionNumber >= 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
@@ -1430,7 +1528,7 @@ extension PersistableRecordTests {
extension PersistableRecordTests {
func test_saveAndFetch_as() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1551,9 +1649,9 @@ extension PersistableRecordTests {
}
}
func test_saveAndFetch_selection_fetch() throws {
func test_saveAndFetch_selection_fetch_column() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -1673,6 +1771,256 @@ extension PersistableRecordTests {
}
}
}
func test_saveAndFetch_selection_fetch_allColumns() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard Database.sqliteLibVersionNumber >= 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 Database.sqliteLibVersionNumber >= 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
@@ -1680,7 +2028,7 @@ extension PersistableRecordTests {
extension PersistableRecordTests {
func test_upsert() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("UPSERT is not available")
}
#else
@@ -1817,7 +2165,7 @@ extension PersistableRecordTests {
func test_upsertAndFetch_do_update_set_where() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("UPSERT is not available")
}
#else
@@ -1962,7 +2310,7 @@ extension PersistableRecordTests {
func test_upsertAndFetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("UPSERT is not available")
}
#else
@@ -2065,7 +2413,7 @@ extension PersistableRecordTests {
func test_upsertAndFetch_as() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("UPSERT is not available")
}
#else
@@ -1508,7 +1508,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
func testAvgExpression_filter() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3030000 else {
guard Database.sqliteLibVersionNumber >= 3030000 else {
throw XCTSkip("FILTER clause on aggregate functions is not available")
}
#else
@@ -1573,7 +1573,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
func testMinExpression_filter() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3030000 else {
guard Database.sqliteLibVersionNumber >= 3030000 else {
throw XCTSkip("FILTER clause on aggregate functions is not available")
}
#else
@@ -1606,7 +1606,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
func testMaxExpression_filter() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3030000 else {
guard Database.sqliteLibVersionNumber >= 3030000 else {
throw XCTSkip("FILTER clause on aggregate functions is not available")
}
#else
@@ -1639,7 +1639,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
func testSumExpression_filter() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3030000 else {
guard Database.sqliteLibVersionNumber >= 3030000 else {
throw XCTSkip("FILTER clause on aggregate functions is not available")
}
#else
@@ -1661,7 +1661,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
func testSumExpression_order() throws {
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3044000 else {
guard Database.sqliteLibVersionNumber >= 3044000 else {
throw XCTSkip("ORDER BY clause on aggregate functions is not available")
}
@@ -1696,7 +1696,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
func testTotalExpression_filter() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3030000 else {
guard Database.sqliteLibVersionNumber >= 3030000 else {
throw XCTSkip("FILTER clause on aggregate functions is not available")
}
#else
@@ -1718,7 +1718,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
func testTotalExpression_order() throws {
// Prevent SQLCipher failures
guard sqlite3_libversion_number() >= 3044000 else {
guard Database.sqliteLibVersionNumber >= 3044000 else {
throw XCTSkip("ORDER BY clause on aggregate functions is not available")
}
@@ -800,6 +800,16 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase {
}
}
func test_static_selectID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalNonOptionalPrimaryKeySingle(id: "theUUID")
try record.insert(db)
let ids: [String] = try MinimalSingle.selectID().fetchAll(db)
XCTAssertEqual(ids, ["theUUID"])
}
}
func test_request_selectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -811,4 +821,14 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase {
XCTAssertEqual(rows, [["id": "theUUID"]])
}
}
func test_request_selectID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalNonOptionalPrimaryKeySingle(id: "theUUID")
try record.insert(db)
let ids: [String] = try MinimalSingle.all().selectID().fetchAll(db)
XCTAssertEqual(ids, ["theUUID"])
}
}
}
@@ -844,6 +844,16 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
}
}
func test_static_selectID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalRowID()
try record.insert(db)
let ids: [Int64?] = try MinimalRowID.selectID().fetchAll(db)
XCTAssertEqual(ids, [1])
}
}
func test_request_selectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -855,4 +865,14 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase {
XCTAssertEqual(rows, [["id": 1]])
}
}
func test_request_selectID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalRowID()
try record.insert(db)
let ids: [Int64?] = try MinimalRowID.all().selectID().fetchAll(db)
XCTAssertEqual(ids, [1])
}
}
}
@@ -375,7 +375,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'")
}
}
// MARK: - Fetch With Key Request
@@ -661,7 +661,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
_ = try MinimalSingle.find(db, key: id)
XCTFail("Expected RecordError")
} catch RecordError.recordNotFound(databaseTableName: "minimalSingles", key: ["UUID": .null]) { }
do {
let fetchedRecord = try MinimalSingle.find(db, key: record.UUID)
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
@@ -680,7 +680,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
}
// MARK: - Fetch With Primary Key Request
@@ -861,7 +861,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
// MARK: Select PrimaryKey
func test_static_selectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -875,6 +875,17 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
}
}
func test_static_selectID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
let ids: [String] = try MinimalSingle.selectID().fetchAll(db)
XCTAssertEqual(ids, ["theUUID"])
}
}
func test_request_selectPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -887,4 +898,15 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase {
XCTAssertEqual(rows, [["UUID": "theUUID"]])
}
}
func test_request_selectID() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = MinimalSingle()
record.UUID = "theUUID"
try record.insert(db)
let ids: [String] = try MinimalSingle.all().selectID().fetchAll(db)
XCTAssertEqual(ids, ["theUUID"])
}
}
}
@@ -28,7 +28,7 @@ private class Person : Record, Hashable {
// Record
override static var databaseSelection: [any SQLSelectable] {
[AllColumns(), Column.rowID]
[.allColumns, .rowID]
}
override class var databaseTableName: String {
+43 -5
View File
@@ -309,10 +309,22 @@ 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)
@@ -347,7 +359,7 @@ extension SQLLiteralTests {
let (sql, arguments) = try query.build(db)
XCTAssertEqual(sql, """
SELECT "altPlayer"."id", "altPlayer"."name"
SELECT "player"."id", "player"."name"
FROM player
""")
XCTAssert(arguments.isEmpty)
@@ -365,6 +377,32 @@ 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)
}
}
}
@@ -640,7 +678,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)"
@@ -654,7 +692,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)"
@@ -668,7 +706,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)")
@@ -682,7 +720,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"])
+2 -2
View File
@@ -188,7 +188,7 @@ class SingletonRecordTest: GRDBTestCase {
func test_upsert_in_empty_database() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("UPSERT is not available")
}
#else
@@ -211,7 +211,7 @@ class SingletonRecordTest: GRDBTestCase {
func test_upsert_in_populated_database() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("UPSERT is not available")
}
#else
+7 -16
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
import XCTest
import GRDB
@@ -56,7 +47,7 @@ class TableDefinitionTests: GRDBTestCase {
}
func testStrictTableCreationOption() throws {
guard sqlite3_libversion_number() >= 3037000 else {
guard Database.sqliteLibVersionNumber >= 3037000 else {
throw XCTSkip("STRICT tables are not available")
}
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
@@ -367,7 +358,7 @@ class TableDefinitionTests: GRDBTestCase {
func testColumnGeneratedAs() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3031000 else {
guard Database.sqliteLibVersionNumber >= 3031000 else {
throw XCTSkip("Generated columns are not available")
}
#else
@@ -802,7 +793,7 @@ class TableDefinitionTests: GRDBTestCase {
}
func testAlterTableRenameColumn() throws {
guard sqlite3_libversion_number() >= 3025000 else {
guard Database.sqliteLibVersionNumber >= 3025000 else {
throw XCTSkip("ALTER TABLE RENAME COLUMN is not available")
}
let dbQueue = try makeDatabaseQueue()
@@ -825,7 +816,7 @@ class TableDefinitionTests: GRDBTestCase {
}
func testAlterTableRenameColumnInvalidatesSchemaCache() throws {
guard sqlite3_libversion_number() >= 3025000 else {
guard Database.sqliteLibVersionNumber >= 3025000 else {
throw XCTSkip("ALTER TABLE RENAME COLUMN is not available")
}
let dbQueue = try makeDatabaseQueue()
@@ -844,7 +835,7 @@ class TableDefinitionTests: GRDBTestCase {
func testAlterTableAddGeneratedVirtualColumn() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3031000 else {
guard Database.sqliteLibVersionNumber >= 3031000 else {
throw XCTSkip("Generated columns are not available")
}
#else
@@ -879,7 +870,7 @@ class TableDefinitionTests: GRDBTestCase {
}
func testAlterTableDropColumn() throws {
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("ALTER TABLE DROP COLUMN is not available")
}
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
@@ -903,7 +894,7 @@ class TableDefinitionTests: GRDBTestCase {
}
func testAlterTableDropColumnInvalidatesSchemaCache() throws {
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("ALTER TABLE DROP COLUMN is not available")
}
#if !GRDBCUSTOMSQLITE && !GRDBCIPHER
@@ -71,6 +71,32 @@ 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\")")
}
}
+27 -13
View File
@@ -227,7 +227,7 @@ class TableRecordDeleteTests: GRDBTestCase {
func testRequestDeleteAndFetchStatement() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -238,16 +238,30 @@ class TableRecordDeleteTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
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: [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"])
}
}
}
func testRequestDeleteAndFetchCursor() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -306,7 +320,7 @@ class TableRecordDeleteTests: GRDBTestCase {
func testRequestDeleteAndFetchArray() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -334,7 +348,7 @@ class TableRecordDeleteTests: GRDBTestCase {
func testRequestDeleteAndFetchSet() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -360,7 +374,7 @@ class TableRecordDeleteTests: GRDBTestCase {
func testRequestDeleteAndFetchIds() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -443,7 +457,7 @@ class TableRecordDeleteTests: GRDBTestCase {
func testJoinedRequestDeleteAndFetch() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
@@ -479,7 +493,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" \
@@ -511,7 +525,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" \
@@ -610,7 +624,7 @@ class TableRecordDeleteTests: GRDBTestCase {
func testGroupedRequestDeleteAndFetchCursor() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
guard Database.sqliteLibVersionNumber >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
+16 -1
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(), Column.rowID] }
static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -128,6 +128,21 @@ 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:
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff. Show more