diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..d82189eac --- /dev/null +++ b/.editorconfig @@ -0,0 +1,8 @@ +[*.swift] +indent_style = space +indent_size = 4 +tab_width = 4 +end_of_line = lf +insert_final_newline = true +max_line_length = 76 +trim_trailing_whitespace = true diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 6a9f3ec80..f657f8ffc 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -1,4 +1,4 @@ -# https://github.com/actions/runner-images/blob/main/images/macos/macos-12-Readme.md +# https://github.com/actions/runner-images/blob/main/images/macos/macos-14-Readme.md name: "GRDB CI" @@ -40,42 +40,18 @@ jobs: fail-fast: false matrix: include: - - xcode: "Xcode_14.3.1.app" - runsOn: macOS-13 + - xcode: "Xcode_16.1.app" + runsOn: macOS-14 destination: "platform=macOS" name: "macOS" - - xcode: "Xcode_14.3.1.app" - runsOn: macOS-13 - destination: "OS=16.4,name=iPhone 14 Pro" + - xcode: "Xcode_16.1.app" + runsOn: macOS-14 + destination: "OS=18.1,name=iPhone 16 Pro" name: "iOS" - - xcode: "Xcode_14.3.1.app" - runsOn: macOS-13 - destination: "OS=16.4,name=Apple TV" + - xcode: "Xcode_16.1.app" + runsOn: macOS-14 + destination: "OS=18.1,name=Apple TV" name: "tvOS" - - xcode: "Xcode_14.2.app" - runsOn: macOS-13 - destination: "platform=macOS" - name: "macOS" - - xcode: "Xcode_14.2.app" - runsOn: macOS-13 - destination: "OS=16.2,name=iPhone 14" - name: "iOS" - - xcode: "Xcode_14.1.app" - runsOn: macOS-13 - destination: "platform=macOS" - name: "macOS" - - xcode: "Xcode_14.1.app" - runsOn: macOS-13 - destination: "OS=16.1,name=iPhone 14" - name: "iOS" - - xcode: "Xcode_14.0.1.app" - runsOn: macOS-12 - destination: "platform=macOS" - name: "macOS" - - xcode: "Xcode_14.0.1.app" - runsOn: macOS-12 - destination: "OS=16.0,name=iPhone 14" - name: "iOS" steps: - uses: actions/checkout@v4 - name: ${{ matrix.name }} @@ -90,18 +66,9 @@ jobs: fail-fast: false matrix: include: - - xcode: "Xcode_14.3.1.app" - runsOn: macOS-13 - name: "Xcode 14.3.1" - - xcode: "Xcode_14.2.app" - runsOn: macOS-13 - name: "Xcode 14.2" - - xcode: "Xcode_14.1.app" - runsOn: macOS-13 - name: "Xcode 14.1" - - xcode: "Xcode_14.0.1.app" - runsOn: macOS-12 - name: "Xcode 14.0.1" + - xcode: "Xcode_16.1.app" + runsOn: macOS-14 + name: "Xcode 16.1" steps: - uses: actions/checkout@v4 - name: ${{ matrix.name }} @@ -116,12 +83,9 @@ jobs: fail-fast: false matrix: include: - - xcode: "Xcode_14.3.1.app" - runsOn: macOS-13 - name: "Xcode 14.3.1" - - xcode: "Xcode_14.0.1.app" - runsOn: macOS-12 - name: "Xcode 14.0.1" + - xcode: "Xcode_16.1.app" + runsOn: macOS-14 + name: "Xcode 16.1" steps: - uses: actions/checkout@v4 - name: ${{ matrix.name }} @@ -136,12 +100,9 @@ jobs: fail-fast: false matrix: include: - - xcode: "Xcode_14.3.1.app" - runsOn: macOS-13 - name: "Xcode 14.3.1" - - xcode: "Xcode_14.0.1.app" - runsOn: macOS-12 - name: "Xcode 14.0.1" + - xcode: "Xcode_16.1.app" + runsOn: macOS-14 + name: "Xcode 16.1" steps: - uses: actions/checkout@v4 - name: ${{ matrix.name }} @@ -156,12 +117,9 @@ jobs: fail-fast: false matrix: include: - - xcode: "Xcode_14.3.1.app" - runsOn: macOS-13 - name: "Xcode 14.3.1" - - xcode: "Xcode_14.0.1.app" - runsOn: macOS-12 - name: "Xcode 14.0.1" + - xcode: "Xcode_16.1.app" + runsOn: macOS-14 + name: "Xcode 16.1" steps: - uses: actions/checkout@v4 - name: ${{ matrix.name }} @@ -176,12 +134,9 @@ jobs: fail-fast: false matrix: include: - - xcode: "Xcode_14.3.1.app" - runsOn: macOS-13 - name: "Xcode 14.3.1" - - xcode: "Xcode_14.0.1.app" - runsOn: macOS-12 - name: "Xcode 14.0.1" + - xcode: "Xcode_16.1.app" + runsOn: macOS-14 + name: "Xcode 16.1" steps: - uses: actions/checkout@v4 - name: ${{ matrix.name }} diff --git a/.spi.yml b/.spi.yml index 9e3cf0267..672a6aac0 100644 --- a/.spi.yml +++ b/.spi.yml @@ -2,3 +2,4 @@ version: 1 builder: configs: - documentation_targets: [GRDB] + swift_version: 6.0 diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/GRDB-Package.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/GRDB-Package.xcscheme deleted file mode 100644 index b60345c20..000000000 --- a/.swiftpm/xcode/xcshareddata/xcschemes/GRDB-Package.xcscheme +++ /dev/null @@ -1,134 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/CHANGELOG.md b/CHANGELOG.md index 9d31c3a7e..18d54a99e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,8 +5,19 @@ All notable changes to this project will be documented in this file. GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: APIs flagged [**:fire: EXPERIMENTAL**](README.md#what-are-experimental-features). Those are unstable, and may break between any two minor releases of the library. +#### 7.x Releases + +- `7.5.x` Releases - [7.5.0](#750) +- `7.4.x` Releases - [7.4.0](#740) - [7.4.1](#741) +- `7.3.x` Releases - [7.3.0](#730) +- `7.2.x` Releases - [7.2.0](#720) +- `7.1.x` Releases - [7.1.0](#710) +- `7.0.x` Releases - [7.0.0](#700) +- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6) - [7.0.0-beta.7](#700-beta7) + #### 6.x Releases +- `6.29.x` Releases - [6.29.0](#6290) - [6.29.1](#6291) - [6.29.2](#6292) - [6.29.3](#6293) - `6.28.x` Releases - [6.28.0](#6280) - `6.27.x` Releases - [6.27.0](#6270) - `6.26.x` Releases - [6.26.0](#6260) @@ -126,6 +137,152 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception: --- +## 7.5.0 + +Released May 11, 2025 + +- **New**: Make it possible to create a raw FTS5Pattern without any database connection by [@groue](https://github.com/groue) in [#1764](https://github.com/groue/GRDB.swift/pull/1764) +- **New**: Build request with closures by [@groue](https://github.com/groue) in [#1759](https://github.com/groue/GRDB.swift/pull/1759) + +## 7.4.1 + +Released March 28, 2025 + +- Removed a compiler warning + +## 7.4.0 + +Released March 22, 2025 + +- **New**: Add the MIN and MAX multi-argument SQL functions to the query interface by [@groue](https://github.com/groue) in [#1745](https://github.com/groue/GRDB.swift/pull/1745) +- **Fixed**: Transaction observers are not impacted by Task Cancellation by [@groue](https://github.com/groue) in [#1747](https://github.com/groue/GRDB.swift/pull/1747). This fixes unexpected `ValueObservation` failures in applications that perform asynchronous writes. + +## 7.3.0 + +Released February 23, 2025 + +- **New**: Support for temporary virtual tables by [@groue](https://github.com/groue) in [#1731](https://github.com/groue/GRDB.swift/pull/1731) +- Fixed a compiler error in Xcode 16.3 beta ([#1729](https://github.com/groue/GRDB.swift/pull/1729), [#1730](https://github.com/groue/GRDB.swift/pull/1730)) + +## 7.2.0 + +Released February 12, 2025 + +- **New**: Select ids with selectID() by [@groue](https://github.com/groue) in [#1719](https://github.com/groue/GRDB.swift/pull/1719) + +## 7.1.0 + +Released February 5, 2025 + +- **New**: Expose `sqlite3_libversion_number` as `Database.sqliteLibVersionNumber` by [@groue](https://github.com/groue) in [#1713](https://github.com/groue/GRDB.swift/pull/1713) +- **Fixed**: DatabaseQueue restores its read/write abilities when an async read-only database access is cancelled by [@groue](https://github.com/groue) in [#1716](https://github.com/groue/GRDB.swift/pull/1716) +- **New**: Allow RxGRDB to compile without warning by [@groue](https://github.com/groue) in [#1717](https://github.com/groue/GRDB.swift/pull/1717) + +## 7.0.0 + +Released January 26, 2025 + +- **New**: Support for JSONB expressions by [@groue](https://github.com/groue) in [#1699](https://github.com/groue/GRDB.swift/pull/1699) +- **Breaking Change**: Fix inflections of Bias, Focus, Gas, and Lens by [@groue](https://github.com/groue) in [#1703](https://github.com/groue/GRDB.swift/pull/1703) + +## 7.0.0-beta.7 + +Released January 19, 2025 + +- **New**: Select all columns from a table, but a few ones by [@groue](https://github.com/groue) in [#1700](https://github.com/groue/GRDB.swift/pull/1700) +- **Fixed**: Fix typo in Readme.md by [@kevinlg](https://github.com/kevinlg) in [#1697](https://github.com/groue/GRDB.swift/pull/1697) +- **New**: Bump custom SQLite to 3.47.2 by [@groue](https://github.com/groue) in [#1696](https://github.com/groue/GRDB.swift/pull/1696) +- **Fixed**: Update LICENSE, fix copyright license year by [@JasonnnW3000](https://github.com/JasonnnW3000) in [#1695](https://github.com/groue/GRDB.swift/pull/1695) +- **Fixed**: Core: import `ucrt` on Windows for `strcmp` by [@compnerd](https://github.com/compnerd) in [#1662](https://github.com/groue/GRDB.swift/pull/1662) +- **Fixed**: Foundation: elide extensions on Windows to match Linux by [@compnerd](https://github.com/compnerd) in [#1661](https://github.com/groue/GRDB.swift/pull/1661) +- **Fixed**: Docs: fixes typos "FST"->"FTS" by [@nylki](https://github.com/nylki) in [#1660](https://github.com/groue/GRDB.swift/pull/1660) + +## 7.0.0-beta.6 + +Released October 13, 2024 + +- **New**: Bump custom SQLite builds to 3.46.1 by [@groue](https://github.com/groue) in [#1654](https://github.com/groue/GRDB.swift/pull/1654) + +## 7.0.0-beta.5 + +Released October 13, 2024 + +- **Fixed**: Fix DatabaseMigrator.hasSchemaChanges failing for readonly connections by [@Jnosh](https://github.com/Jnosh) in [#1653](https://github.com/groue/GRDB.swift/pull/1653) +- **Documentation Update**: Enhance the database schema documentation by [@groue](https://github.com/groue) in [#1652](https://github.com/groue/GRDB.swift/pull/1652) + +## 7.0.0-beta.4 + +Released October 12, 2024 + +- **New**: Allow applications to handle DatabaseMigrator schema changes by [@groue](https://github.com/groue) in [#1651](https://github.com/groue/GRDB.swift/pull/1651) + +## 7.0.0-beta.3 + +Released October 6, 2024 + +- **Fix**: use #if directives to conditionally @preconcurrency import the Dispatch module to enable building the package on linux by [@tayloraswift](https://github.com/tayloraswift) in [#1644](https://github.com/groue/GRDB.swift/pull/1644) +- **New**: Add coalesce free function and Row method by [@philmitchell](https://github.com/philmitchell) in [#1645](https://github.com/groue/GRDB.swift/pull/1645) +- **Documentation Update**: Add `DatabaseValueConvertible` tip for JSON columns by [@bok-](https://github.com/bok-) in [#1649](https://github.com/groue/GRDB.swift/pull/1649) + +## 7.0.0-beta.2 + +Released September 29, 2024 + +- **Fix**: Update .spi.yml by [@finestructure](https://github.com/finestructure) in [#1643](https://github.com/groue/GRDB.swift/pull/1643) + +## 7.0.0-beta + +Released September 29, 2024 + +**GRDB 7 brings full support for Swift 6.** + +[Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) describes in detail how to bump the GRDB version in your application. + +The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency. + +The [demo app](Documentation/DemoApps/) was rewritten from scratch in a brand new Xcode 16 project. + +- **Breaking Change**: Bump requirements by [@groue](https://github.com/groue) in [#1598](https://github.com/groue/GRDB.swift/pull/1598) and [#1634](https://github.com/groue/GRDB.swift/pull/1634) +- **Breaking Change**: Enhance ergonomics of record methods that insert/save/upsert and fetch by [@groue](https://github.com/groue) in [#1599](https://github.com/groue/GRDB.swift/pull/1599) +- **Breaking Change**: Rename the CSQLite module to GRDBSQLite, and stop exporting the C SQLite functions by [@groue](https://github.com/groue) in [#1600](https://github.com/groue/GRDB.swift/pull/1600) +- **Breaking Change**: Perform all writes with immediate transactions by default by [@groue](https://github.com/groue) in [#1602](https://github.com/groue/GRDB.swift/pull/1602) +- **Breaking Change**: Remove DatabasePool.concurrentRead by [@groue](https://github.com/groue) in [#1603](https://github.com/groue/GRDB.swift/pull/1603) +- **Breaking Change**: Coding strategies depend on the column by [@groue](https://github.com/groue) in [#1606](https://github.com/groue/GRDB.swift/pull/1606) +- **Breaking Change**: Add missing Sendable conformances by [@groue](https://github.com/groue) in [#1607](https://github.com/groue/GRDB.swift/pull/1607) and [#1639](https://github.com/groue/GRDB.swift/pull/1639) +- **Breaking Change**: Async database accesses honor Task cancellation by [@groue](https://github.com/groue) in [#1610](https://github.com/groue/GRDB.swift/pull/1610) +- **Breaking Change**: Prefer Collection over Sequence for filter(keys:) and related APIs by [@groue](https://github.com/groue) in [#1617](https://github.com/groue/GRDB.swift/pull/1617) +- **Breaking Change**: MainActor ValueObservation scheduling by [@groue](https://github.com/groue) in [#1633](https://github.com/groue/GRDB.swift/pull/1633) +- **Breaking Change**: Prefer any DatabaseReader and DatabaseWriter by [@groue](https://github.com/groue) in [#1635](https://github.com/groue/GRDB.swift/pull/1635) +- **New**: Sendable database accesses by [@groue](https://github.com/groue) in [#1618](https://github.com/groue/GRDB.swift/pull/1618) +- **New**: DatabaseCursor has a primary associated type by [@groue](https://github.com/groue) in [#1605](https://github.com/groue/GRDB.swift/pull/1605) + +## 6.29.3 + +Released September 7, 2024 + +- **Fixed**: [#1613](https://github.com/groue/GRDB.swift/pull/1613) by [@groue](https://github.com/groue): Avoid SQLite misuse when releasing memory on a closed database connection + +## 6.29.2 + +Released August 24, 2024 + +- **New**: [#1593](https://github.com/groue/GRDB.swift/pull/1593) by [@mingchen](https://github.com/mingchen): Fix sample code in README + +## 6.29.1 + +Released August 7, 2024 + +- **New**: [#1579](https://github.com/groue/GRDB.swift/pull/1579) by [@groue](https://github.com/groue): Modernize the demo apps +- **New**: [#1584](https://github.com/groue/GRDB.swift/pull/1584) by [@SagarSDagdu](https://github.com/SagarSDagdu): Update README to highlight deployment issue with CocoaPods +- **New**: [#1589](https://github.com/groue/GRDB.swift/pull/1589) by [@groue](https://github.com/groue): Fix compilation issue with Xcode 16 beta 5 due to a missing import + +## 6.29.0 + +Released July 20, 2024 + +- **New**: [#1574](https://github.com/groue/GRDB.swift/pull/1574) by [@sroebert](https://github.com/sroebert): Support for single value decoding (the complement of [#1570](https://github.com/groue/GRDB.swift/pull/1570) shipped in 6.28.0) +- **New**: [#1575](https://github.com/groue/GRDB.swift/pull/1575) by [@Jason-Abbott](https://github.com/Jason-Abbott): Show comments when tracing expanded statements + ## 6.28.0 Released July 11, 2024 @@ -140,8 +297,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 @@ -166,7 +323,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 @@ -193,7 +350,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 @@ -229,8 +386,8 @@ Released October 4, 2023 • [diff](https://github.com/groue/GRDB.swift/compa - **New**: [#1436](https://github.com/groue/GRDB.swift/pull/1436) by [@myyra](https://github.com/myyra) and [@groue](https://github.com/groue): JSON functions - **New**: `Database` has learned to create indexes on expressions, and specify specific collations on indexed columns, with the `create(index:on:expressions:options:condition:)` method. - **New**: Codable records can specify coding strategies for their `Data` properties. See [#1436](https://github.com/groue/GRDB.swift/pull/1436) for more information. -- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/json) article provides an overview of JSON handling. -- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol. +- **Documentation Update**: A new [JSON Support](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/json) article provides an overview of JSON handling. +- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) now recommend that record types with an auto-incremented id avoid conforming to the `Identifiable` protocol. ## 6.18.0 @@ -254,14 +411,14 @@ Released July 9, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/ - **New**: [#1403](https://github.com/groue/GRDB.swift/pull/1403) by [@groue](https://github.com/groue): GitHub CI: test Xcode 14.3.1, macOS 13 - **New**: :star: [#1405](https://github.com/groue/GRDB.swift/pull/1405) Simplify the declaration of BelongsTo associations in the database schema - **Documentation Update**: The documentation was updated for the new recommended way to declare associations in the database schema, with the `belongsTo()` method introduced by [#1405](https://github.com/groue/GRDB.swift/pull/1405): - - [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:)) - - [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) - - [Migrations](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations) - - [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) + - [`belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tabledefinition/belongsto(_:intable:ondelete:onupdate:deferred:indexed:)) + - [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) + - [Migrations](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/migrations) + - [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) - [Associations](Documentation/AssociationsBasics.md) - - [`BelongsToAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/belongstoassociation) - - [`HasManyAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasmanyassociation) - - [`HasOneAssociation`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/hasoneassociation) + - [`BelongsToAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/belongstoassociation) + - [`HasManyAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/hasmanyassociation) + - [`HasOneAssociation`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/hasoneassociation) ## 6.15.1 @@ -278,7 +435,7 @@ Released June 2, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/ - **New**: [#1382](https://github.com/groue/GRDB.swift/pull/1382) Add `DerivableRequest.all()` - **New**: [#1384](https://github.com/groue/GRDB.swift/pull/1384) Allow ValueObservation to start from a truncated wal file -- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`. +- **Documentation Update**: The [ValueObservation Performance](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation#ValueObservation-Performance) documentation chapter explains how truncating WAL checkpoints impact `ValueObservation`. ## 6.14.0 @@ -313,7 +470,7 @@ Released April 17, 2023 • [diff](https://github.com/groue/GRDB.swift/compar Released April 10, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.1...v6.10.2) -- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC. +- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC. - **Documentation Update**: The [Demo Applications](Documentation/DemoApps/) demonstrate how their `AppDatabase` "database manager" can provide a base database configuration. ## 6.10.1 @@ -340,8 +497,8 @@ Released March 14, 2023 • [diff](https://github.com/groue/GRDB.swift/compar Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.0...v6.9.1) - **Documentation Updates**: Moved more README chapters into DocC: - - [`RowAdapter`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter) - - [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/splittingrowadapters(columncounts:)) + - [`RowAdapter`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter) + - [`splittingRowAdapters(columnCounts:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/splittingrowadapters(columncounts:)) ## 6.9.0 @@ -350,9 +507,9 @@ Released March 12, 2023 • [diff](https://github.com/groue/GRDB.swift/compar - **New**: [#1348](https://github.com/groue/GRDB.swift/pull/1348) by [@groue](https://github.com/groue): SQLite argument binding optimization - **New**: `FTS5.api(db)` returns a pointer to the `fts5_api` structure, useful for low-level [FTS5 customization](https://www.sqlite.org/fts5.html#extending_fts5). - **Documentation Updates**: Moved more README chapters into DocC, enhanced and extended DocC articles: - - [Database Connections](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections) - - [Prepared Statements](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statement) - - [DatabaseValueConvertible](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasevalueconvertible) + - [Database Connections](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseconnections) + - [Prepared Statements](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statement) + - [DatabaseValueConvertible](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasevalueconvertible) ## 6.8.0 @@ -360,7 +517,7 @@ Released February 24, 2023 • [diff](https://github.com/groue/GRDB.swift/com - **New**: [#1338](https://github.com/groue/GRDB.swift/pull/1338) by [@groue](https://github.com/groue): TimestampedRecord sample code - **New**: `EncodableRecord.databaseChanges(modify:)` modifies a record and returns a dictionary of applied changes. -- **Documentation Update**: The [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article provides a sample `TimestampedRecord` protocol that application may adapt for their own use. +- **Documentation Update**: The [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps) article provides a sample `TimestampedRecord` protocol that application may adapt for their own use. ## 6.7.0 @@ -371,7 +528,7 @@ Released February 19, 2023 • [diff](https://github.com/groue/GRDB.swift/com - **Fixed**: [#1327](https://github.com/groue/GRDB.swift/pull/1327) by [@groue](https://github.com/groue): Remove dependency on any specific SwiftLint version. - **New**: [#1331](https://github.com/groue/GRDB.swift/pull/1331) by [@groue](https://github.com/groue): Transaction Date - **New**: [#1336](https://github.com/groue/GRDB.swift/pull/1336) by [@groue](https://github.com/groue): Enable FTS5 by default -- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records. +- **Documentation Update**: The new [Record Timestamps and Transaction Date](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordtimestamps) article explains how applications can save the creation and modification date of records. - Added support for `Table` in SQL interpolation. ## 6.6.1 @@ -401,11 +558,11 @@ Released November 28, 2022 • [diff](https://github.com/groue/GRDB.swift/com - **New**: `DatabaseReader.configuration.readQoS` and `writeQoS` return the effective quality of service of read-only and write database accesses. This helps application code avoid priority inversion and similar scheduling misuses when needed. - **New**: `DatabaseReader.configuration.maximumReaderCount` returns the effective capacity for concurrent reads, so that application code can adapt when needed. - **New**: `DatabasePool.makeSnapshot()` no longer throws an error when the database is not in the WAL mode. In such case, the returned snapshot prevents all database modifications during its lifetime. -- **New**: A new [`DatabaseSnapshotReader`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshotreader) protocol was introduced for types that see an unchanging database content (`DatabaseSnapshot` and the new `DatabaseSnapshotPool`). -- **New**: [`Database.registerAccess(to:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/registeraccess(to:)) has `ValueObservation` track a region. This helps building optimized observations of a constant database region with [`ValueObservation.trackingConstantRegion(_:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/trackingconstantregion(_:)). -- **New**: Open several connections to the same in-memory database with [`DatabaseQueue(named:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue/init(named:configuration:)). -- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/tabledefinition) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended. -- **New**: The [Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) documentation article has a brand new "Database Schema Recommendations" section. +- **New**: A new [`DatabaseSnapshotReader`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesnapshotreader) protocol was introduced for types that see an unchanging database content (`DatabaseSnapshot` and the new `DatabaseSnapshotPool`). +- **New**: [`Database.registerAccess(to:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/registeraccess(to:)) has `ValueObservation` track a region. This helps building optimized observations of a constant database region with [`ValueObservation.trackingConstantRegion(_:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/trackingconstantregion(_:)). +- **New**: Open several connections to the same in-memory database with [`DatabaseQueue(named:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue/init(named:configuration:)). +- **New**: [`TableDefinition`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/tabledefinition) has new methods for defining primary keys, with automatic NOT NULL constraints. They workaround [an SQLite bug](https://www.sqlite.org/quirks.html#primary_keys_can_sometimes_contain_nulls). Previous techniques for defining primary keys are preserved for backwards compatibility, but their use is not recommended. +- **New**: The [Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) documentation article has a brand new "Database Schema Recommendations" section. - **New**: Multiple improvements to the DocC documentation. ## 6.3.1 diff --git a/Documentation/AppGroupContainers.md b/Documentation/AppGroupContainers.md index 85f8aca1f..995956e53 100644 --- a/Documentation/AppGroupContainers.md +++ b/Documentation/AppGroupContainers.md @@ -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). diff --git a/Documentation/AssociationsBasics.md b/Documentation/AssociationsBasics.md index 50e241674..5f7b6e1e2 100644 --- a/Documentation/AssociationsBasics.md +++ b/Documentation/AssociationsBasics.md @@ -58,15 +58,26 @@ GRDB Associations Associations streamline common operations in your code, make them safer, and more efficient. For example, consider a library application that has two record types, author and book: ```swift -struct Author { +struct Author: Codable, Identifiable, FetchableRecord, PersistableRecord { var id: Int64 var name: String + + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + } } -struct Book { +struct Book: Codable, Identifiable, FetchableRecord, PersistableRecord { var id: Int64 var authorId: Int64? var title: String + + enum Columns { + static let id = Column(CodingKeys.id) + static let authorId = Column(CodingKeys.authorId) + static let title = Column(CodingKeys.title) + } } ``` @@ -75,7 +86,7 @@ Now, suppose we wanted to load all books from an existing author. We'd need to d ```swift let author: Author = ... let books = try Book - .filter(Column("authorId") == author.id) + .filter { $0.authorId == author.id } .fetchAll(db) ``` @@ -121,7 +132,7 @@ let books = try author.books.fetchAll(db) As for loading all pairs of books and authors, it is not only easier, but also *much more efficient*: ```swift -struct BookInfo: FetchableRecord, Decodable { +struct BookInfo: Decodable, FetchableRecord { let book: Book let author: Author? } @@ -130,16 +141,14 @@ 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 **Associations are available on types that adopt the necessary supporting protocols.** -When your record type is a subclass of the [Record class], all necessary protocols are already setup and ready: you can skip this chapter. - -Generally speaking, associations use the [TableRecord], [FetchableRecord], and [EncodableRecord] protocols: +Associations are based on the [TableRecord], [FetchableRecord], and [EncodableRecord] protocols: - **[TableRecord]** is the protocol that lets you declare associations between record types: @@ -730,9 +739,15 @@ Your help is needed. You have to instruct GRDB which foreign key to use: ```swift struct Book: TableRecord { + // Table columns + enum Columns { + static let authorId = Column("authorId") + static let translatorId = Column("translatorId") + } + // Define foreign keys - static let authorForeignKey = ForeignKey(["authorId"]) - static let translatorForeignKey = ForeignKey(["translatorId"]) + static let authorForeignKey = ForeignKey([Columns.authorId]) + static let translatorForeignKey = ForeignKey([Columns.translatorId]) // Use foreign keys to define associations: static let author = belongsTo(Person.self, using: authorForeignKey) @@ -749,24 +764,11 @@ struct Person: TableRecord { } ``` -Foreign keys can also be defined from query interface columns: - -```swift -struct Book: TableRecord { - enum Columns: String, ColumnExpression { - case id, title, authorId, translatorId - } - - static let authorForeignKey = ForeignKey([Columns.authorId]) - static let translatorForeignKey = ForeignKey([Columns.translatorId]) -} -``` - When the destination table of a foreign key does not define any primary key, you need to provide the full definition of a foreign key: ```swift struct Book: TableRecord { - static let authorForeignKey = ForeignKey(["authorId"], to: ["id"]) + static let authorForeignKey = ForeignKey([Columns.authorId], to: [Person.Columns.id]) static let author = belongsTo(Person.self, using: authorForeignKey) } ``` @@ -838,8 +840,8 @@ Requests for associated records can be filtered and ordered like all [query inte ```swift let novels = try author .books - .filter(Column("kind") == BookKind.novel) - .order(Column("publishDate").desc) + .filter { $0.kind == BookKind.novel } + .order(\.publishDate.desc) .fetchAll(db) // [Book] ``` @@ -923,7 +925,7 @@ struct BookInfo: Decodable, FetchableRecord { var author: PartialAuthor } let bookInfos = try Book - .including(required: Book.author.select(Column("name"), Column("country"))) + .including(required: Book.author.select { [$0.name, $0.country] }) .asRequest(of: BookInfo.self) .fetchAll(db) ``` @@ -937,7 +939,7 @@ struct BookInfo: Decodable, FetchableRecord { var country: String } let bookInfos = try Book - .annotated(withRequired: Book.author.select(Column("country"))) + .annotated(withRequired: Book.author.select(\.country) .asRequest(of: BookInfo.self) .fetchAll(db) ``` @@ -984,7 +986,7 @@ struct BookInfo: Decodable, FetchableRecord { var author: PartialAuthor? } let bookInfos = try Book - .including(optional: Book.author.select(Column("name"), Column("country"))) + .including(optional: Book.author.select { [$0.name, $0.country] }) .asRequest(of: BookInfo.self) .fetchAll(db) ``` @@ -998,7 +1000,7 @@ struct BookInfo: Decodable, FetchableRecord { var country: String? } let bookInfos = try Book - .annotated(withOptional: Book.author.select(Column("country"))) + .annotated(withOptional: Book.author.select(\.country)) .asRequest(of: BookInfo.self) .fetchAll(db) ``` @@ -1066,7 +1068,7 @@ struct AuthorInfo: Decodable, FetchableRecord { var books: [PartialBook] } let authorInfos = try Author - .including(all: Author.books.select(Column("title"), Column("year"))) + .including(all: Author.books.select { [$0.title, $0.year] }) .asRequest(of: AuthorInfo.self) .fetchAll(db) ``` @@ -1081,7 +1083,7 @@ struct AuthorInfo: Decodable, FetchableRecord { } let authorInfos = try Author .including(all: Author.books - .select(Column("title")) + .select(\.title) .forKey("bookTitles")) .asRequest(of: AuthorInfo.self) .fetchAll(db) @@ -1095,7 +1097,7 @@ For example, fetch books along with the name and country of their author: // SELECT book.*, author.name, author.country // FROM book // JOIN author ON author.id = book.authorId -let request = Book.annotated(withRequired: Book.author.select(Column("name"), Column("country"))) +let request = Book.annotated(withRequired: Book.author.select { [$0.name, $0.country] }) ``` This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, records are not present in the fetched results: the associated record is "required". @@ -1110,7 +1112,7 @@ struct BookInfo: Decodable, FetchableRecord { var country: String // A column of the required associated record } let bookInfos = try Book - .annotated(withRequired: Book.author.select(Column("name"), Column("country"))) + .annotated(withRequired: Book.author.select { [$0.name, $0.country] }) .asRequest(of: BookInfo.self) .fetchAll(db) ``` @@ -1124,7 +1126,7 @@ struct BookInfo: Decodable, FetchableRecord { var authorName: String } let bookInfos = try Book - .annotated(withRequired: Book.author.select(Column("name").forKey("authorName"))) + .annotated(withRequired: Book.author.select { $0.name.forKey("authorName") }) .asRequest(of: BookInfo.self) .fetchAll(db) ``` @@ -1137,7 +1139,7 @@ For example, fetch books along with the name and country of their eventual autho // SELECT book.*, author.name, author.country // FROM book // LEFT JOIN author ON author.id = book.authorId -let request = Book.annotated(withOptional: Book.author.select(Column("name"), Column("country"))) +let request = Book.annotated(withOptional: Book.author.select { [$0.name, $0.country] }) ``` This method accepts any association. The base record is annotated with the selected columns of one associated record. When the associated record does not exist, the columns of the associated record are NULL: the associated record is "optional". @@ -1152,7 +1154,7 @@ struct BookInfo: Decodable, FetchableRecord { var country: String? // A column of the optional associated record } let bookInfos = try Book - .annotated(withOptional: Book.author.select(Column("name"), Column("country"))) + .annotated(withOptional: Book.author.select { [$0.name, $0.country] }) .asRequest(of: BookInfo.self) .fetchAll(db) ``` @@ -1166,7 +1168,7 @@ struct BookInfo: Decodable, FetchableRecord { var authorName: String? } let bookInfos = try Book - .annotated(withOptional: Book.author.select(Column("name").forKey("authorName"))) + .annotated(withOptional: Book.author.select { $0.name.forKey("authorName") }) .asRequest(of: BookInfo.self) .fetchAll(db) ``` @@ -1180,7 +1182,7 @@ For example, fetch books by French authors: // FROM book // JOIN author ON author.id = book.authorId // AND author.country = 'France' -let request = Book.joining(required: Book.author.filter(Column("country") == "France")) +let request = Book.joining(required: Book.author.filter { $0.country == "France" }) ``` This method accepts any association. It has the base record "joined" with one associated record, which is not included in the fetched results. When the associated record does not exist, the base record is not present in the fetched results: the associated record is "required". @@ -1190,7 +1192,7 @@ To fetch results from such a request, you do not need to define a dedicated reco ```swift // Fetch all books by French authors let books = try Book - .joining(required: Book.author.filter(Column("country") == "France")) + .joining(required: Book.author.filter { $0.country == "France" }) .fetchAll(db) ``` @@ -1241,7 +1243,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec } let bookInfos = try Book - .including(required: Book.author.select(Column("name"), Column("country"))) + .including(required: Book.author.select { [$0.name, $0.country] }) .asRequest(of: BookInfo.self) .fetchAll(db) ``` @@ -1256,9 +1258,9 @@ In this chapter, we take the reversed perspective. We list various shapes of dec } let bookInfos = try Book - .annotated(withRequired: Book.author.select( - Column("name").forKey("authorName"), - Column("country"))) + .annotated(withRequired: Book.author.select { + [$0.name.forKey("authorName"), $0.country] + }) .asRequest(of: BookInfo.self) .fetchAll(db) ``` @@ -1288,7 +1290,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec } let bookInfos = try Book - .including(optional: Book.author.select(Column("name"), Column("country"))) + .including(optional: Book.author.select { [$0.name, $0.country] }) .asRequest(of: BookInfo.self) .fetchAll(db) ``` @@ -1303,9 +1305,9 @@ In this chapter, we take the reversed perspective. We list various shapes of dec } let bookInfos = try Book - .annotated(withOptional: Book.author.select( - Column("name").forKey("authorName"), - Column("country"))) + .annotated(withOptional: Book.author.select { + [$0.name.forKey("authorName"), $0.country] + }) .asRequest(of: BookInfo.self) .fetchAll(db) ``` @@ -1335,7 +1337,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec } let authorInfos = try Author - .including(all: Author.books.select(Column("title"), Column("year"))) + .including(all: Author.books.select { [$0.title, $0.year] }) .asRequest(of: AuthorInfo.self) .fetchAll(db) ``` @@ -1348,7 +1350,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec let authorInfos = try Author .including(all: Author.books - .select(Column("title")) + .select(\.title) .forKey("bookTitles")) .asRequest(of: AuthorInfo.self) .fetchAll(db) @@ -1462,7 +1464,7 @@ The `filter(_:)`, `filter(id:)`, `filter(ids:)`, `filter(key:)` and `filter(keys // FROM book // JOIN person ON person.id = book.authorId // AND person.countryCode = 'FR' -let frenchAuthor = Book.author.filter(Column("countryCode") == "FR") +let frenchAuthor = Book.author.filter { $0.countryCode == "FR" } let request = Book.joining(required: frenchAuthor) // This request feeds the Book record: @@ -1476,10 +1478,10 @@ The one below fetches all authors along with their novels and poems: ```swift let request = Author .including(all: Author.book - .filter(Column("kind") == "novel") + .filter { $0.kind == "novel" } .forKey("novels")) .including(all: Author.book - .filter(Column("kind") == "poems") + .filter { $0.kind == "poems" } .forKey("poems")) // This request can feed the following record: @@ -1510,7 +1512,7 @@ The `order()` method, that you already know for [sorting simple requests](../REA // FROM book // JOIN person ON person.id = book.authorId // ORDER BY person.name -let sortedAuthor = Book.author.order(Column("name")) +let sortedAuthor = Book.author.order(\.name) let request = Book.including(required: sortedAuthor) ``` @@ -1521,10 +1523,10 @@ When you sort both the base record and the associated record, the request is sor // FROM book // JOIN person ON person.id = book.authorId // ORDER BY book.publishDate DESC, person.name -let sortedAuthor = Book.author.order(Column("name")) +let sortedAuthor = Book.author.order(\.name) let request = Book .including(required: sortedAuthor) - .order(Column("publishDate").desc) + .order(\.publishDate.desc) ``` **There are more sorting options:** @@ -1561,7 +1563,7 @@ The `Team.players` association is ordered by position, so that all team players ```swift extension Team { - static let players = hasMany(Player.self).order(Column("position")) + static let players = hasMany(Player.self).order(\.position) var players: QueryInterfaceRequest { request(for: Team.players) @@ -1593,7 +1595,7 @@ Again, the `Team.players` association is ordered by position, so that all team p ```swift extension Team { - static let playerRoles = hasMany(PlayerRole.self).order(Column("position")) + static let playerRoles = hasMany(PlayerRole.self).order(\.position) static let players = hasMany(Player.self, through: playerRoles, using: PlayerRole.player) @@ -1625,9 +1627,9 @@ let teamInfos = try Team // Custom ordering let team: Team = ... -let players = try team.players.order(Column("name")).fetchAll(db) +let players = try team.players.order(\.name).fetchAll(db) let teamInfos = try Team - .including(all: Team.players.order(Column("name"))) + .including(all: Team.players.order(\.name)) .asRequest(of: TeamInfo.self) .fetchAll(db) ``` @@ -1653,7 +1655,7 @@ To specify the selection in a specific request, use the `select` method: // SELECT book.*, author.id, author.name // FROM book // JOIN author ON author.id = book.authorId -let restrictedAuthor = Book.author.select(Column("id"), Column("name")) +let restrictedAuthor = Book.author.select { [$0.id, $0.name] } let request = Book.including(required: restrictedAuthor) ``` @@ -1675,7 +1677,7 @@ Associations support more refinements: } let distinctBookKinds = Author.books - .select(Column("kind")) + .select(\.kind) .distinct() .forKey("bookKinds") @@ -1701,10 +1703,8 @@ Associations support more refinements: } let bookKindInfos = Author.books - .select( - Column("kind"), - max(Column("year")).forKey("maxYear")) - .group(Column("kind")) + .select { [$0.kind, max($0.year).forKey("maxYear")] } + .group(\.kind) .forKey("bookKindInfos") let authorInfos: [AuthorInfo] = try Author @@ -1774,7 +1774,7 @@ Let's first see a wrong way to do it: // WHERE book.publishDate >= book.deathDate let request = Book .joining(required: Book.author) - .filter(Column("publishDate") >= Column("deathDate")) + .filter { $0.publishDate >= $0.deathDate } ``` When executed, we'll get a DatabaseError of code 1, "no such column: book.deathDate". @@ -1784,21 +1784,35 @@ That is because the "deathDate" column has been used for filtering books, when i To fix this error, we need a **table alias**: ```swift -let authorAlias = TableAlias() +let authorAlias = TableAlias() ``` We modify the `Book.author` association so that it uses this table alias, and we use the table alias to qualify author columns where needed: ```swift -// SELECT book.* -// FROM book -// JOIN person ON person.id = book.authorId -// WHERE book.publishDate >= person.deathDate +// Swift 6.1 +// +// > SELECT book.* +// > FROM book +// > JOIN person ON person.id = book.authorId +// > WHERE book.publishDate >= person.deathDate let request = Book .joining(required: Book.author.aliased(authorAlias)) - .filter(Column("publishDate") >= authorAlias[Column("deathDate")]) + .filter { $0.publishDate >= authorAlias.deathDate } + +// Swift 6.0 +// +// > SELECT book.* +// > FROM book +// > JOIN person ON person.id = book.authorId +// > WHERE book.publishDate >= person.deathDate +let request = Book + .joining(required: Book.author.aliased(authorAlias)) + .filter { $0.publishDate >= authorAlias[Author.Columns.deathDate] } ``` +Note that Swift 6.1 is required for the short syntac `alias.column`. From now on, we will only give examples in Swift 6.1. + **Table aliases** can also improve control over the ordering of request results. In the example below, we override the [default ordering](#sorting-associations) of associated records by sorting on author names first: ```swift @@ -1808,7 +1822,7 @@ let request = Book // ORDER BY person.name, book.publishDate let request = Book .joining(required: Book.author.aliased(authorAlias)) - .order(authorAlias[Column("name")], Column("publishDate")) + .order { [authorAlias.name, $0.publishDate] } ``` **Table aliases** can be given a name. This name is guaranteed to be used as the table alias in the SQL query. This guarantee lets you write SQL snippets when you need it: @@ -1819,8 +1833,8 @@ let request = Book // JOIN person a ON a.id = b.authorId // AND a.countryCode = 'FR' // WHERE b.publishDate >= a.deathDate -let bookAlias = TableAlias(name: "b") -let authorAlias = TableAlias(name: "a") +let bookAlias = TableAlias(name: "b") +let authorAlias = TableAlias(name: "a") let request = Book.aliased(bookAlias) .joining(required: Book.author.aliased(authorAlias) .filter(sql: "a.countryCode = ?", arguments: ["FR"])) @@ -1840,11 +1854,11 @@ let request = Book.aliased(bookAlias) > > ```swift > // NOT IMPLEMENTED: loading all authors along with their posthumous books -> let authorAlias = TableAlias() +> let authorAlias = TableAlias() > let request = Author > .aliased(authorAlias) > .including(all: Author.books -> .filter(Column("publishDate") >= authorAlias[Column("deathDate")])) +> .filter { $0.publishDate >= authorAlias.deathDate }) > ``` @@ -1906,7 +1920,7 @@ For example, we can start by defining base requests as extensions to the [Deriva extension DerivableRequest { /// Filters authors by country func filter(country: String) -> Self { - filter(Column("country") == country) + filter { $0.country == country } } } @@ -1919,12 +1933,13 @@ extension DerivableRequest { /// Order books by author name and then book title func orderedByAuthorNameAndYear() -> Self { - let authorAlias = TableAlias() + let authorAlias = TableAlias() return self .joining(optional: Book.author.aliased(authorAlias)) - .order( - authorAlias[Column("name")].collating(.localizedCaseInsensitiveCompare), - Column("year")) + .order { [ + authorAlias.name.collating(.localizedCaseInsensitiveCompare), + $0.year, + ] } } } ``` @@ -2065,7 +2080,7 @@ Keys can also be customized with the `forKey` method: ```swift extension Author { static let novels = books - .filter(Column("kind") == "novel") + .filter { $0.kind == "novel" } .forKey("novels") } Author.including(all: Author.novels) // association key "novels" @@ -2290,7 +2305,7 @@ let author: Author = ... let bookCount = try author.books.fetchCount(db) // Int // The year of the most recent book by this author -let request = author.books.select(max(yearColumn)) +let request = author.books.select { max($0.year) } let maxBookYear = try Int.fetchOne(db, request) // Int? ``` @@ -2361,7 +2376,7 @@ struct AuthorInfo: Decodable, FetchableRecord { // GROUP BY author.id let request = Author.annotated(with: Author.books.count, - Author.books.max(Column("year"))) + Author.books.max(\.year)) let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) @@ -2378,13 +2393,13 @@ The default name is built from the aggregating method, the **[association key](# | Method | Association Key | Aggregated Column | Aggregate name | | ------ | --------------- | ----------------- | -------------- | -| `Author.books.isEmpty`. | `books` | - | `hasNoBook` | -| `Author.books.count`. | `books` | - | `bookCount` | -| `Author.books.min(Column("year"))` | `books` | `year` | `minBookYear` | -| `Author.books.max(Column("year"))` | `books` | `year` | `maxBookYear` | -| `Author.books.average(Column("price"))` | `books` | `price` | `averageBookPrice` | -| `Author.books.sum(Column("awards"))` | `books` | `awards` | `bookAwardsSum` | -| `Author.books.total(Column("awards"))` | `books` | `awards` | `bookAwardsSum` ¹ | +| `Author.books.isEmpty`. | `books` | - | `hasNoBook` | +| `Author.books.count`. | `books` | - | `bookCount` | +| `Author.books.min(\.year)` | `books` | `year` | `minBookYear` | +| `Author.books.max(\.year)` | `books` | `year` | `maxBookYear` | +| `Author.books.average(\.price)` | `books` | `price` | `averageBookPrice` | +| `Author.books.sum(\.awards)` | `books` | `awards` | `bookAwardsSum` | +| `Author.books.total((\.awards))` | `books` | `awards` | `bookAwardsSum` ¹ | ¹ The default name of the `total` aggregate has a `Sum` suffix, just like the `sum` aggregate. Both compute sums, one with the `SUM` SQL function, the other with `TOTAL`. See [SQLite documentation](https://www.sqlite.org/lang_aggfunc.html#sumunc) for the difference between these aggregate functions. @@ -2513,7 +2528,7 @@ The `having(_:)` method filters a request according to an aggregated value. You ```swift - let request = Author.having(Author.books.max(Column("year")) >= 2010) + let request = Author.having(Author.books.max(\.year) >= 2010) ``` - Authors who wrote at least one book of kind "novel": @@ -2532,7 +2547,7 @@ The `having(_:)` method filters a request according to an aggregated value. You ```swift - let novels = Author.books.filter(Column("kind") == "novel") + let novels = Author.books.filter { $0.kind == "novel" } let request = Author.having(novels.isEmpty == false) ``` @@ -2618,7 +2633,7 @@ Aggregates can be modified and combined with Swift operators: ```swift - let request = Author.having(Author.books.max(Column("year")) >= 2010) + let request = Author.having(Author.books.max(\.year) >= 2010) ``` - Arithmetic operators `+`, `-`, `*`, `/` @@ -2658,7 +2673,7 @@ Aggregates can be modified and combined with Swift operators: ```swift - let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0) + let request = Team.annotated(with: Team.players.min(\.score) ?? 0) ``` - SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions: @@ -2676,7 +2691,7 @@ Aggregates can be modified and combined with Swift operators: ```swift - let request = Team.annotated(with: abs(Team.players.max(Column("score")))) + let request = Team.annotated(with: abs(Team.players.max(\.score))) ``` ### Isolation of Multiple Aggregates @@ -2713,8 +2728,8 @@ In the example below, we use compute two aggregates from the same association `A } let request = Author.annotated(with: - Author.books.min(Column("year")), // association key "books" - Author.books.max(Column("year"))) // association key "books" + Author.books.min(\.year), // association key "books" + Author.books.max(\.year)) // association key "books" let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request) ``` @@ -2784,11 +2799,11 @@ But in the following example, we use the same association `Author.books` twice, } let novelCount = Author.books - .filter(Column("kind") == "novel") + .filter { $0.kind == "novel" } .forKey("novels") // association key "novels" .count let theatrePlayCount = Author.books - .filter(Column("kind") == "theatrePlay") + .filter { $0.kind == "theatrePlay" } .forKey("theatrePlays") // association key "theatrePlays" .count let request = Author.annotated(with: novelCount, theatrePlayCount) @@ -2815,11 +2830,11 @@ But in the following example, we use the same association `Author.books` twice, ```swift // WRONG: not counting distinct sets of associated books let novelCount = Author.books // association key "books" - .filter(Column("kind") == "novel") + .filter { $0.kind == "novel" } .count .forKey("novelCount") let theatrePlayCount = Author.books // association key "books" - .filter(Column("kind") == "theatrePlay") + .filter { $0.kind == "theatrePlay" } .count .forKey("theatrePlayCount") let request = Author.annotated(with: novelCount, theatrePlayCount) @@ -2849,11 +2864,11 @@ Those methods are defined on extensions to the `DerivableRequest` protocol: ```swift extension DerivableRequest { func filter(country: String) -> Self { - filter(Column("country") == country) + filter { $0.country == country } } func orderedByName() -> Self { - order(Column("name").collating(.localizedCaseInsensitiveCompare)) + order { $0.name.collating(.localizedCaseInsensitiveCompare) } } } @@ -2884,11 +2899,11 @@ See [Recommended Practices for Designing Record Types] for more information. ```swift // NOT IMPLEMENTED: loading all authors along with their posthumous books - let authorAlias = TableAlias() + let authorAlias = TableAlias() let request = Author .aliased(authorAlias) .including(all: Author.books - .filter(Column("publishDate") >= authorAlias[Column("deathDate")])) + .filter { $0.publishDate >= authorAlias.deathDate }) ``` - **You can't use the `including(all:)` method with a [HasMany] and a [HasManyThrough] associations that share the same base association in the same request**: @@ -2965,7 +2980,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 @@ -3000,17 +3015,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 -[Record class]: ../README.md#record-class [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 diff --git a/Documentation/Combine.md b/Documentation/Combine.md index d4e114cc8..27bfd59e4 100644 --- a/Documentation/Combine.md +++ b/Documentation/Combine.md @@ -226,11 +226,11 @@ This publisher has the same behavior as ValueObservation: - It notifies an initial value before the eventual changes. - It may coalesce subsequent changes into a single notification. -- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also. +- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also. - It only completes when it is cancelled. - By default, it notifies the initial value, as well as eventual changes and errors, on the main thread, asynchronously. - This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservationscheduler). + This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservationscheduler). For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the publisher is subscribed. It can help your application update the user interface without having to wait for any asynchronous notifications: @@ -332,7 +332,7 @@ let hallOfFamePublisher = ValueObservation // 2nd request let bestPlayers = try Player - .order(Column("score").desc) + .order(\.score.desc) .limit(10) .fetchAll(db) @@ -358,7 +358,7 @@ let totalPlayerCountPublisher = ValueObservation // OK let bestPlayerPublisher = ValueObservation .tracking(Player - .order(Column("score").desc) + .order(\.score.desc) .limit(10) .fetchAll) .publisher(in: dbQueue) @@ -382,23 +382,23 @@ let cancellable = hallOfFamePublisher.sink( [Usage]: #usage [Asynchronous Database Access]: #asynchronous-database-access [Combine]: https://developer.apple.com/documentation/combine -[Database Changes Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation +[Database Changes Observation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation [Database Observation]: #database-observation [Combine and Data Consistency]: #combine-and-data-consistency -[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseregionobservation +[DatabaseRegionObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseregionobservation [Demo Application]: DemoApps/GRDBCombineDemo/README.md [SQLite]: http://sqlite.org -[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation -[SharedValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sharedvalueobservation +[ValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation +[SharedValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/sharedvalueobservation [`DatabaseRegionObservation.publisher(in:)`]: #databaseregionobservationpublisherin [`ValueObservation.publisher(in:scheduling:)`]: #valueobservationpublisherinscheduling [`SharedValueObservation.publisher()`]: #sharedvalueobservationpublisher [`readPublisher(receiveOn:value:)`]: #databasereaderreadpublisherreceiveonvalue [`writePublisher(receiveOn:updates:)`]: #databasewriterwritepublisherreceiveonupdates [`writePublisher(receiveOn:updates:thenRead:)`]: #databasewriterwritepublisherreceiveonupdatesthenread -[`migratePublisher(_:receiveOn:)`]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator/migratepublisher(_:receiveon:) +[`migratePublisher(_:receiveOn:)`]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator/migratepublisher(_:receiveon:) [configured]: ../README.md#databasepool-configuration -[database pool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool -[database queue]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue -[database snapshot]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesnapshot +[database pool]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool +[database queue]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue +[database snapshot]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesnapshot [scheduler]: https://developer.apple.com/documentation/combine/scheduler diff --git a/Documentation/CommonTableExpressions.md b/Documentation/CommonTableExpressions.md index 4f447ad2b..42277c8ec 100644 --- a/Documentation/CommonTableExpressions.md +++ b/Documentation/CommonTableExpressions.md @@ -31,7 +31,7 @@ The CTE request can be provided as a [query interface request]: // WITH playerName AS (SELECT name FROM player) ... let playerNameCTE = CommonTableExpression( named: "playerName", - request: Player.select(Column("name"))) + request: Player.select(\.name)) ``` You can feed a CTE with raw SQL as well (second and third examples use [SQL Interpolation]): @@ -123,7 +123,7 @@ And we can then filter the `player` table with a subquery: // WHERE name = (SELECT * FROM playerName) let request = Player .with(playerNameCTE) - .filter(Column("name") == playerNameCTE.all()) + .filter { $0.name == playerNameCTE.all() } ``` > **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request. @@ -167,13 +167,13 @@ Common table expressions can also be used as subqueries, when you update or dele // UPDATE player SET name = (SELECT * FROM playerName) try Player .with(playerNameCTE) - .updateAll(db, Column("name").set(to: playerNameCTE.all())) + .updateAll(db) { $0.name.set(to: playerNameCTE.all()) } // WITH playerName AS (SELECT 'O''Brien') // DELETE FROM player WHERE name = (SELECT * FROM playerName) try Player .with(playerNameCTE) - .filter(Column("name") == playerNameCTE.all()) + .filter { $0.name == playerNameCTE.all() } .deleteAll(db) ``` @@ -281,9 +281,15 @@ struct Chat: Codable, FetchableRecord, PersistableRecord { } struct Message: Codable, FetchableRecord, PersistableRecord { - var chatID: Int64 + var chatId: Int64 var date: Date ... + + enum Columns { + static let chatId = Column("chatId") + static let date = Column("date") + ... + } } ``` @@ -315,8 +321,8 @@ We start by defining the CTE request, which loads the latest messages of all cha ```swift // SELECT *, MAX(date) FROM message GROUP BY chatID let latestMessageRequest = Message - .annotated(with: max(Column("date"))) - .group(Column("chatID")) + .annotated { max($0.date) } + .group(\.chatId) ``` We can now define the CTE for the latest messages: @@ -324,7 +330,7 @@ We can now define the CTE for the latest messages: ```swift // WITH latestMessage AS // (SELECT *, MAX(date) FROM message GROUP BY chatID) -let latestMessageCTE = CommonTableExpression( +let latestMessageCTE = CommonTableExpression( named: "latestMessage", request: latestMessageRequest) ``` @@ -337,9 +343,9 @@ The association from a chat to its latest message follows: let latestMessage = Chat.association( to: latestMessageCTE, on: { chat, latestMessage in - chat[Column("id")] == latestMessage[Column("chatID")] + chat.id == latestMessage.chatId }) - .order(Column("date").desc) + .order(\.date.desc) ``` The final request can now be defined: diff --git a/Documentation/Concurrency.md b/Documentation/Concurrency.md index 04278db62..9d6b454d1 100644 --- a/Documentation/Concurrency.md +++ b/Documentation/Concurrency.md @@ -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). diff --git a/Documentation/CustomSQLiteBuilds.md b/Documentation/CustomSQLiteBuilds.md index c49092d47..f3903ed46 100644 --- a/Documentation/CustomSQLiteBuilds.md +++ b/Documentation/CustomSQLiteBuilds.md @@ -3,9 +3,9 @@ Custom SQLite Builds By default, GRDB uses the version of SQLite that ships with the target operating system. -**You can build GRDB with a custom build of [SQLite 3.44.0](https://www.sqlite.org/changes.html).** +**You can build GRDB with a custom build of [SQLite 3.47.2](https://www.sqlite.org/changes.html).** -A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver). +A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver). GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need. @@ -21,7 +21,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal 2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`. - It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool). + It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool). 3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory. diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.pbxproj deleted file mode 100644 index ceb3cb987..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.pbxproj +++ /dev/null @@ -1,609 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 54; - objects = { - -/* Begin PBXBuildFile section */ - 56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */; }; - 56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */; }; - 56519DCA274FC8E900ED16D8 /* GRDBQuery in Frameworks */ = {isa = PBXBuildFile; productRef = 56519DC9274FC8E900ED16D8 /* GRDBQuery */; }; - 5671723A261B23C800423B6F /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717239261B23C800423B6F /* PlayerList.swift */; }; - 56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717251261B334D00423B6F /* PlayerRequestTests.swift */; }; - 567C3E1A2520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E192520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift */; }; - 567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */; }; - 567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */; }; - 567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E532520B75C0011F6E9 /* Player.swift */; }; - 567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E542520B75C0011F6E9 /* Persistence.swift */; }; - 567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */; }; - 567C3E622520B75D0011F6E9 /* AppView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* AppView.swift */; }; - 567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */; }; - 567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */; }; - 567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E652520B7880011F6E9 /* AppDatabase.swift */; }; - 567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E752520BB650011F6E9 /* Localizable.stringsdict */; }; - 567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; }; - 56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; }; - 56F8A13527359A5A0011ACBE /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56F8A13427359A5A0011ACBE /* GRDB */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 567C3E152520B6DE0011F6E9; - remoteInfo = GRDBAsyncDemo; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 567C3E502520B70E0011F6E9 /* Embed Frameworks */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - ); - name = "Embed Frameworks"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 56026C9825B8A7D000D1DF3F /* GRDBAsyncDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBAsyncDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 56026C9C25B8A7D000D1DF3F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = ""; }; - 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = ""; }; - 56717239261B23C800423B6F /* PlayerList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = ""; }; - 56717251261B334D00423B6F /* PlayerRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequestTests.swift; sourceTree = ""; }; - 567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBAsyncDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 567C3E192520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBAsyncDemoApp.swift; sourceTree = ""; }; - 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; - 567C3E222520B6DF0011F6E9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 567C3E532520B75C0011F6E9 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; - 567C3E542520B75C0011F6E9 /* Persistence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = ""; }; - 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormView.swift; sourceTree = ""; }; - 567C3E5A2520B75C0011F6E9 /* AppView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppView.swift; sourceTree = ""; }; - 567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationView.swift; sourceTree = ""; }; - 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionView.swift; sourceTree = ""; }; - 567C3E652520B7880011F6E9 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; - 567C3E762520BB650011F6E9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = ""; }; - 567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = ""; }; - 56F8A12E27359A350011ACBE /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 56026C9525B8A7D000D1DF3F /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 567C3E132520B6DE0011F6E9 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 56519DCA274FC8E900ED16D8 /* GRDBQuery in Frameworks */, - 56F8A13527359A5A0011ACBE /* GRDB in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 56026C9925B8A7D000D1DF3F /* GRDBAsyncDemoTests */ = { - isa = PBXGroup; - children = ( - 56026C9C25B8A7D000D1DF3F /* Info.plist */, - 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */, - 56717251261B334D00423B6F /* PlayerRequestTests.swift */, - 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */, - ); - path = GRDBAsyncDemoTests; - sourceTree = ""; - }; - 56185BC125B8047D00B9C30F /* Resources */ = { - isa = PBXGroup; - children = ( - 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */, - 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */, - 567C3E752520BB650011F6E9 /* Localizable.stringsdict */, - ); - path = Resources; - sourceTree = ""; - }; - 567C3E0D2520B6DE0011F6E9 = { - isa = PBXGroup; - children = ( - 567C3E182520B6DE0011F6E9 /* GRDBAsyncDemo */, - 56026C9925B8A7D000D1DF3F /* GRDBAsyncDemoTests */, - 567C3E172520B6DE0011F6E9 /* Products */, - 567C3E4D2520B70E0011F6E9 /* Frameworks */, - 56F8A12E27359A350011ACBE /* GRDB.swift */, - ); - sourceTree = ""; - }; - 567C3E172520B6DE0011F6E9 /* Products */ = { - isa = PBXGroup; - children = ( - 567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */, - 56026C9825B8A7D000D1DF3F /* GRDBAsyncDemoTests.xctest */, - ); - name = Products; - sourceTree = ""; - }; - 567C3E182520B6DE0011F6E9 /* GRDBAsyncDemo */ = { - isa = PBXGroup; - children = ( - 567C3E222520B6DF0011F6E9 /* Info.plist */, - 567C3E652520B7880011F6E9 /* AppDatabase.swift */, - 567C3E192520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift */, - 567C3E542520B75C0011F6E9 /* Persistence.swift */, - 567C3E532520B75C0011F6E9 /* Player.swift */, - 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */, - 567C3E1F2520B6DF0011F6E9 /* Preview Content */, - 56185BC125B8047D00B9C30F /* Resources */, - 567C3E582520B75C0011F6E9 /* Views */, - ); - path = GRDBAsyncDemo; - sourceTree = ""; - }; - 567C3E1F2520B6DF0011F6E9 /* Preview Content */ = { - isa = PBXGroup; - children = ( - 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */, - ); - path = "Preview Content"; - sourceTree = ""; - }; - 567C3E4D2520B70E0011F6E9 /* Frameworks */ = { - isa = PBXGroup; - children = ( - ); - name = Frameworks; - sourceTree = ""; - }; - 567C3E582520B75C0011F6E9 /* Views */ = { - isa = PBXGroup; - children = ( - 567C3E5A2520B75C0011F6E9 /* AppView.swift */, - 567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */, - 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */, - 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */, - 56717239261B23C800423B6F /* PlayerList.swift */, - ); - path = Views; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 56026C9725B8A7D000D1DF3F /* GRDBAsyncDemoTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoTests" */; - buildPhases = ( - 56026C9425B8A7D000D1DF3F /* Sources */, - 56026C9525B8A7D000D1DF3F /* Frameworks */, - 56026C9625B8A7D000D1DF3F /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */, - ); - name = GRDBAsyncDemoTests; - productName = GRDBAsyncDemoTests; - productReference = 56026C9825B8A7D000D1DF3F /* GRDBAsyncDemoTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; - 567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */ = { - isa = PBXNativeTarget; - buildConfigurationList = 567C3E252520B6DF0011F6E9 /* Build configuration list for PBXNativeTarget "GRDBAsyncDemo" */; - buildPhases = ( - 567C3E122520B6DE0011F6E9 /* Sources */, - 567C3E132520B6DE0011F6E9 /* Frameworks */, - 567C3E142520B6DE0011F6E9 /* Resources */, - 567C3E502520B70E0011F6E9 /* Embed Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - 56F8A13127359A540011ACBE /* PBXTargetDependency */, - ); - name = GRDBAsyncDemo; - packageProductDependencies = ( - 56F8A13427359A5A0011ACBE /* GRDB */, - 56519DC9274FC8E900ED16D8 /* GRDBQuery */, - ); - productName = GRBCombineDemo; - productReference = 567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 567C3E0E2520B6DE0011F6E9 /* Project object */ = { - isa = PBXProject; - attributes = { - BuildIndependentTargetsInParallel = YES; - LastSwiftUpdateCheck = 1250; - LastUpgradeCheck = 1200; - TargetAttributes = { - 56026C9725B8A7D000D1DF3F = { - CreatedOnToolsVersion = 12.3; - TestTargetID = 567C3E152520B6DE0011F6E9; - }; - 567C3E152520B6DE0011F6E9 = { - CreatedOnToolsVersion = 12.0; - }; - }; - }; - buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBAsyncDemo" */; - compatibilityVersion = "Xcode 12.0"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 567C3E0D2520B6DE0011F6E9; - packageReferences = ( - 56519DC8274FC8E900ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */, - ); - productRefGroup = 567C3E172520B6DE0011F6E9 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */, - 56026C9725B8A7D000D1DF3F /* GRDBAsyncDemoTests */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 56026C9625B8A7D000D1DF3F /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 567C3E142520B6DE0011F6E9 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */, - 567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */, - 567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */, - 567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 56026C9425B8A7D000D1DF3F /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */, - 56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */, - 56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 567C3E122520B6DE0011F6E9 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */, - 567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */, - 56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */, - 5671723A261B23C800423B6F /* PlayerList.swift in Sources */, - 567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */, - 567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */, - 567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */, - 567C3E622520B75D0011F6E9 /* AppView.swift in Sources */, - 567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */, - 567C3E1A2520B6DE0011F6E9 /* GRDBAsyncDemoApp.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */; - targetProxy = 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */; - }; - 56F8A13127359A540011ACBE /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - productRef = 56F8A13027359A540011ACBE /* GRDB */; - }; -/* End PBXTargetDependency section */ - -/* Begin PBXVariantGroup section */ - 567C3E752520BB650011F6E9 /* Localizable.stringsdict */ = { - isa = PBXVariantGroup; - children = ( - 567C3E762520BB650011F6E9 /* en */, - ); - name = Localizable.stringsdict; - sourceTree = ""; - }; - 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 567C3E782520BB650011F6E9 /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 56026C9F25B8A7D000D1DF3F /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CODE_SIGN_STYLE = Automatic; - INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBAsyncDemoTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBAsyncDemo.app/GRDBAsyncDemo"; - }; - name = Debug; - }; - 56026CA025B8A7D000D1DF3F /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CODE_SIGN_STYLE = Automatic; - INFOPLIST_FILE = GRDBAsyncDemoTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBAsyncDemoTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBAsyncDemo.app/GRDBAsyncDemo"; - }; - name = Release; - }; - 567C3E232520B6DF0011F6E9 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 15.0; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 567C3E242520B6DF0011F6E9 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 15.0; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 567C3E262520B6DF0011F6E9 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; - CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_ASSET_PATHS = "\"GRDBAsyncDemo/Preview Content\""; - DEVELOPMENT_TEAM = ""; - ENABLE_PREVIEWS = YES; - INFOPLIST_FILE = GRDBAsyncDemo/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 15.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBAsyncDemo; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = 1; - }; - name = Debug; - }; - 567C3E272520B6DF0011F6E9 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; - CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_ASSET_PATHS = "\"GRDBAsyncDemo/Preview Content\""; - DEVELOPMENT_TEAM = ""; - ENABLE_PREVIEWS = YES; - INFOPLIST_FILE = GRDBAsyncDemo/Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 15.0; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBAsyncDemo; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = 1; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 56026C9F25B8A7D000D1DF3F /* Debug */, - 56026CA025B8A7D000D1DF3F /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBAsyncDemo" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 567C3E232520B6DF0011F6E9 /* Debug */, - 567C3E242520B6DF0011F6E9 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 567C3E252520B6DF0011F6E9 /* Build configuration list for PBXNativeTarget "GRDBAsyncDemo" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 567C3E262520B6DF0011F6E9 /* Debug */, - 567C3E272520B6DF0011F6E9 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - -/* Begin XCRemoteSwiftPackageReference section */ - 56519DC8274FC8E900ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */ = { - isa = XCRemoteSwiftPackageReference; - repositoryURL = "https://github.com/groue/GRDBQuery"; - requirement = { - kind = upToNextMajorVersion; - minimumVersion = 0.6.0; - }; - }; -/* End XCRemoteSwiftPackageReference section */ - -/* Begin XCSwiftPackageProductDependency section */ - 56519DC9274FC8E900ED16D8 /* GRDBQuery */ = { - isa = XCSwiftPackageProductDependency; - package = 56519DC8274FC8E900ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */; - productName = GRDBQuery; - }; - 56F8A13027359A540011ACBE /* GRDB */ = { - isa = XCSwiftPackageProductDependency; - productName = GRDB; - }; - 56F8A13427359A5A0011ACBE /* GRDB */ = { - isa = XCSwiftPackageProductDependency; - productName = GRDB; - }; -/* End XCSwiftPackageProductDependency section */ - }; - rootObject = 567C3E0E2520B6DE0011F6E9 /* Project object */; -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d981003..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved deleted file mode 100644 index 5a507d565..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ /dev/null @@ -1,14 +0,0 @@ -{ - "pins" : [ - { - "identity" : "grdbquery", - "kind" : "remoteSourceControl", - "location" : "https://github.com/groue/GRDBQuery", - "state" : { - "revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6", - "version" : "0.6.0" - } - } - ], - "version" : 2 -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme deleted file mode 100644 index aeb65e487..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/xcshareddata/xcschemes/GRDBAsyncDemo.xcscheme +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift deleted file mode 100644 index e19cc7af7..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/AppDatabase.swift +++ /dev/null @@ -1,235 +0,0 @@ -import Foundation -import GRDB -import os.log - -/// A database of players. -/// -/// You create an `AppDatabase` with a connection to an SQLite database -/// (see ). -/// -/// Create those connections with a configuration returned from -/// `AppDatabase/makeConfiguration(_:)`. -/// -/// For example: -/// -/// ```swift -/// // Create an in-memory AppDatabase -/// let config = AppDatabase.makeConfiguration() -/// let dbQueue = try DatabaseQueue(configuration: config) -/// let appDatabase = try AppDatabase(dbQueue) -/// ``` -struct AppDatabase { - /// Creates an `AppDatabase`, and makes sure the database schema - /// is ready. - /// - /// - important: Create the `DatabaseWriter` with a configuration - /// returned by ``makeConfiguration(_:)``. - init(_ dbWriter: any DatabaseWriter) throws { - self.dbWriter = dbWriter - try migrator.migrate(dbWriter) - } - - /// Provides access to the database. - /// - /// Application can use a `DatabasePool`, while SwiftUI previews and tests - /// can use a fast in-memory `DatabaseQueue`. - /// - /// See - private let dbWriter: any DatabaseWriter -} - -// MARK: - Database Configuration - -extension AppDatabase { - private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL") - - /// Returns a database configuration suited for `PlayerRepository`. - /// - /// SQL statements are logged if the `SQL_TRACE` environment variable - /// is set. - /// - /// - parameter base: A base configuration. - public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration { - var config = base - - // An opportunity to add required custom SQL functions or - // collations, if needed: - // config.prepareDatabase { db in - // db.add(function: ...) - // } - - // Log SQL statements if the `SQL_TRACE` environment variable is set. - // See - if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil { - config.prepareDatabase { db in - db.trace { - // It's ok to log statements publicly. Sensitive - // information (statement arguments) are not logged - // unless config.publicStatementArguments is set - // (see below). - os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0)) - } - } - } - -#if DEBUG - // Protect sensitive information by enabling verbose debugging in - // DEBUG builds only. - // See - config.publicStatementArguments = true -#endif - - return config - } -} - -// MARK: - Database Migrations - -extension AppDatabase { - /// The DatabaseMigrator that defines the database schema. - /// - /// See - private var migrator: DatabaseMigrator { - var migrator = DatabaseMigrator() - -#if DEBUG - // Speed up development by nuking the database when migrations change - // See - migrator.eraseDatabaseOnSchemaChange = true -#endif - - migrator.registerMigration("createPlayer") { db in - // Create a table - // See - try db.create(table: "player") { t in - t.autoIncrementedPrimaryKey("id") - t.column("name", .text).notNull() - t.column("score", .integer).notNull() - } - } - - // Migrations for future application versions will be inserted here: - // migrator.registerMigration(...) { db in - // ... - // } - - return migrator - } -} - -// MARK: - Database Access: Writes -// The write methods execute invariant-preserving database transactions. - -extension AppDatabase { - /// A validation error that prevents some players from being saved into - /// the database. - enum ValidationError: LocalizedError { - case missingName - - var errorDescription: String? { - switch self { - case .missingName: - return "Please provide a name" - } - } - } - - /// Saves (inserts or updates) a player. When the method returns, the - /// player is present in the database, and its id is not nil. - func savePlayer(_ player: inout Player) async throws { - if player.name.isEmpty { - throw ValidationError.missingName - } - player = try await dbWriter.write { [player] db in - try player.saved(db) - } - } - - /// Delete the specified players - func deletePlayers(ids: [Int64]) async throws { - try await dbWriter.write { db in - _ = try Player.deleteAll(db, ids: ids) - } - } - - /// Delete all players - func deleteAllPlayers() async throws { - try await dbWriter.write { db in - _ = try Player.deleteAll(db) - } - } - - /// Refresh all players (by performing some random changes, for demo purpose). - func refreshPlayers() async throws { - try await dbWriter.write { db in - if try Player.all().isEmpty(db) { - // When database is empty, insert new random players - try createRandomPlayers(db) - } else { - // Insert a player - if Bool.random() { - _ = try Player.makeRandom().inserted(db) // insert but ignore inserted id - } - - // Delete a random player - if Bool.random() { - try Player.order(sql: "RANDOM()").limit(1).deleteAll(db) - } - - // Update some players - for var player in try Player.fetchAll(db) where Bool.random() { - try player.updateChanges(db) { - $0.score = Player.randomScore() - } - } - } - } - } - - /// Create random players if the database is empty. - func createRandomPlayersIfEmpty() throws { - try dbWriter.write { db in - if try Player.all().isEmpty(db) { - try createRandomPlayers(db) - } - } - } - - private static let uiTestPlayers = [ - Player(id: nil, name: "Arthur", score: 5), - Player(id: nil, name: "Barbara", score: 6), - Player(id: nil, name: "Craig", score: 8), - Player(id: nil, name: "David", score: 4), - Player(id: nil, name: "Elena", score: 1), - Player(id: nil, name: "Frederik", score: 2), - Player(id: nil, name: "Gilbert", score: 7), - Player(id: nil, name: "Henriette", score: 3)] - - func createPlayersForUITests() throws { - try dbWriter.write { db in - try AppDatabase.uiTestPlayers.forEach { player in - _ = try player.inserted(db) // insert but ignore inserted id - } - } - } - - /// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`. - private func createRandomPlayers(_ db: Database) throws { - for _ in 0..<8 { - _ = try Player.makeRandom().inserted(db) // insert but ignore inserted id - } - } -} - -// MARK: - Database Access: Reads - -// This demo app does not provide any specific reading method, and instead -// gives an unrestricted read-only access to the rest of the application. -// In your app, you are free to choose another path, and define focused -// reading methods. -extension AppDatabase { - /// Provides a read-only access to the database - var reader: DatabaseReader { - dbWriter - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/GRDBAsyncDemoApp.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/GRDBAsyncDemoApp.swift deleted file mode 100644 index 0ddda97f5..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/GRDBAsyncDemoApp.swift +++ /dev/null @@ -1,40 +0,0 @@ -import GRDBQuery -import SwiftUI - -@main -struct GRDBAsyncDemoApp: App { - var body: some Scene { - WindowGroup { - AppView().environment(\.appDatabase, .shared) - } - } -} - -// MARK: - Give SwiftUI access to the database -// -// Define a new environment key that grants access to an AppDatabase. -// -// The technique is documented at -// . - -private struct AppDatabaseKey: EnvironmentKey { - static var defaultValue: AppDatabase { .empty() } -} - -extension EnvironmentValues { - var appDatabase: AppDatabase { - get { self[AppDatabaseKey.self] } - set { self[AppDatabaseKey.self] = newValue } - } -} - -// In this demo app, views observe the database with the @Query property -// wrapper, defined in the GRDBQuery package. Its documentation recommends to -// define a dedicated initializer for `appDatabase` access, so we comply: - -extension Query where Request.DatabaseContext == AppDatabase { - /// Convenience initializer for requests that feed from `AppDatabase`. - init(_ request: Request) { - self.init(request, in: \.appDatabase) - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Info.plist b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Info.plist deleted file mode 100644 index 4754bb868..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Info.plist +++ /dev/null @@ -1,50 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - LSRequiresIPhoneOS - - UIApplicationSceneManifest - - UIApplicationSupportsMultipleScenes - - - UIApplicationSupportsIndirectInputEvents - - UILaunchScreen - - UILaunchStoryboardName - LaunchScreen - UIRequiredDeviceCapabilities - - armv7 - - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - - diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift deleted file mode 100644 index 05b011578..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Persistence.swift +++ /dev/null @@ -1,77 +0,0 @@ -import Foundation -import GRDB - -extension AppDatabase { - /// The database for the application - static let shared = makeShared() - - private static func makeShared() -> AppDatabase { - do { - // Apply recommendations from - // - // - // Create the "Application Support/Database" directory if needed - let fileManager = FileManager.default - let appSupportURL = try fileManager.url( - for: .applicationSupportDirectory, in: .userDomainMask, - appropriateFor: nil, create: true) - let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true) - - // Support for tests: delete the database if requested - if CommandLine.arguments.contains("-reset") { - try? fileManager.removeItem(at: directoryURL) - } - - // Create the database folder if needed - try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true) - - // Open or create the database - let databaseURL = directoryURL.appendingPathComponent("db.sqlite") - NSLog("Database stored at \(databaseURL.path)") - let dbPool = try DatabasePool( - path: databaseURL.path, - // Use default AppDatabase configuration - configuration: AppDatabase.makeConfiguration()) - - // Create the AppDatabase - let appDatabase = try AppDatabase(dbPool) - - // Prepare the database with test fixtures if requested - if CommandLine.arguments.contains("-fixedTestData") { - try appDatabase.createPlayersForUITests() - } else { - // Otherwise, populate the database if it is empty, for better - // demo purpose. - try appDatabase.createRandomPlayersIfEmpty() - } - - return appDatabase - } catch { - // Replace this implementation with code to handle the error appropriately. - // fatalError() causes the application to generate a crash log and terminate. - // - // Typical reasons for an error here include: - // * The parent directory cannot be created, or disallows writing. - // * The database is not accessible, due to permissions or data protection when the device is locked. - // * The device is out of space. - // * The database could not be migrated to its latest schema version. - // Check the error message to determine what the actual problem was. - fatalError("Unresolved error \(error)") - } - } - - /// 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 - let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - return try! AppDatabase(dbQueue) - } - - /// Creates a database full of random players for SwiftUI previews - static func random() -> AppDatabase { - let appDatabase = empty() - try! appDatabase.createRandomPlayersIfEmpty() - return appDatabase - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift deleted file mode 100644 index 7876b049d..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Player.swift +++ /dev/null @@ -1,105 +0,0 @@ -import GRDB - -/// The Player struct. -/// -/// Identifiable conformance supports SwiftUI list animations, and type-safe -/// GRDB primary key methods. -/// Equatable conformance supports tests. -struct Player: Identifiable, Equatable { - /// The player id. - /// - /// Int64 is the recommended type for auto-incremented database ids. - /// Use nil for players that are not inserted yet in the database. - var id: Int64? - var name: String - var score: Int -} - -extension Player { - private static let names = [ - "Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David", - "Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette", - "Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl", - "Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole", - "Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul", - "Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain", - "Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann", - "Zazie", "Zoé"] - - /// Creates a new player with empty name and zero score - static func new() -> Player { - Player(id: nil, name: "", score: 0) - } - - /// Creates a new player with random name and random score - static func makeRandom() -> Player { - Player(id: nil, name: randomName(), score: randomScore()) - } - - /// Returns a random name - static func randomName() -> String { - names.randomElement()! - } - - /// Returns a random score - static func randomScore() -> Int { - 10 * Int.random(in: 0...100) - } -} - -// MARK: - Persistence - -/// Make Player a Codable Record. -/// -/// See -extension Player: Codable, FetchableRecord, MutablePersistableRecord { - // Define database columns from CodingKeys - fileprivate enum Columns { - static let name = Column(CodingKeys.name) - static let score = Column(CodingKeys.score) - } - - /// Updates a player id after it has been inserted in the database. - mutating func didInsert(_ inserted: InsertionSuccess) { - id = inserted.rowID - } -} - -// MARK: - Player Database Requests - -/// Define some player requests used by the application. -/// -/// See -extension DerivableRequest { - /// A request of players ordered by name. - /// - /// For example: - /// - /// let players: [Player] = try dbWriter.read { db in - /// try Player.all().orderedByName().fetchAll(db) - /// } - func orderedByName() -> Self { - // Sort by name in a localized case insensitive fashion - // See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison - order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare)) - } - - /// A request of players ordered by score. - /// - /// For example: - /// - /// let players: [Player] = try dbWriter.read { db in - /// try Player.all().orderedByScore().fetchAll(db) - /// } - /// let bestPlayer: Player? = try dbWriter.read { db in - /// try Player.all().orderedByScore().fetchOne(db) - /// } - func orderedByScore() -> Self { - // Sort by descending score, and then by name, in a - // localized case insensitive fashion - // See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison - order( - Player.Columns.score.desc, - Player.Columns.name.collating(.localizedCaseInsensitiveCompare)) - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/PlayerRequest.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/PlayerRequest.swift deleted file mode 100644 index 8c70aab8d..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/PlayerRequest.swift +++ /dev/null @@ -1,55 +0,0 @@ -import Combine -import GRDB -import GRDBQuery - -/// A player request can be used with the `@Query` property wrapper in order to -/// feed a view with a list of players. -/// -/// For example: -/// -/// struct MyView: View { -/// @Query(PlayerRequest(ordering: .byName)) private var players: [Player] -/// -/// var body: some View { -/// List(players) { player in ... ) -/// } -/// } -struct PlayerRequest: Queryable { - enum Ordering { - case byScore - case byName - } - - /// The ordering used by the player request. - var ordering: Ordering - - // MARK: - Queryable Implementation - - static var defaultValue: [Player] { [] } - - func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> { - // Build the publisher from the general-purpose read-only access - // granted by `appDatabase.reader`. - // Some apps will prefer to call a dedicated method of `appDatabase`. - ValueObservation - .tracking(fetchValue(_:)) - .publisher( - in: appDatabase.reader, - // The `.immediate` scheduling feeds the view right on - // subscription, and avoids an undesired animation when the - // application starts. - scheduling: .immediate) - .eraseToAnyPublisher() - } - - // This method is not required by Queryable, but it makes it easier - // to test PlayerRequest. - func fetchValue(_ db: Database) throws -> [Player] { - switch ordering { - case .byScore: - return try Player.all().orderedByScore().fetchAll(db) - case .byName: - return try Player.all().orderedByName().fetchAll(db) - } - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index 29d91251d..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "images" : [ - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "icon_20pt@2x.png", - "scale" : "2x" - }, - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "icon_20pt@3x.png", - "scale" : "3x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "icon_29pt@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "icon_29pt@3x.png", - "scale" : "3x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "icon_40pt@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "icon_40pt@3x.png", - "scale" : "3x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "icon_60pt@2x.png", - "scale" : "2x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "icon_60pt@3x.png", - "scale" : "3x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "icon_20pt.png", - "scale" : "1x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "icon_20pt@2x-1.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "icon_29pt.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "icon_29pt@2x-1.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "icon_40pt.png", - "scale" : "1x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "icon_40pt@2x-1.png", - "scale" : "2x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "icon_76pt.png", - "scale" : "1x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "icon_76pt@2x.png", - "scale" : "2x" - }, - { - "size" : "83.5x83.5", - "idiom" : "ipad", - "filename" : "icon_83.5@2x.png", - "scale" : "2x" - }, - { - "size" : "1024x1024", - "idiom" : "ios-marketing", - "filename" : "Icon.png", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon.png deleted file mode 100644 index 66b1931a1..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt.png deleted file mode 100644 index 90648b3f4..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x-1.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x-1.png deleted file mode 100644 index a077a6f49..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x-1.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x.png deleted file mode 100644 index a077a6f49..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@3x.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@3x.png deleted file mode 100644 index 600bdbd9c..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@3x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt.png deleted file mode 100644 index 8e04af0dd..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x-1.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x-1.png deleted file mode 100644 index 686e8d99e..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x-1.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x.png deleted file mode 100644 index 686e8d99e..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@3x.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@3x.png deleted file mode 100644 index 1d013c3d3..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@3x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt.png deleted file mode 100644 index a077a6f49..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x-1.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x-1.png deleted file mode 100644 index da66b9ba8..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x-1.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x.png deleted file mode 100644 index da66b9ba8..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@3x.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@3x.png deleted file mode 100644 index 59346ef4b..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@3x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@2x.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@2x.png deleted file mode 100644 index 59346ef4b..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@3x.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@3x.png deleted file mode 100644 index d4640afc9..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@3x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt.png deleted file mode 100644 index e3a04522b..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt@2x.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt@2x.png deleted file mode 100644 index 593ebd783..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_83.5@2x.png b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_83.5@2x.png deleted file mode 100644 index ca02cd03b..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_83.5@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/LaunchIcon.imageset/Contents.json b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/LaunchIcon.imageset/Contents.json deleted file mode 100644 index 2cbe59d5e..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/LaunchIcon.imageset/Contents.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "images" : [ - { - "filename" : "LaunchIcon.pdf", - "idiom" : "universal" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Base.lproj/LaunchScreen.storyboard b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index 79f85a1dd..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/en.lproj/Localizable.stringsdict b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/en.lproj/Localizable.stringsdict deleted file mode 100644 index 2d9aa217c..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/en.lproj/Localizable.stringsdict +++ /dev/null @@ -1,42 +0,0 @@ - - - - - %lld Players - - NSStringLocalizedFormatKey - %#@VARIABLE@ - VARIABLE - - NSStringFormatSpecTypeKey - NSStringPluralRuleType - NSStringFormatValueTypeKey - lld - zero - No Player - one - 1 Player - other - %lld Players - - - %lld points - - NSStringLocalizedFormatKey - %#@VARIABLE@ - VARIABLE - - NSStringFormatSpecTypeKey - NSStringPluralRuleType - NSStringFormatValueTypeKey - lld - zero - 0 point - one - 1 point - other - %lld points - - - - diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/AppView.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/AppView.swift deleted file mode 100644 index 1eda4c442..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/AppView.swift +++ /dev/null @@ -1,154 +0,0 @@ -import GRDBQuery -import SwiftUI - -/// The main application view -struct AppView: View { - /// Write access to the database - @Environment(\.appDatabase) private var appDatabase - - /// The `players` property is automatically updated when the database changes - @Query(PlayerRequest(ordering: .byScore)) private var players: [Player] - - /// We'll need to leave edit mode in several occasions. - @State private var editMode = EditMode.inactive - - /// Tracks the presentation of the player creation sheet. - @State private var newPlayerIsPresented = false - - // If you want to define the query on initialization, you will prefer: - // - // @Query private var players: [Player] - // - // init(initialOrdering: PlayerRequest.Ordering) { - // _players = Query(PlayerRequest(ordering: initialOrdering)) - // } - - var body: some View { - NavigationView { - PlayerList(players: players) - .navigationBarTitle(Text("\(players.count) Players")) - .navigationBarItems( - leading: HStack { - EditButton() - newPlayerButton - }, - trailing: ToggleOrderingButton( - ordering: $players.ordering, - willChange: { - // onChange(of: $players.wrappedValue.ordering) - // is not able to leave the editing mode during - // the animation of the list content. - // Workaround: stop editing before the ordering - // is changed, and the list content is updated. - stopEditing() - })) - .toolbar { toolbarContent } - .onChange(of: players) { players in - if players.isEmpty { - stopEditing() - } - } - .environment(\.editMode, $editMode) - } - } - - private var toolbarContent: some ToolbarContent { - ToolbarItemGroup(placement: .bottomBar) { - Button { - // Don't stopEditing() here because this is - // performed `onChange(of: players)` - Task { - try? await appDatabase.deleteAllPlayers() - } - } label: { - Image(systemName: "trash").imageScale(.large) - } - - Spacer() - - Button { - stopEditing() - Task { - try? await appDatabase.refreshPlayers() - } - } label: { - Image(systemName: "arrow.clockwise").imageScale(.large) - } - - Spacer() - - Button { - stopEditing() - // Perform 50 refreshes in parallel - Task { - try? await withThrowingTaskGroup(of: Void.self) { group in - for _ in 0..<50 { - _ = group.addTaskUnlessCancelled { - try await appDatabase.refreshPlayers() - } - } - try await group.waitForAll() - } - } - } label: { - Image(systemName: "tornado").imageScale(.large) - } - } - } - - /// The button that presents the player creation sheet. - private var newPlayerButton: some View { - Button { - stopEditing() - newPlayerIsPresented = true - } label: { - Image(systemName: "plus") - } - .accessibility(label: Text("New Player")) - .sheet(isPresented: $newPlayerIsPresented) { - PlayerCreationView() - } - } - - private func stopEditing() { - withAnimation { - editMode = .inactive - } - } -} - -private struct ToggleOrderingButton: View { - @Binding var ordering: PlayerRequest.Ordering - let willChange: () -> Void - - var body: some View { - switch ordering { - case .byName: - Button { - willChange() - ordering = .byScore - } label: { - Label("Name", systemImage: "arrowtriangle.up.fill").labelStyle(.titleAndIcon) - } - case .byScore: - Button { - willChange() - ordering = .byName - } label: { - Label("Score", systemImage: "arrowtriangle.down.fill").labelStyle(.titleAndIcon) - } - } - } -} - -struct AppView_Previews: PreviewProvider { - static var previews: some View { - Group { - // Preview the default, empty database - AppView() - - // Preview a database of random players - AppView().environment(\.appDatabase, .random()) - } - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerCreationView.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerCreationView.swift deleted file mode 100644 index b71a3c2aa..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerCreationView.swift +++ /dev/null @@ -1,50 +0,0 @@ -import SwiftUI - -/// The view that creates a new player. -struct PlayerCreationView: View { - /// Write access to the database - @Environment(\.appDatabase) private var appDatabase - @Environment(\.dismiss) private var dismiss - @State private var form = PlayerForm(name: "", score: "") - @State private var errorAlertIsPresented = false - @State private var errorAlertTitle = "" - - var body: some View { - NavigationView { - PlayerFormView(form: $form) - .alert( - isPresented: $errorAlertIsPresented, - content: { Alert(title: Text(errorAlertTitle)) }) - .navigationBarTitle("New Player") - .navigationBarItems( - leading: Button(role: .cancel) { - dismiss() - } label: { - Text("Cancel") - }, - trailing: Button { - Task { await save() } - } label: { - Text("Save") - }) - } - } - - private func save() async { - do { - var player = Player(id: nil, name: "", score: 0) - form.apply(to: &player) - try await appDatabase.savePlayer(&player) - dismiss() - } catch { - errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred" - errorAlertIsPresented = true - } - } -} - -struct PlayerCreationSheet_Previews: PreviewProvider { - static var previews: some View { - PlayerCreationView() - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerEditionView.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerEditionView.swift deleted file mode 100644 index 79f524506..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerEditionView.swift +++ /dev/null @@ -1,40 +0,0 @@ -import SwiftUI - -/// The view that edits an existing player. -struct PlayerEditionView: View { - /// Write access to the database - @Environment(\.appDatabase) private var appDatabase - @Environment(\.isPresented) private var isPresented - private let player: Player - @State private var form: PlayerForm - - init(player: Player) { - self.player = player - self.form = PlayerForm(player) - } - - var body: some View { - PlayerFormView(form: $form) - .onChange(of: isPresented) { isPresented in - // Save when back button is pressed - if !isPresented { - Task { - var savedPlayer = player - form.apply(to: &savedPlayer) - // Ignore error because I don't know how to cancel the - // back button and present the error - try? await appDatabase.savePlayer(&savedPlayer) - } - } - } - } -} - -struct PlayerEditionView_Previews: PreviewProvider { - static var previews: some View { - NavigationView { - PlayerEditionView(player: Player.makeRandom()) - .navigationBarTitle("Player Edition") - } - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerFormView.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerFormView.swift deleted file mode 100644 index bc7883e28..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerFormView.swift +++ /dev/null @@ -1,47 +0,0 @@ -import SwiftUI - -/// The Player editing form, embedded in both -/// `PlayerCreationView` and `PlayerEditionView`. -struct PlayerFormView: View { - @Binding var form: PlayerForm - - var body: some View { - List { - TextField("Name", text: $form.name) - .accessibility(label: Text("Player Name")) - TextField("Score", text: $form.score).keyboardType(.numberPad) - .accessibility(label: Text("Player Score")) - } - .listStyle(InsetGroupedListStyle()) - } -} - -struct PlayerForm { - var name: String - var score: String -} - -extension PlayerForm { - init(_ player: Player) { - self.name = player.name - self.score = "\(player.score)" - } - - func apply(to player: inout Player) { - player.name = name - player.score = Int(score) ?? 0 - } -} - -struct PlayerFormView_Previews: PreviewProvider { - static var previews: some View { - Group { - PlayerFormView(form: .constant(PlayerForm( - name: "", - score: ""))) - PlayerFormView(form: .constant(PlayerForm( - name: Player.randomName(), - score: "\(Player.randomScore())"))) - } - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerList.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerList.swift deleted file mode 100644 index b4ec9cee0..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Views/PlayerList.swift +++ /dev/null @@ -1,59 +0,0 @@ -import SwiftUI - -struct PlayerList: View { - /// Write access to the database - @Environment(\.appDatabase) private var appDatabase - - /// The players in the list - var players: [Player] - - var body: some View { - List { - ForEach(players) { player in - NavigationLink(destination: editionView(for: player)) { - PlayerRow(player: player) - // Don't animate player update - .animation(nil, value: player) - } - } - .onDelete { offsets in - let playerIds = offsets.compactMap { players[$0].id } - Task { - try? await appDatabase.deletePlayers(ids: playerIds) - } - } - } - // Animate list updates - .animation(.default, value: players) - .listStyle(.plain) - } - - /// The view that edits a player in the list. - private func editionView(for player: Player) -> some View { - PlayerEditionView(player: player).navigationBarTitle(player.name) - } -} - -private struct PlayerRow: View { - var player: Player - - var body: some View { - HStack { - Text(player.name) - Spacer() - Text("\(player.score) points").foregroundColor(.gray) - } - } -} - -struct PlayerList_Previews: PreviewProvider { - static var previews: some View { - NavigationView { - PlayerList(players: [ - Player(id: 1, name: "Arthur", score: 100), - Player(id: 2, name: "Barbara", score: 1000), - ]) - .navigationTitle("Preview") - } - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift deleted file mode 100644 index b736e9077..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/AppDatabaseTests.swift +++ /dev/null @@ -1,144 +0,0 @@ -import XCTest -import GRDB -@testable import GRDBAsyncDemo - -class AppDatabaseTests: XCTestCase { - func test_database_schema() throws { - // Given an empty database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - - // When we instantiate an AppDatabase - _ = try AppDatabase(dbQueue) - - // Then the player table exists, with id, name & score columns - try dbQueue.read { db in - try XCTAssert(db.tableExists("player")) - let columns = try db.columns(in: "player") - let columnNames = Set(columns.map { $0.name }) - XCTAssertEqual(columnNames, ["id", "name", "score"]) - } - } - - func test_savePlayer_inserts() async throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - - // When we save a new player - var player = Player(id: nil, name: "Arthur", score: 100) - try await appDatabase.savePlayer(&player) - - // Then the player exists in the database - let playerExists = try await dbQueue.read { [player] in try player.exists($0) } - XCTAssertTrue(playerExists) - } - - func test_savePlayer_updates() async throws { - // Given a players database that contains a player - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - var player = try await dbQueue.write { db in - try Player(id: nil, name: "Arthur", score: 100).inserted(db) - } - - // When we modify and save the player - player.name = "Barbara" - player.score = 1000 - try await appDatabase.savePlayer(&player) - - // Then the player has been updated in the database - let fetchedPlayer = try await dbQueue.read { [player] db in - try XCTUnwrap(Player.fetchOne(db, key: player.id)) - } - XCTAssertEqual(fetchedPlayer, player) - } - - func test_deletePlayers() async throws { - // Given a players database that contains four players - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - let playerIds: [Int64] = try await dbQueue.write { db in - _ = try Player(id: nil, name: "Arthur", score: 100).inserted(db) - _ = try Player(id: nil, name: "Barbara", score: 200).inserted(db) - _ = try Player(id: nil, name: "Craig", score: 150).inserted(db) - _ = try Player(id: nil, name: "David", score: 120).inserted(db) - return try Player.selectPrimaryKey().fetchAll(db) - } - - // When we delete two players - let deletedId1 = playerIds[0] - let deletedId2 = playerIds[2] - try await appDatabase.deletePlayers(ids: [deletedId1, deletedId2]) - - // Then the deleted players no longer exist - try await dbQueue.read { db in - try XCTAssertFalse(Player.exists(db, id: deletedId1)) - try XCTAssertFalse(Player.exists(db, id: deletedId2)) - } - - // Then the database still contains two players - let count = try await dbQueue.read { try Player.fetchCount($0) } - XCTAssertEqual(count, 2) - } - - func test_deleteAllPlayers() async throws { - // Given a players database that contains players - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - try await dbQueue.write { db in - _ = try Player(id: nil, name: "Arthur", score: 100).inserted(db) - _ = try Player(id: nil, name: "Barbara", score: 200).inserted(db) - _ = try Player(id: nil, name: "Craig", score: 150).inserted(db) - _ = try Player(id: nil, name: "David", score: 120).inserted(db) - } - - // When we delete all players - try await appDatabase.deleteAllPlayers() - - // Then the database does not contain any player - let count = try await dbQueue.read { try Player.fetchCount($0) } - XCTAssertEqual(count, 0) - } - - func test_refreshPlayers_populates_an_empty_database() async throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - - // When we refresh players - try await appDatabase.refreshPlayers() - - // Then the database is not empty - let count = try await dbQueue.read { try Player.fetchCount($0) } - XCTAssert(count > 0) - } - - func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - - // When we create random players - try appDatabase.createRandomPlayersIfEmpty() - - // Then the database is not empty - try XCTAssert(dbQueue.read(Player.fetchCount) > 0) - } - - func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws { - // Given a players database that contains one player - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - var player = Player(id: nil, name: "Arthur", score: 100) - try dbQueue.write { db in - try player.insert(db) - } - - // When we create random players - try appDatabase.createRandomPlayersIfEmpty() - - // Then the database still only contains the original player - let players = try dbQueue.read(Player.fetchAll) - XCTAssertEqual(players, [player]) - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/Info.plist b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/Info.plist deleted file mode 100644 index 64d65ca49..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/Info.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - - diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerRequestTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerRequestTests.swift deleted file mode 100644 index 2675f82d5..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerRequestTests.swift +++ /dev/null @@ -1,43 +0,0 @@ -import XCTest -import GRDB -@testable import GRDBAsyncDemo - -class PlayerRequestTests: XCTestCase { - func test_PlayerRequest_byName_fetches_well_ordered_players() throws { - // Given a players database that contains two players - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: nil, name: "Arthur", score: 100) - var player2 = Player(id: nil, name: "Barbara", score: 1000) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - } - - // When we fetch players ordered by name - let playerRequest = PlayerRequest(ordering: .byName) - let players = try dbQueue.read(playerRequest.fetchValue) - - // Then the players are the two players ordered by name - XCTAssertEqual(players, [player1, player2]) - } - - func test_PlayerRequest_byScore_fetches_well_ordered_players() throws { - // Given a players database that contains two players - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: nil, name: "Arthur", score: 100) - var player2 = Player(id: nil, name: "Barbara", score: 1000) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - } - - // When we fetch players ordered by score - let playerRequest = PlayerRequest(ordering: .byScore) - let players = try dbQueue.read(playerRequest.fetchValue) - - // Then the players are the two players ordered by score descending - XCTAssertEqual(players, [player2, player1]) - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerTests.swift b/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerTests.swift deleted file mode 100644 index edd872684..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemoTests/PlayerTests.swift +++ /dev/null @@ -1,108 +0,0 @@ -import XCTest -import GRDB -@testable import GRDBAsyncDemo - -class PlayerTests: XCTestCase { - // MARK: - CRUD - // Test that our Player type properly talks to GRDB. - - func testInsert() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - - // When we insert a player - var player = Player(id: nil, name: "Arthur", score: 100) - try dbQueue.write { db in - try player.insert(db) - } - - // Then the player gets a non-nil id - XCTAssertNotNil(player.id) - } - - func testRoundtrip() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - - // When we insert a player and fetch the player with the same id - var insertedPlayer = Player(id: nil, name: "Arthur", score: 100) - let fetchedPlayer: Player? = try dbQueue.write { db in - try insertedPlayer.insert(db) - return try Player.fetchOne(db, key: insertedPlayer.id) - } - - // Then the fetched player is equal to the inserted player - XCTAssertEqual(insertedPlayer, fetchedPlayer) - } - - // MARK: - Requests - // Test that requests defined on the Player type behave as expected. - - func testOrderedByScore() throws { - // Given a players database that contains players with distinct scores - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: 1, name: "Arthur", score: 100) - var player2 = Player(id: 2, name: "Barbara", score: 200) - var player3 = Player(id: 3, name: "Craig", score: 150) - var player4 = Player(id: 4, name: "David", score: 120) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we fetch players ordered by score - let players = try dbQueue.read(Player.all().orderedByScore().fetchAll) - - // Then fetched players are ordered by score descending - XCTAssertEqual(players, [player2, player3, player4, player1]) - } - - func testOrderedByScoreSortsIdenticalScoresByName() throws { - // Given a players database that contains players with common scores - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: 1, name: "Arthur", score: 100) - var player2 = Player(id: 2, name: "Barbara", score: 200) - var player3 = Player(id: 3, name: "Craig", score: 200) - var player4 = Player(id: 4, name: "David", score: 200) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we fetch players ordered by score - let players = try dbQueue.read(Player.all().orderedByScore().fetchAll) - - // Then fetched players are ordered by score descending and by name - XCTAssertEqual(players, [player2, player3, player4, player1]) - } - - func testOrderedByName() throws { - // Given a players database that contains players with distinct names - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: 1, name: "Arthur", score: 100) - var player2 = Player(id: 2, name: "Barbara", score: 200) - var player3 = Player(id: 3, name: "Craig", score: 150) - var player4 = Player(id: 4, name: "David", score: 120) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we fetch players ordered by name - let players = try dbQueue.read(Player.all().orderedByName().fetchAll) - - // Then fetched players are ordered by name - XCTAssertEqual(players, [player1, player2, player3, player4]) - } -} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/README.md b/Documentation/DemoApps/GRDBAsyncDemo/README.md deleted file mode 100644 index 79389fdb2..000000000 --- a/Documentation/DemoApps/GRDBAsyncDemo/README.md +++ /dev/null @@ -1,52 +0,0 @@ -Async/Await + SwiftUI Demo Application -====================================== - - - -**This demo application is an Async/Await + SwiftUI application.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md), and for Combine + SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md). - -**Requirements**: iOS 15.0+ / Xcode 13.1+ - -> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration. - -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) Combine publishers. -- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices). -- How to perform `async` database accesses. -- How to feed SwiftUI previews with a transient database. - -**Files of interest:** - -- [GRDBAsyncDemoApp.swift](GRDBAsyncDemo/GRDBAsyncDemoApp.swift) - - `GRDBAsyncDemoApp` feeds the app views with a database, through the SwiftUI environment. - -- [AppDatabase.swift](GRDBAsyncDemo/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. - -- [Persistence.swift](GRDBAsyncDemo/Persistence.swift) - - This file instantiates various `AppDatabase` for the various projects needs: one database on disk for the application, and in-memory databases for SwiftUI previews. - -- [Player.swift](GRDBAsyncDemo/Player.swift) - - `Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). - -- [PlayerRequest.swift](GRDBAsyncDemo/PlayerRequest.swift), [AppView.swift](GRDBAsyncDemo/Views/AppView.swift) - - `PlayerRequest` defines the player requests used by the app (sorted by score, or by name). - - `PlayerRequest` feeds the `@Query` property wrapper (`@Query`, defined in [GRDBQuery](https://github.com/groue/GRDBQuery), allows SwiftUI views to display up-to-date database content). - - `AppView` is the SwiftUI view that uses `@Query` in order to feed its player list. - -- [GRDBAsyncDemoTests](GRDBAsyncDemoTests) - - - Test the database schema - - Test the `Player` record and its requests - - Test the `PlayerRequest` methods that feed the list of players. - - Test the `AppDatabase` methods that let the app access the database. diff --git a/Documentation/DemoApps/GRDBAsyncDemo/Screenshot.png b/Documentation/DemoApps/GRDBAsyncDemo/Screenshot.png deleted file mode 100644 index 053682185..000000000 Binary files a/Documentation/DemoApps/GRDBAsyncDemo/Screenshot.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj deleted file mode 100644 index 5435eaded..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj +++ /dev/null @@ -1,607 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 54; - objects = { - -/* Begin PBXBuildFile section */ - 56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */; }; - 56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */; }; - 56519DC7274FC85600ED16D8 /* GRDBQuery in Frameworks */ = {isa = PBXBuildFile; productRef = 56519DC6274FC85600ED16D8 /* GRDBQuery */; }; - 5671723A261B23C800423B6F /* PlayerList.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717239261B23C800423B6F /* PlayerList.swift */; }; - 56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56717251261B334D00423B6F /* PlayerRequestTests.swift */; }; - 567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */; }; - 567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */; }; - 567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */; }; - 567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E532520B75C0011F6E9 /* Player.swift */; }; - 567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E542520B75C0011F6E9 /* Persistence.swift */; }; - 567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */; }; - 567C3E622520B75D0011F6E9 /* AppView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5A2520B75C0011F6E9 /* AppView.swift */; }; - 567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */; }; - 567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */; }; - 567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E652520B7880011F6E9 /* AppDatabase.swift */; }; - 567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E752520BB650011F6E9 /* Localizable.stringsdict */; }; - 567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */; }; - 56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */; }; - 56F8A1202735989D0011ACBE /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56F8A11F2735989D0011ACBE /* GRDB */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 567C3E152520B6DE0011F6E9; - remoteInfo = GRDBCombineDemo; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 567C3E502520B70E0011F6E9 /* Embed Frameworks */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - ); - name = "Embed Frameworks"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCombineDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 56026C9C25B8A7D000D1DF3F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = ""; }; - 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = ""; }; - 56717239261B23C800423B6F /* PlayerList.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerList.swift; sourceTree = ""; }; - 56717251261B334D00423B6F /* PlayerRequestTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequestTests.swift; sourceTree = ""; }; - 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBCombineDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoApp.swift; sourceTree = ""; }; - 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; - 567C3E222520B6DF0011F6E9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 567C3E532520B75C0011F6E9 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; - 567C3E542520B75C0011F6E9 /* Persistence.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = ""; }; - 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerFormView.swift; sourceTree = ""; }; - 567C3E5A2520B75C0011F6E9 /* AppView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppView.swift; sourceTree = ""; }; - 567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerCreationView.swift; sourceTree = ""; }; - 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionView.swift; sourceTree = ""; }; - 567C3E652520B7880011F6E9 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; - 567C3E762520BB650011F6E9 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.stringsdict; name = en; path = en.lproj/Localizable.stringsdict; sourceTree = ""; }; - 567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = ""; }; - 56F8A11C2735988F0011ACBE /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 56026C9525B8A7D000D1DF3F /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 567C3E132520B6DE0011F6E9 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 56519DC7274FC85600ED16D8 /* GRDBQuery in Frameworks */, - 56F8A1202735989D0011ACBE /* GRDB in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */ = { - isa = PBXGroup; - children = ( - 56026C9C25B8A7D000D1DF3F /* Info.plist */, - 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */, - 56717251261B334D00423B6F /* PlayerRequestTests.swift */, - 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */, - ); - path = GRDBCombineDemoTests; - sourceTree = ""; - }; - 56185BC125B8047D00B9C30F /* Resources */ = { - isa = PBXGroup; - children = ( - 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */, - 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */, - 567C3E752520BB650011F6E9 /* Localizable.stringsdict */, - ); - path = Resources; - sourceTree = ""; - }; - 567C3E0D2520B6DE0011F6E9 = { - isa = PBXGroup; - children = ( - 567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */, - 56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */, - 567C3E172520B6DE0011F6E9 /* Products */, - 567C3E4D2520B70E0011F6E9 /* Frameworks */, - 56F8A11C2735988F0011ACBE /* GRDB.swift */, - ); - sourceTree = ""; - }; - 567C3E172520B6DE0011F6E9 /* Products */ = { - isa = PBXGroup; - children = ( - 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */, - 56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */, - ); - name = Products; - sourceTree = ""; - }; - 567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */ = { - isa = PBXGroup; - children = ( - 567C3E222520B6DF0011F6E9 /* Info.plist */, - 567C3E652520B7880011F6E9 /* AppDatabase.swift */, - 567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */, - 567C3E542520B75C0011F6E9 /* Persistence.swift */, - 567C3E532520B75C0011F6E9 /* Player.swift */, - 56B6D1082619EC1B003CC455 /* PlayerRequest.swift */, - 567C3E1F2520B6DF0011F6E9 /* Preview Content */, - 56185BC125B8047D00B9C30F /* Resources */, - 567C3E582520B75C0011F6E9 /* Views */, - ); - path = GRDBCombineDemo; - sourceTree = ""; - }; - 567C3E1F2520B6DF0011F6E9 /* Preview Content */ = { - isa = PBXGroup; - children = ( - 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */, - ); - path = "Preview Content"; - sourceTree = ""; - }; - 567C3E4D2520B70E0011F6E9 /* Frameworks */ = { - isa = PBXGroup; - children = ( - ); - name = Frameworks; - sourceTree = ""; - }; - 567C3E582520B75C0011F6E9 /* Views */ = { - isa = PBXGroup; - children = ( - 567C3E5A2520B75C0011F6E9 /* AppView.swift */, - 567C3E5B2520B75C0011F6E9 /* PlayerCreationView.swift */, - 567C3E5C2520B75C0011F6E9 /* PlayerEditionView.swift */, - 567C3E592520B75C0011F6E9 /* PlayerFormView.swift */, - 56717239261B23C800423B6F /* PlayerList.swift */, - ); - path = Views; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoTests" */; - buildPhases = ( - 56026C9425B8A7D000D1DF3F /* Sources */, - 56026C9525B8A7D000D1DF3F /* Frameworks */, - 56026C9625B8A7D000D1DF3F /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */, - ); - name = GRDBCombineDemoTests; - productName = GRDBCombineDemoTests; - productReference = 56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; - 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */ = { - isa = PBXNativeTarget; - buildConfigurationList = 567C3E252520B6DF0011F6E9 /* Build configuration list for PBXNativeTarget "GRDBCombineDemo" */; - buildPhases = ( - 567C3E122520B6DE0011F6E9 /* Sources */, - 567C3E132520B6DE0011F6E9 /* Frameworks */, - 567C3E142520B6DE0011F6E9 /* Resources */, - 567C3E502520B70E0011F6E9 /* Embed Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - 56F8A11E273598960011ACBE /* PBXTargetDependency */, - ); - name = GRDBCombineDemo; - packageProductDependencies = ( - 56F8A11F2735989D0011ACBE /* GRDB */, - 56519DC6274FC85600ED16D8 /* GRDBQuery */, - ); - productName = GRBCombineDemo; - productReference = 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 567C3E0E2520B6DE0011F6E9 /* Project object */ = { - isa = PBXProject; - attributes = { - BuildIndependentTargetsInParallel = YES; - LastSwiftUpdateCheck = 1250; - LastUpgradeCheck = 1200; - TargetAttributes = { - 56026C9725B8A7D000D1DF3F = { - CreatedOnToolsVersion = 12.3; - TestTargetID = 567C3E152520B6DE0011F6E9; - }; - 567C3E152520B6DE0011F6E9 = { - CreatedOnToolsVersion = 12.0; - }; - }; - }; - buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */; - compatibilityVersion = "Xcode 12.0"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 567C3E0D2520B6DE0011F6E9; - packageReferences = ( - 56519DC5274FC85600ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */, - ); - productRefGroup = 567C3E172520B6DE0011F6E9 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */, - 56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 56026C9625B8A7D000D1DF3F /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 567C3E142520B6DE0011F6E9 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */, - 567C3E7A2520BB650011F6E9 /* LaunchScreen.storyboard in Resources */, - 567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */, - 567C3E792520BB650011F6E9 /* Localizable.stringsdict in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 56026C9425B8A7D000D1DF3F /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */, - 56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */, - 56717252261B334D00423B6F /* PlayerRequestTests.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 567C3E122520B6DE0011F6E9 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 567C3E5E2520B75C0011F6E9 /* Persistence.swift in Sources */, - 567C3E5D2520B75C0011F6E9 /* Player.swift in Sources */, - 56B6D1092619EC1B003CC455 /* PlayerRequest.swift in Sources */, - 5671723A261B23C800423B6F /* PlayerList.swift in Sources */, - 567C3E612520B75D0011F6E9 /* PlayerFormView.swift in Sources */, - 567C3E632520B75D0011F6E9 /* PlayerCreationView.swift in Sources */, - 567C3E662520B7880011F6E9 /* AppDatabase.swift in Sources */, - 567C3E622520B75D0011F6E9 /* AppView.swift in Sources */, - 567C3E642520B75D0011F6E9 /* PlayerEditionView.swift in Sources */, - 567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */; - targetProxy = 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */; - }; - 56F8A11E273598960011ACBE /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - productRef = 56F8A11D273598960011ACBE /* GRDB */; - }; -/* End PBXTargetDependency section */ - -/* Begin PBXVariantGroup section */ - 567C3E752520BB650011F6E9 /* Localizable.stringsdict */ = { - isa = PBXVariantGroup; - children = ( - 567C3E762520BB650011F6E9 /* en */, - ); - name = Localizable.stringsdict; - sourceTree = ""; - }; - 567C3E772520BB650011F6E9 /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 567C3E782520BB650011F6E9 /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 56026C9F25B8A7D000D1DF3F /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CODE_SIGN_STYLE = Automatic; - INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemoTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBCombineDemo.app/GRDBCombineDemo"; - }; - name = Debug; - }; - 56026CA025B8A7D000D1DF3F /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CODE_SIGN_STYLE = Automatic; - INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemoTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBCombineDemo.app/GRDBCombineDemo"; - }; - name = Release; - }; - 567C3E232520B6DF0011F6E9 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 15.0; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 567C3E242520B6DF0011F6E9 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 15.0; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - VALIDATE_PRODUCT = YES; - }; - name = Release; - }; - 567C3E262520B6DF0011F6E9 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; - CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\""; - DEVELOPMENT_TEAM = ""; - ENABLE_PREVIEWS = YES; - INFOPLIST_FILE = GRDBCombineDemo/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemo; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = 1; - }; - name = Debug; - }; - 567C3E272520B6DF0011F6E9 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; - CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_ASSET_PATHS = "\"GRDBCombineDemo/Preview Content\""; - DEVELOPMENT_TEAM = ""; - ENABLE_PREVIEWS = YES; - INFOPLIST_FILE = GRDBCombineDemo/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemo; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = 1; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 56026C9F25B8A7D000D1DF3F /* Debug */, - 56026CA025B8A7D000D1DF3F /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 567C3E232520B6DF0011F6E9 /* Debug */, - 567C3E242520B6DF0011F6E9 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 567C3E252520B6DF0011F6E9 /* Build configuration list for PBXNativeTarget "GRDBCombineDemo" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 567C3E262520B6DF0011F6E9 /* Debug */, - 567C3E272520B6DF0011F6E9 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - -/* Begin XCRemoteSwiftPackageReference section */ - 56519DC5274FC85600ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */ = { - isa = XCRemoteSwiftPackageReference; - repositoryURL = "https://github.com/groue/GRDBQuery"; - requirement = { - kind = upToNextMajorVersion; - minimumVersion = 0.6.0; - }; - }; -/* End XCRemoteSwiftPackageReference section */ - -/* Begin XCSwiftPackageProductDependency section */ - 56519DC6274FC85600ED16D8 /* GRDBQuery */ = { - isa = XCSwiftPackageProductDependency; - package = 56519DC5274FC85600ED16D8 /* XCRemoteSwiftPackageReference "GRDBQuery" */; - productName = GRDBQuery; - }; - 56F8A11D273598960011ACBE /* GRDB */ = { - isa = XCSwiftPackageProductDependency; - productName = GRDB; - }; - 56F8A11F2735989D0011ACBE /* GRDB */ = { - isa = XCSwiftPackageProductDependency; - productName = GRDB; - }; -/* End XCSwiftPackageProductDependency section */ - }; - rootObject = 567C3E0E2520B6DE0011F6E9 /* Project object */; -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved deleted file mode 100644 index 5a507d565..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ /dev/null @@ -1,14 +0,0 @@ -{ - "pins" : [ - { - "identity" : "grdbquery", - "kind" : "remoteSourceControl", - "location" : "https://github.com/groue/GRDBQuery", - "state" : { - "revision" : "aefc0d7e7a64e841da33e1c8be7429da1bd9b5d6", - "version" : "0.6.0" - } - } - ], - "version" : 2 -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme deleted file mode 100644 index 0cbf7bf5c..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift deleted file mode 100644 index c4b5a5e92..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift +++ /dev/null @@ -1,235 +0,0 @@ -import Foundation -import GRDB -import os.log - -/// A database of players. -/// -/// You create an `AppDatabase` with a connection to an SQLite database -/// (see ). -/// -/// Create those connections with a configuration returned from -/// `AppDatabase/makeConfiguration(_:)`. -/// -/// For example: -/// -/// ```swift -/// // Create an in-memory AppDatabase -/// let config = AppDatabase.makeConfiguration() -/// let dbQueue = try DatabaseQueue(configuration: config) -/// let appDatabase = try AppDatabase(dbQueue) -/// ``` -struct AppDatabase { - /// Creates an `AppDatabase`, and makes sure the database schema - /// is ready. - /// - /// - important: Create the `DatabaseWriter` with a configuration - /// returned by ``makeConfiguration(_:)``. - init(_ dbWriter: any DatabaseWriter) throws { - self.dbWriter = dbWriter - try migrator.migrate(dbWriter) - } - - /// Provides access to the database. - /// - /// Application can use a `DatabasePool`, while SwiftUI previews and tests - /// can use a fast in-memory `DatabaseQueue`. - /// - /// See - private let dbWriter: any DatabaseWriter -} - -// MARK: - Database Configuration - -extension AppDatabase { - private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL") - - /// Returns a database configuration suited for `PlayerRepository`. - /// - /// SQL statements are logged if the `SQL_TRACE` environment variable - /// is set. - /// - /// - parameter base: A base configuration. - public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration { - var config = base - - // An opportunity to add required custom SQL functions or - // collations, if needed: - // config.prepareDatabase { db in - // db.add(function: ...) - // } - - // Log SQL statements if the `SQL_TRACE` environment variable is set. - // See - if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil { - config.prepareDatabase { db in - db.trace { - // It's ok to log statements publicly. Sensitive - // information (statement arguments) are not logged - // unless config.publicStatementArguments is set - // (see below). - os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0)) - } - } - } - -#if DEBUG - // Protect sensitive information by enabling verbose debugging in - // DEBUG builds only. - // See - config.publicStatementArguments = true -#endif - - return config - } -} - -// MARK: - Database Migrations - -extension AppDatabase { - /// The DatabaseMigrator that defines the database schema. - /// - /// See - private var migrator: DatabaseMigrator { - var migrator = DatabaseMigrator() - -#if DEBUG - // Speed up development by nuking the database when migrations change - // See - migrator.eraseDatabaseOnSchemaChange = true -#endif - - migrator.registerMigration("createPlayer") { db in - // Create a table - // See - try db.create(table: "player") { t in - t.autoIncrementedPrimaryKey("id") - t.column("name", .text).notNull() - t.column("score", .integer).notNull() - } - } - - // Migrations for future application versions will be inserted here: - // migrator.registerMigration(...) { db in - // ... - // } - - return migrator - } -} - -// MARK: - Database Access: Writes -// The write methods execute invariant-preserving database transactions. - -extension AppDatabase { - /// A validation error that prevents some players from being saved into - /// the database. - enum ValidationError: LocalizedError { - case missingName - - var errorDescription: String? { - switch self { - case .missingName: - return "Please provide a name" - } - } - } - - /// Saves (inserts or updates) a player. When the method returns, the - /// player is present in the database, and its id is not nil. - func savePlayer(_ player: inout Player) throws { - if player.name.isEmpty { - throw ValidationError.missingName - } - try dbWriter.write { db in - try player.save(db) - } - } - - /// Delete the specified players - func deletePlayers(ids: [Int64]) throws { - try dbWriter.write { db in - _ = try Player.deleteAll(db, ids: ids) - } - } - - /// Delete all players - func deleteAllPlayers() throws { - try dbWriter.write { db in - _ = try Player.deleteAll(db) - } - } - - /// Refresh all players (by performing some random changes, for demo purpose). - func refreshPlayers() throws { - try dbWriter.write { db in - if try Player.all().isEmpty(db) { - // When database is empty, insert new random players - try createRandomPlayers(db) - } else { - // Insert a player - if Bool.random() { - _ = try Player.makeRandom().inserted(db) // insert but ignore inserted id - } - - // Delete a random player - if Bool.random() { - try Player.order(sql: "RANDOM()").limit(1).deleteAll(db) - } - - // Update some players - for var player in try Player.fetchAll(db) where Bool.random() { - try player.updateChanges(db) { - $0.score = Player.randomScore() - } - } - } - } - } - - /// Create random players if the database is empty. - func createRandomPlayersIfEmpty() throws { - try dbWriter.write { db in - if try Player.all().isEmpty(db) { - try createRandomPlayers(db) - } - } - } - - private static let uiTestPlayers = [ - Player(id: nil, name: "Arthur", score: 5), - Player(id: nil, name: "Barbara", score: 6), - Player(id: nil, name: "Craig", score: 8), - Player(id: nil, name: "David", score: 4), - Player(id: nil, name: "Elena", score: 1), - Player(id: nil, name: "Frederik", score: 2), - Player(id: nil, name: "Gilbert", score: 7), - Player(id: nil, name: "Henriette", score: 3)] - - func createPlayersForUITests() throws { - try dbWriter.write { db in - try AppDatabase.uiTestPlayers.forEach { player in - _ = try player.inserted(db) // insert but ignore inserted id - } - } - } - - /// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`. - private func createRandomPlayers(_ db: Database) throws { - for _ in 0..<8 { - _ = try Player.makeRandom().inserted(db) // insert but ignore inserted id - } - } -} - -// MARK: - Database Access: Reads - -// This demo app does not provide any specific reading method, and instead -// gives an unrestricted read-only access to the rest of the application. -// In your app, you are free to choose another path, and define focused -// reading methods. -extension AppDatabase { - /// Provides a read-only access to the database - var reader: DatabaseReader { - dbWriter - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/GRDBCombineDemoApp.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/GRDBCombineDemoApp.swift deleted file mode 100644 index 3565a31cb..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/GRDBCombineDemoApp.swift +++ /dev/null @@ -1,40 +0,0 @@ -import GRDBQuery -import SwiftUI - -@main -struct GRDBCombineDemoApp: App { - var body: some Scene { - WindowGroup { - AppView().environment(\.appDatabase, .shared) - } - } -} - -// MARK: - Give SwiftUI access to the database -// -// Define a new environment key that grants access to an AppDatabase. -// -// The technique is documented at -// . - -private struct AppDatabaseKey: EnvironmentKey { - static var defaultValue: AppDatabase { .empty() } -} - -extension EnvironmentValues { - var appDatabase: AppDatabase { - get { self[AppDatabaseKey.self] } - set { self[AppDatabaseKey.self] = newValue } - } -} - -// In this demo app, views observe the database with the @Query property -// wrapper, defined in the GRDBQuery package. Its documentation recommends to -// define a dedicated initializer for `appDatabase` access, so we comply: - -extension Query where Request.DatabaseContext == AppDatabase { - /// Convenience initializer for requests that feed from `AppDatabase`. - init(_ request: Request) { - self.init(request, in: \.appDatabase) - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Info.plist b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Info.plist deleted file mode 100644 index 4754bb868..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Info.plist +++ /dev/null @@ -1,50 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - LSRequiresIPhoneOS - - UIApplicationSceneManifest - - UIApplicationSupportsMultipleScenes - - - UIApplicationSupportsIndirectInputEvents - - UILaunchScreen - - UILaunchStoryboardName - LaunchScreen - UIRequiredDeviceCapabilities - - armv7 - - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - - diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift deleted file mode 100644 index 05b011578..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Persistence.swift +++ /dev/null @@ -1,77 +0,0 @@ -import Foundation -import GRDB - -extension AppDatabase { - /// The database for the application - static let shared = makeShared() - - private static func makeShared() -> AppDatabase { - do { - // Apply recommendations from - // - // - // Create the "Application Support/Database" directory if needed - let fileManager = FileManager.default - let appSupportURL = try fileManager.url( - for: .applicationSupportDirectory, in: .userDomainMask, - appropriateFor: nil, create: true) - let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true) - - // Support for tests: delete the database if requested - if CommandLine.arguments.contains("-reset") { - try? fileManager.removeItem(at: directoryURL) - } - - // Create the database folder if needed - try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true) - - // Open or create the database - let databaseURL = directoryURL.appendingPathComponent("db.sqlite") - NSLog("Database stored at \(databaseURL.path)") - let dbPool = try DatabasePool( - path: databaseURL.path, - // Use default AppDatabase configuration - configuration: AppDatabase.makeConfiguration()) - - // Create the AppDatabase - let appDatabase = try AppDatabase(dbPool) - - // Prepare the database with test fixtures if requested - if CommandLine.arguments.contains("-fixedTestData") { - try appDatabase.createPlayersForUITests() - } else { - // Otherwise, populate the database if it is empty, for better - // demo purpose. - try appDatabase.createRandomPlayersIfEmpty() - } - - return appDatabase - } catch { - // Replace this implementation with code to handle the error appropriately. - // fatalError() causes the application to generate a crash log and terminate. - // - // Typical reasons for an error here include: - // * The parent directory cannot be created, or disallows writing. - // * The database is not accessible, due to permissions or data protection when the device is locked. - // * The device is out of space. - // * The database could not be migrated to its latest schema version. - // Check the error message to determine what the actual problem was. - fatalError("Unresolved error \(error)") - } - } - - /// 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 - let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - return try! AppDatabase(dbQueue) - } - - /// Creates a database full of random players for SwiftUI previews - static func random() -> AppDatabase { - let appDatabase = empty() - try! appDatabase.createRandomPlayersIfEmpty() - return appDatabase - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/PlayerRequest.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/PlayerRequest.swift deleted file mode 100644 index 8c70aab8d..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/PlayerRequest.swift +++ /dev/null @@ -1,55 +0,0 @@ -import Combine -import GRDB -import GRDBQuery - -/// A player request can be used with the `@Query` property wrapper in order to -/// feed a view with a list of players. -/// -/// For example: -/// -/// struct MyView: View { -/// @Query(PlayerRequest(ordering: .byName)) private var players: [Player] -/// -/// var body: some View { -/// List(players) { player in ... ) -/// } -/// } -struct PlayerRequest: Queryable { - enum Ordering { - case byScore - case byName - } - - /// The ordering used by the player request. - var ordering: Ordering - - // MARK: - Queryable Implementation - - static var defaultValue: [Player] { [] } - - func publisher(in appDatabase: AppDatabase) -> AnyPublisher<[Player], Error> { - // Build the publisher from the general-purpose read-only access - // granted by `appDatabase.reader`. - // Some apps will prefer to call a dedicated method of `appDatabase`. - ValueObservation - .tracking(fetchValue(_:)) - .publisher( - in: appDatabase.reader, - // The `.immediate` scheduling feeds the view right on - // subscription, and avoids an undesired animation when the - // application starts. - scheduling: .immediate) - .eraseToAnyPublisher() - } - - // This method is not required by Queryable, but it makes it easier - // to test PlayerRequest. - func fetchValue(_ db: Database) throws -> [Player] { - switch ordering { - case .byScore: - return try Player.all().orderedByScore().fetchAll(db) - case .byName: - return try Player.all().orderedByName().fetchAll(db) - } - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index 29d91251d..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "images" : [ - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "icon_20pt@2x.png", - "scale" : "2x" - }, - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "icon_20pt@3x.png", - "scale" : "3x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "icon_29pt@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "icon_29pt@3x.png", - "scale" : "3x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "icon_40pt@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "icon_40pt@3x.png", - "scale" : "3x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "icon_60pt@2x.png", - "scale" : "2x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "icon_60pt@3x.png", - "scale" : "3x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "icon_20pt.png", - "scale" : "1x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "icon_20pt@2x-1.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "icon_29pt.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "icon_29pt@2x-1.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "icon_40pt.png", - "scale" : "1x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "icon_40pt@2x-1.png", - "scale" : "2x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "icon_76pt.png", - "scale" : "1x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "icon_76pt@2x.png", - "scale" : "2x" - }, - { - "size" : "83.5x83.5", - "idiom" : "ipad", - "filename" : "icon_83.5@2x.png", - "scale" : "2x" - }, - { - "size" : "1024x1024", - "idiom" : "ios-marketing", - "filename" : "Icon.png", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon.png deleted file mode 100644 index 66b1931a1..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt.png deleted file mode 100644 index 90648b3f4..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x-1.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x-1.png deleted file mode 100644 index a077a6f49..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x-1.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x.png deleted file mode 100644 index a077a6f49..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@3x.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@3x.png deleted file mode 100644 index 600bdbd9c..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@3x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt.png deleted file mode 100644 index 8e04af0dd..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x-1.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x-1.png deleted file mode 100644 index 686e8d99e..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x-1.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x.png deleted file mode 100644 index 686e8d99e..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@3x.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@3x.png deleted file mode 100644 index 1d013c3d3..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@3x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt.png deleted file mode 100644 index a077a6f49..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x-1.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x-1.png deleted file mode 100644 index da66b9ba8..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x-1.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x.png deleted file mode 100644 index da66b9ba8..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@3x.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@3x.png deleted file mode 100644 index 59346ef4b..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@3x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@2x.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@2x.png deleted file mode 100644 index 59346ef4b..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@3x.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@3x.png deleted file mode 100644 index d4640afc9..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@3x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt.png deleted file mode 100644 index e3a04522b..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt@2x.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt@2x.png deleted file mode 100644 index 593ebd783..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_83.5@2x.png b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_83.5@2x.png deleted file mode 100644 index ca02cd03b..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AppIcon.appiconset/icon_83.5@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/LaunchIcon.imageset/Contents.json b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/LaunchIcon.imageset/Contents.json deleted file mode 100644 index 2cbe59d5e..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/LaunchIcon.imageset/Contents.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "images" : [ - { - "filename" : "LaunchIcon.pdf", - "idiom" : "universal" - } - ], - "info" : { - "author" : "xcode", - "version" : 1 - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/LaunchIcon.imageset/LaunchIcon.pdf b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/LaunchIcon.imageset/LaunchIcon.pdf deleted file mode 100644 index 266089149..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/LaunchIcon.imageset/LaunchIcon.pdf and /dev/null differ diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Base.lproj/LaunchScreen.storyboard b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index 79f85a1dd..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/en.lproj/Localizable.stringsdict b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/en.lproj/Localizable.stringsdict deleted file mode 100644 index 2d9aa217c..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/en.lproj/Localizable.stringsdict +++ /dev/null @@ -1,42 +0,0 @@ - - - - - %lld Players - - NSStringLocalizedFormatKey - %#@VARIABLE@ - VARIABLE - - NSStringFormatSpecTypeKey - NSStringPluralRuleType - NSStringFormatValueTypeKey - lld - zero - No Player - one - 1 Player - other - %lld Players - - - %lld points - - NSStringLocalizedFormatKey - %#@VARIABLE@ - VARIABLE - - NSStringFormatSpecTypeKey - NSStringPluralRuleType - NSStringFormatValueTypeKey - lld - zero - 0 point - one - 1 point - other - %lld points - - - - diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/AppView.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/AppView.swift deleted file mode 100644 index 0879f3430..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/AppView.swift +++ /dev/null @@ -1,145 +0,0 @@ -import GRDBQuery -import SwiftUI - -/// The main application view -struct AppView: View { - /// Write access to the database - @Environment(\.appDatabase) private var appDatabase - - /// The `players` property is automatically updated when the database changes - @Query(PlayerRequest(ordering: .byScore)) private var players: [Player] - - /// We'll need to leave edit mode in several occasions. - @State private var editMode = EditMode.inactive - - /// Tracks the presentation of the player creation sheet. - @State private var newPlayerIsPresented = false - - // If you want to define the query on initialization, you will prefer: - // - // @Query private var players: [Player] - // - // init(initialOrdering: PlayerRequest.Ordering) { - // _players = Query(PlayerRequest(ordering: initialOrdering)) - // } - - var body: some View { - NavigationView { - PlayerList(players: players) - .navigationBarTitle(Text("\(players.count) Players")) - .navigationBarItems( - leading: HStack { - EditButton() - newPlayerButton - }, - trailing: ToggleOrderingButton( - ordering: $players.ordering, - willChange: { - // onChange(of: $players.wrappedValue.ordering) - // is not able to leave the editing mode during - // the animation of the list content. - // Workaround: stop editing before the ordering - // is changed, and the list content is updated. - stopEditing() - })) - .toolbar { toolbarContent } - .onChange(of: players) { players in - if players.isEmpty { - stopEditing() - } - } - .environment(\.editMode, $editMode) - } - } - - private var toolbarContent: some ToolbarContent { - ToolbarItemGroup(placement: .bottomBar) { - Button { - // Don't stopEditing() here because this is - // performed `onChange(of: players)` - try! appDatabase.deleteAllPlayers() - } label: { - Image(systemName: "trash").imageScale(.large) - } - - Spacer() - - Button { - stopEditing() - try! appDatabase.refreshPlayers() - } label: { - Image(systemName: "arrow.clockwise").imageScale(.large) - } - - Spacer() - - Button { - stopEditing() - // Perform 50 refreshes in parallel - for _ in 0..<50 { - DispatchQueue.global().async { - try! AppDatabase.shared.refreshPlayers() - } - } - } label: { - Image(systemName: "tornado").imageScale(.large) - } - } - } - - /// The button that presents the player creation sheet. - private var newPlayerButton: some View { - Button { - stopEditing() - newPlayerIsPresented = true - } label: { - Image(systemName: "plus") - } - .accessibility(label: Text("New Player")) - .sheet(isPresented: $newPlayerIsPresented) { - PlayerCreationView() - } - } - - private func stopEditing() { - withAnimation { - editMode = .inactive - } - } -} - -private struct ToggleOrderingButton: View { - @Binding var ordering: PlayerRequest.Ordering - let willChange: () -> Void - - var body: some View { - switch ordering { - case .byName: - Button { - willChange() - ordering = .byScore - } label: { - Label("Name", systemImage: "arrowtriangle.up.fill").labelStyle(.titleAndIcon) - } - case .byScore: - Button { - willChange() - ordering = .byName - } label: { - Label("Score", systemImage: "arrowtriangle.down.fill").labelStyle(.titleAndIcon) - } - } - } -} - -struct AppView_Previews: PreviewProvider { - static var previews: some View { - Group { - // Preview the default, empty database - AppView() - - // Preview a database of random players - AppView().environment(\.appDatabase, .random()) - } - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerCreationView.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerCreationView.swift deleted file mode 100644 index 1c78289a9..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerCreationView.swift +++ /dev/null @@ -1,50 +0,0 @@ -import SwiftUI - -/// The view that creates a new player. -struct PlayerCreationView: View { - /// Write access to the database - @Environment(\.appDatabase) private var appDatabase - @Environment(\.dismiss) private var dismiss - @State private var form = PlayerForm(name: "", score: "") - @State private var errorAlertIsPresented = false - @State private var errorAlertTitle = "" - - var body: some View { - NavigationView { - PlayerFormView(form: $form) - .alert( - isPresented: $errorAlertIsPresented, - content: { Alert(title: Text(errorAlertTitle)) }) - .navigationBarTitle("New Player") - .navigationBarItems( - leading: Button(role: .cancel) { - dismiss() - } label: { - Text("Cancel") - }, - trailing: Button { - save() - } label: { - Text("Save") - }) - } - } - - private func save() { - do { - var player = Player(id: nil, name: "", score: 0) - form.apply(to: &player) - try appDatabase.savePlayer(&player) - dismiss() - } catch { - errorAlertTitle = (error as? LocalizedError)?.errorDescription ?? "An error occurred" - errorAlertIsPresented = true - } - } -} - -struct PlayerCreationSheet_Previews: PreviewProvider { - static var previews: some View { - PlayerCreationView() - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerEditionView.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerEditionView.swift deleted file mode 100644 index a3bde6aa8..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerEditionView.swift +++ /dev/null @@ -1,38 +0,0 @@ -import SwiftUI - -/// The view that edits an existing player. -struct PlayerEditionView: View { - /// Write access to the database - @Environment(\.appDatabase) private var appDatabase - @Environment(\.isPresented) private var isPresented - private let player: Player - @State private var form: PlayerForm - - init(player: Player) { - self.player = player - self.form = PlayerForm(player) - } - - var body: some View { - PlayerFormView(form: $form) - .onChange(of: isPresented) { isPresented in - // Save when back button is pressed - if !isPresented { - var savedPlayer = player - form.apply(to: &savedPlayer) - // Ignore error because I don't know how to cancel the - // back button and present the error - try? appDatabase.savePlayer(&savedPlayer) - } - } - } -} - -struct PlayerEditionView_Previews: PreviewProvider { - static var previews: some View { - NavigationView { - PlayerEditionView(player: Player.makeRandom()) - .navigationBarTitle("Player Edition") - } - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerFormView.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerFormView.swift deleted file mode 100644 index bc7883e28..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerFormView.swift +++ /dev/null @@ -1,47 +0,0 @@ -import SwiftUI - -/// The Player editing form, embedded in both -/// `PlayerCreationView` and `PlayerEditionView`. -struct PlayerFormView: View { - @Binding var form: PlayerForm - - var body: some View { - List { - TextField("Name", text: $form.name) - .accessibility(label: Text("Player Name")) - TextField("Score", text: $form.score).keyboardType(.numberPad) - .accessibility(label: Text("Player Score")) - } - .listStyle(InsetGroupedListStyle()) - } -} - -struct PlayerForm { - var name: String - var score: String -} - -extension PlayerForm { - init(_ player: Player) { - self.name = player.name - self.score = "\(player.score)" - } - - func apply(to player: inout Player) { - player.name = name - player.score = Int(score) ?? 0 - } -} - -struct PlayerFormView_Previews: PreviewProvider { - static var previews: some View { - Group { - PlayerFormView(form: .constant(PlayerForm( - name: "", - score: ""))) - PlayerFormView(form: .constant(PlayerForm( - name: Player.randomName(), - score: "\(Player.randomScore())"))) - } - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerList.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerList.swift deleted file mode 100644 index 1b41a8bc4..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Views/PlayerList.swift +++ /dev/null @@ -1,57 +0,0 @@ -import SwiftUI - -struct PlayerList: View { - /// Write access to the database - @Environment(\.appDatabase) private var appDatabase - - /// The players in the list - var players: [Player] - - var body: some View { - List { - ForEach(players) { player in - NavigationLink(destination: editionView(for: player)) { - PlayerRow(player: player) - // Don't animate player update - .animation(nil, value: player) - } - } - .onDelete { offsets in - let playerIds = offsets.compactMap { players[$0].id } - try? appDatabase.deletePlayers(ids: playerIds) - } - } - // Animate list updates - .animation(.default, value: players) - .listStyle(.plain) - } - - /// The view that edits a player in the list. - private func editionView(for player: Player) -> some View { - PlayerEditionView(player: player).navigationBarTitle(player.name) - } -} - -private struct PlayerRow: View { - var player: Player - - var body: some View { - HStack { - Text(player.name) - Spacer() - Text("\(player.score) points").foregroundColor(.gray) - } - } -} - -struct PlayerList_Previews: PreviewProvider { - static var previews: some View { - NavigationView { - PlayerList(players: [ - Player(id: 1, name: "Arthur", score: 100), - Player(id: 2, name: "Barbara", score: 1000), - ]) - .navigationTitle("Preview") - } - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift deleted file mode 100644 index f9343671e..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift +++ /dev/null @@ -1,146 +0,0 @@ -import XCTest -import GRDB -@testable import GRDBCombineDemo - -class AppDatabaseTests: XCTestCase { - func test_database_schema() throws { - // Given an empty database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - - // When we instantiate an AppDatabase - _ = try AppDatabase(dbQueue) - - // Then the player table exists, with id, name & score columns - try dbQueue.read { db in - try XCTAssert(db.tableExists("player")) - let columns = try db.columns(in: "player") - let columnNames = Set(columns.map { $0.name }) - XCTAssertEqual(columnNames, ["id", "name", "score"]) - } - } - - func test_savePlayer_inserts() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - - // When we save a new player - var player = Player(id: nil, name: "Arthur", score: 100) - try appDatabase.savePlayer(&player) - - // Then the player exists in the database - try XCTAssertTrue(dbQueue.read(player.exists)) - } - - func test_savePlayer_updates() throws { - // Given a players database that contains a player - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - var player = Player(id: nil, name: "Arthur", score: 100) - try dbQueue.write { db in - try player.insert(db) - } - - // When we modify and save the player - player.name = "Barbara" - player.score = 1000 - try appDatabase.savePlayer(&player) - - // Then the player has been updated in the database - let fetchedPlayer = try dbQueue.read { db in - try XCTUnwrap(Player.fetchOne(db, key: player.id)) - } - XCTAssertEqual(fetchedPlayer, player) - } - - func test_deletePlayers() throws { - // Given a players database that contains four players - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - var player1 = Player(id: nil, name: "Arthur", score: 100) - var player2 = Player(id: nil, name: "Barbara", score: 200) - var player3 = Player(id: nil, name: "Craig", score: 150) - var player4 = Player(id: nil, name: "David", score: 120) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we delete two players - try appDatabase.deletePlayers(ids: [player1.id!, player3.id!]) - - // Then the deleted players no longer exist - try dbQueue.read { db in - try XCTAssertFalse(player1.exists(db)) - try XCTAssertFalse(player3.exists(db)) - } - - // Then the database still contains two players - try XCTAssertEqual(dbQueue.read(Player.fetchCount), 2) - } - - func test_deleteAllPlayers() throws { - // Given a players database that contains players - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - var player1 = Player(id: nil, name: "Arthur", score: 100) - var player2 = Player(id: nil, name: "Barbara", score: 200) - var player3 = Player(id: nil, name: "Craig", score: 150) - var player4 = Player(id: nil, name: "David", score: 120) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we delete all players - try appDatabase.deleteAllPlayers() - - // Then the database does not contain any player - try XCTAssertEqual(dbQueue.read(Player.fetchCount), 0) - } - - func test_refreshPlayers_populates_an_empty_database() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - - // When we refresh players - try appDatabase.refreshPlayers() - - // Then the database is not empty - try XCTAssert(dbQueue.read(Player.fetchCount) > 0) - } - - func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - - // When we create random players - try appDatabase.createRandomPlayersIfEmpty() - - // Then the database is not empty - try XCTAssert(dbQueue.read(Player.fetchCount) > 0) - } - - func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws { - // Given a players database that contains one player - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - var player = Player(id: nil, name: "Arthur", score: 100) - try dbQueue.write { db in - try player.insert(db) - } - - // When we create random players - try appDatabase.createRandomPlayersIfEmpty() - - // Then the database still only contains the original player - let players = try dbQueue.read(Player.fetchAll) - XCTAssertEqual(players, [player]) - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/Info.plist b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/Info.plist deleted file mode 100644 index 64d65ca49..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/Info.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - - diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerRequestTests.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerRequestTests.swift deleted file mode 100644 index 151d8e41e..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerRequestTests.swift +++ /dev/null @@ -1,43 +0,0 @@ -import XCTest -import GRDB -@testable import GRDBCombineDemo - -class PlayerRequestTests: XCTestCase { - func test_PlayerRequest_byName_fetches_well_ordered_players() throws { - // Given a players database that contains two players - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: nil, name: "Arthur", score: 100) - var player2 = Player(id: nil, name: "Barbara", score: 1000) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - } - - // When we fetch players ordered by name - let playerRequest = PlayerRequest(ordering: .byName) - let players = try dbQueue.read(playerRequest.fetchValue) - - // Then the players are the two players ordered by name - XCTAssertEqual(players, [player1, player2]) - } - - func test_PlayerRequest_byScore_fetches_well_ordered_players() throws { - // Given a players database that contains two players - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: nil, name: "Arthur", score: 100) - var player2 = Player(id: nil, name: "Barbara", score: 1000) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - } - - // When we fetch players ordered by score - let playerRequest = PlayerRequest(ordering: .byScore) - let players = try dbQueue.read(playerRequest.fetchValue) - - // Then the players are the two players ordered by score descending - XCTAssertEqual(players, [player2, player1]) - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift deleted file mode 100644 index 4262d8023..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift +++ /dev/null @@ -1,108 +0,0 @@ -import XCTest -import GRDB -@testable import GRDBCombineDemo - -class PlayerTests: XCTestCase { - // MARK: - CRUD - // Test that our Player type properly talks to GRDB. - - func testInsert() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - - // When we insert a player - var player = Player(id: nil, name: "Arthur", score: 100) - try dbQueue.write { db in - try player.insert(db) - } - - // Then the player gets a non-nil id - XCTAssertNotNil(player.id) - } - - func testRoundtrip() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - - // When we insert a player and fetch the player with the same id - var insertedPlayer = Player(id: nil, name: "Arthur", score: 100) - let fetchedPlayer: Player? = try dbQueue.write { db in - try insertedPlayer.insert(db) - return try Player.fetchOne(db, key: insertedPlayer.id) - } - - // Then the fetched player is equal to the inserted player - XCTAssertEqual(insertedPlayer, fetchedPlayer) - } - - // MARK: - Requests - // Test that requests defined on the Player type behave as expected. - - func testOrderedByScore() throws { - // Given a players database that contains players with distinct scores - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: 1, name: "Arthur", score: 100) - var player2 = Player(id: 2, name: "Barbara", score: 200) - var player3 = Player(id: 3, name: "Craig", score: 150) - var player4 = Player(id: 4, name: "David", score: 120) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we fetch players ordered by score - let players = try dbQueue.read(Player.all().orderedByScore().fetchAll) - - // Then fetched players are ordered by score descending - XCTAssertEqual(players, [player2, player3, player4, player1]) - } - - func testOrderedByScoreSortsIdenticalScoresByName() throws { - // Given a players database that contains players with common scores - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: 1, name: "Arthur", score: 100) - var player2 = Player(id: 2, name: "Barbara", score: 200) - var player3 = Player(id: 3, name: "Craig", score: 200) - var player4 = Player(id: 4, name: "David", score: 200) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we fetch players ordered by score - let players = try dbQueue.read(Player.all().orderedByScore().fetchAll) - - // Then fetched players are ordered by score descending and by name - XCTAssertEqual(players, [player2, player3, player4, player1]) - } - - func testOrderedByName() throws { - // Given a players database that contains players with distinct names - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: 1, name: "Arthur", score: 100) - var player2 = Player(id: 2, name: "Barbara", score: 200) - var player3 = Player(id: 3, name: "Craig", score: 150) - var player4 = Player(id: 4, name: "David", score: 120) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we fetch players ordered by name - let players = try dbQueue.read(Player.all().orderedByName().fetchAll) - - // Then fetched players are ordered by name - XCTAssertEqual(players, [player1, player2, player3, player4]) - } -} diff --git a/Documentation/DemoApps/GRDBCombineDemo/README.md b/Documentation/DemoApps/GRDBCombineDemo/README.md deleted file mode 100644 index 6b2ccec0f..000000000 --- a/Documentation/DemoApps/GRDBCombineDemo/README.md +++ /dev/null @@ -1,51 +0,0 @@ -Combine + SwiftUI Demo Application -================================== - - - -**This demo application is a Combine + SwiftUI application.** For a demo application that uses UIKit, see [GRDBDemoiOS](../GRDBDemoiOS/README.md), and for Async/Await + SwiftUI, see [GRDBAsyncDemo](../GRDBAsyncDemo/README.md). - -**Requirements**: iOS 15.0+ / Xcode 12+ - -> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration. - -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) Combine publishers. -- 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:** - -- [GRDBCombineDemoApp.swift](GRDBCombineDemo/GRDBCombineDemoApp.swift) - - `GRDBCombineDemoApp` feeds the app views with a database, through the SwiftUI environment. - -- [AppDatabase.swift](GRDBCombineDemo/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. - -- [Persistence.swift](GRDBCombineDemo/Persistence.swift) - - This file instantiates various `AppDatabase` for the various projects needs: one database on disk for the application, and in-memory databases for SwiftUI previews. - -- [Player.swift](GRDBCombineDemo/Player.swift) - - `Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). - -- [PlayerRequest.swift](GRDBCombineDemo/PlayerRequest.swift), [AppView.swift](GRDBCombineDemo/Views/AppView.swift) - - `PlayerRequest` defines the player requests used by the app (sorted by score, or by name). - - `PlayerRequest` feeds the `@Query` property wrapper (`@Query`, defined in [GRDBQuery](https://github.com/groue/GRDBQuery), allows SwiftUI views to display up-to-date database content). - - `AppView` is the SwiftUI view that uses `@Query` in order to feed its player list. - -- [GRDBCombineDemoTests](GRDBCombineDemoTests) - - - Test the database schema - - Test the `Player` record and its requests - - Test the `PlayerRequest` methods that feed the list of players. - - Test the `AppDatabase` methods that let the app access the database. diff --git a/Documentation/DemoApps/GRDBCombineDemo/Screenshot.png b/Documentation/DemoApps/GRDBCombineDemo/Screenshot.png deleted file mode 100644 index 053682185..000000000 Binary files a/Documentation/DemoApps/GRDBCombineDemo/Screenshot.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/project.pbxproj new file mode 100644 index 000000000..47782e062 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/project.pbxproj @@ -0,0 +1,503 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXBuildFile section */ + 56CFC6772C9F1E1B000B5023 /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56CFC6762C9F1E1B000B5023 /* GRDB */; }; + 56CFC6E42C9F5AEA000B5023 /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56CFC6E32C9F5AEA000B5023 /* GRDB */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 56CFC6552C9F1DCA000B5023 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56CFC63C2C9F1DC9000B5023 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 56CFC6432C9F1DC9000B5023; + remoteInfo = GRDBDemo; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 56CFC6442C9F1DC9000B5023 /* GRDBDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 56CFC6542C9F1DCA000B5023 /* GRDBDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 56CFC6B82C9F544D000B5023 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ + 56CFC6AA2C9F3ADB000B5023 /* Exceptions for "GRDBDemo" folder in "GRDBDemo" target */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + Info.plist, + ); + target = 56CFC6432C9F1DC9000B5023 /* GRDBDemo */; + }; +/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + 56CFC6462C9F1DC9000B5023 /* GRDBDemo */ = { + isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + 56CFC6AA2C9F3ADB000B5023 /* Exceptions for "GRDBDemo" folder in "GRDBDemo" target */, + ); + path = GRDBDemo; + sourceTree = ""; + }; + 56CFC6572C9F1DCA000B5023 /* GRDBDemoTests */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = GRDBDemoTests; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + 56CFC6412C9F1DC9000B5023 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 56CFC6772C9F1E1B000B5023 /* GRDB in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 56CFC6512C9F1DCA000B5023 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 56CFC6E42C9F5AEA000B5023 /* GRDB in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 56CFC63B2C9F1DC9000B5023 = { + isa = PBXGroup; + children = ( + 56CFC6B82C9F544D000B5023 /* README.md */, + 56CFC6462C9F1DC9000B5023 /* GRDBDemo */, + 56CFC6572C9F1DCA000B5023 /* GRDBDemoTests */, + 56CFC6E22C9F5AEA000B5023 /* Frameworks */, + 56CFC6452C9F1DC9000B5023 /* Products */, + ); + sourceTree = ""; + }; + 56CFC6452C9F1DC9000B5023 /* Products */ = { + isa = PBXGroup; + children = ( + 56CFC6442C9F1DC9000B5023 /* GRDBDemo.app */, + 56CFC6542C9F1DCA000B5023 /* GRDBDemoTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 56CFC6E22C9F5AEA000B5023 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 56CFC6432C9F1DC9000B5023 /* GRDBDemo */ = { + isa = PBXNativeTarget; + buildConfigurationList = 56CFC6682C9F1DCB000B5023 /* Build configuration list for PBXNativeTarget "GRDBDemo" */; + buildPhases = ( + 56CFC6402C9F1DC9000B5023 /* Sources */, + 56CFC6412C9F1DC9000B5023 /* Frameworks */, + 56CFC6422C9F1DC9000B5023 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + 56CFC6462C9F1DC9000B5023 /* GRDBDemo */, + ); + name = GRDBDemo; + packageProductDependencies = ( + 56CFC6762C9F1E1B000B5023 /* GRDB */, + ); + productName = GRDBDemo; + productReference = 56CFC6442C9F1DC9000B5023 /* GRDBDemo.app */; + productType = "com.apple.product-type.application"; + }; + 56CFC6532C9F1DCA000B5023 /* GRDBDemoTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 56CFC66B2C9F1DCB000B5023 /* Build configuration list for PBXNativeTarget "GRDBDemoTests" */; + buildPhases = ( + 56CFC6502C9F1DCA000B5023 /* Sources */, + 56CFC6512C9F1DCA000B5023 /* Frameworks */, + 56CFC6522C9F1DCA000B5023 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 56CFC6562C9F1DCA000B5023 /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + 56CFC6572C9F1DCA000B5023 /* GRDBDemoTests */, + ); + name = GRDBDemoTests; + packageProductDependencies = ( + 56CFC6E32C9F5AEA000B5023 /* GRDB */, + ); + productName = GRDBDemoTests; + productReference = 56CFC6542C9F1DCA000B5023 /* GRDBDemoTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 56CFC63C2C9F1DC9000B5023 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 1600; + TargetAttributes = { + 56CFC6432C9F1DC9000B5023 = { + CreatedOnToolsVersion = 16.0; + }; + 56CFC6532C9F1DCA000B5023 = { + CreatedOnToolsVersion = 16.0; + TestTargetID = 56CFC6432C9F1DC9000B5023; + }; + }; + }; + buildConfigurationList = 56CFC63F2C9F1DC9000B5023 /* Build configuration list for PBXProject "GRDBDemo" */; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 56CFC63B2C9F1DC9000B5023; + minimizedProjectReferenceProxies = 1; + packageReferences = ( + 56CFC6752C9F1E1B000B5023 /* XCLocalSwiftPackageReference "../../../../GRDB.swift" */, + ); + preferredProjectObjectVersion = 77; + productRefGroup = 56CFC6452C9F1DC9000B5023 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 56CFC6432C9F1DC9000B5023 /* GRDBDemo */, + 56CFC6532C9F1DCA000B5023 /* GRDBDemoTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 56CFC6422C9F1DC9000B5023 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 56CFC6522C9F1DCA000B5023 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 56CFC6402C9F1DC9000B5023 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 56CFC6502C9F1DCA000B5023 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 56CFC6562C9F1DCA000B5023 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 56CFC6432C9F1DC9000B5023 /* GRDBDemo */; + targetProxy = 56CFC6552C9F1DCA000B5023 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 56CFC6662C9F1DCB000B5023 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 56CFC6672C9F1DCB000B5023 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.6; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_EMIT_LOC_STRINGS = YES; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 56CFC6692C9F1DCB000B5023 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_ASSET_PATHS = "\"GRDBDemo/Preview Content\""; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = GRDBDemo/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = "GRDB Demo"; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 56CFC66A2C9F1DCB000B5023 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_ASSET_PATHS = "\"GRDBDemo/Preview Content\""; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = GRDBDemo/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = "GRDB Demo"; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemo; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + 56CFC66C2C9F1DCB000B5023 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo"; + }; + name = Debug; + }; + 56CFC66D2C9F1DCB000B5023 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 6.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemo.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/GRDBDemo"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 56CFC63F2C9F1DC9000B5023 /* Build configuration list for PBXProject "GRDBDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56CFC6662C9F1DCB000B5023 /* Debug */, + 56CFC6672C9F1DCB000B5023 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 56CFC6682C9F1DCB000B5023 /* Build configuration list for PBXNativeTarget "GRDBDemo" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56CFC6692C9F1DCB000B5023 /* Debug */, + 56CFC66A2C9F1DCB000B5023 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 56CFC66B2C9F1DCB000B5023 /* Build configuration list for PBXNativeTarget "GRDBDemoTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56CFC66C2C9F1DCB000B5023 /* Debug */, + 56CFC66D2C9F1DCB000B5023 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 56CFC6752C9F1E1B000B5023 /* XCLocalSwiftPackageReference "../../../../GRDB.swift" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ../../../../GRDB.swift; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 56CFC6762C9F1E1B000B5023 /* GRDB */ = { + isa = XCSwiftPackageProductDependency; + productName = GRDB; + }; + 56CFC6E32C9F5AEA000B5023 /* GRDB */ = { + isa = XCSwiftPackageProductDependency; + package = 56CFC6752C9F1E1B000B5023 /* XCLocalSwiftPackageReference "../../../../GRDB.swift" */; + productName = GRDB; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 56CFC63C2C9F1DC9000B5023 /* Project object */; +} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata similarity index 100% rename from Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata rename to Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme b/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/xcshareddata/xcschemes/GRDBDemo.xcscheme similarity index 70% rename from Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme rename to Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/xcshareddata/xcschemes/GRDBDemo.xcscheme index 20c4615d2..386a9790f 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj/xcshareddata/xcschemes/GRDBDemo.xcscheme @@ -1,10 +1,11 @@ + LastUpgradeVersion = "1600" + version = "1.7"> + buildImplicitDependencies = "YES" + buildArchitectures = "Automatic"> + BlueprintIdentifier = "56CFC6432C9F1DC9000B5023" + BuildableName = "GRDBDemo.app" + BlueprintName = "GRDBDemo" + ReferencedContainer = "container:GRDBDemo.xcodeproj"> @@ -26,17 +27,18 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - shouldUseLaunchSchemeArgsEnv = "YES"> + shouldUseLaunchSchemeArgsEnv = "YES" + shouldAutocreateTestPlan = "YES"> + BlueprintIdentifier = "56CFC6532C9F1DCA000B5023" + BuildableName = "GRDBDemoTests.xctest" + BlueprintName = "GRDBDemoTests" + ReferencedContainer = "container:GRDBDemo.xcodeproj"> @@ -55,10 +57,10 @@ runnableDebuggingMode = "0"> + BlueprintIdentifier = "56CFC6432C9F1DC9000B5023" + BuildableName = "GRDBDemo.app" + BlueprintName = "GRDBDemo" + ReferencedContainer = "container:GRDBDemo.xcodeproj"> @@ -79,10 +81,10 @@ runnableDebuggingMode = "0"> + BlueprintIdentifier = "56CFC6432C9F1DC9000B5023" + BuildableName = "GRDBDemo.app" + BlueprintName = "GRDBDemo" + ReferencedContainer = "container:GRDBDemo.xcodeproj"> diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/AppDatabase.swift similarity index 59% rename from Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift rename to Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/AppDatabase.swift index 8c38cd2a7..9ce44f0ae 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/AppDatabase.swift @@ -1,105 +1,48 @@ +import Foundation import GRDB import os.log -/// `AppDatabase` lets the application access the database. -/// -/// You create an `AppDatabase` with a connection to an SQLite database -/// (see ). -/// -/// Create those connections with a configuration returned from -/// `AppDatabase/makeConfiguration(_:)`. +/// The type that provides access to the application database. /// /// For example: /// /// ```swift -/// // Create an in-memory AppDatabase +/// // Create an empty, in-memory, AppDatabase /// let config = AppDatabase.makeConfiguration() /// let dbQueue = try DatabaseQueue(configuration: config) /// let appDatabase = try AppDatabase(dbQueue) /// ``` -struct AppDatabase { - /// Creates an `AppDatabase`, and makes sure the database schema +final class AppDatabase: Sendable { + /// Access to the database. + /// + /// See + private let dbWriter: any DatabaseWriter + + /// Creates a `AppDatabase`, and makes sure the database schema /// is ready. /// /// - important: Create the `DatabaseWriter` with a configuration /// returned by ``makeConfiguration(_:)``. - init(_ dbWriter: any DatabaseWriter) throws { + init(_ dbWriter: any GRDB.DatabaseWriter) throws { self.dbWriter = dbWriter try migrator.migrate(dbWriter) } - /// Provides access to the database. - /// - /// Application can use a `DatabasePool`, and tests can use a fast - /// in-memory `DatabaseQueue`. - /// - /// See - private let dbWriter: any DatabaseWriter -} - -// MARK: - Database Configuration - -extension AppDatabase { - private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL") - - /// Returns a database configuration suited for `PlayerRepository`. - /// - /// SQL statements are logged if the `SQL_TRACE` environment variable - /// is set. - /// - /// - parameter base: A base configuration. - public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration { - var config = base - - // An opportunity to add required custom SQL functions or - // collations, if needed: - // config.prepareDatabase { db in - // db.add(function: ...) - // } - - // Log SQL statements if the `SQL_TRACE` environment variable is set. - // See - if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil { - config.prepareDatabase { db in - db.trace { - // It's ok to log statements publicly. Sensitive - // information (statement arguments) are not logged - // unless config.publicStatementArguments is set - // (see below). - os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0)) - } - } - } - -#if DEBUG - // Protect sensitive information by enabling verbose debugging in - // DEBUG builds only. - // See - config.publicStatementArguments = true -#endif - - return config - } -} - -// MARK: - Database Migrations - -extension AppDatabase { /// The DatabaseMigrator that defines the database schema. /// - /// See + /// See private var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() #if DEBUG // Speed up development by nuking the database when migrations change - // See + // See migrator.eraseDatabaseOnSchemaChange = true #endif - migrator.registerMigration("createPlayer") { db in + migrator.registerMigration("v1") { db in // Create a table - // See + // See try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() @@ -116,8 +59,51 @@ extension AppDatabase { } } +// MARK: - Database Configuration + +extension AppDatabase { + // Uncomment for enabling SQL logging + // private static let sqlLogger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "SQL") + + /// Returns a database configuration suited for `AppDatabase`. + /// + /// - parameter config: A base configuration. + static func makeConfiguration(_ config: Configuration = Configuration()) -> Configuration { + // var config = config + // + // Add custom SQL functions or collations, if needed: + // config.prepareDatabase { db in + // db.add(function: ...) + // } + // + // Uncomment for enabling SQL logging if the `SQL_TRACE` environment variable is set. + // See + // if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil { + // config.prepareDatabase { db in + // let dbName = db.description + // db.trace { event in + // // Sensitive information (statement arguments) is not + // // logged unless config.publicStatementArguments is set + // // (see below). + // sqlLogger.debug("\(dbName): \(event)") + // } + // } + // } + // + // #if DEBUG + // // Protect sensitive information by enabling verbose debugging in + // // DEBUG builds only. + // // See + // config.publicStatementArguments = true + // #endif + + return config + } +} + // MARK: - Database Access: Writes // The write methods execute invariant-preserving database transactions. +// In this demo repository, they are pretty simple. extension AppDatabase { /// Saves (inserts or updates) a player. When the method returns, the @@ -131,7 +117,7 @@ extension AppDatabase { /// Delete the specified players func deletePlayers(ids: [Int64]) throws { try dbWriter.write { db in - _ = try Player.deleteAll(db, ids: ids) + _ = try Player.deleteAll(db, keys: ids) } } @@ -143,8 +129,8 @@ extension AppDatabase { } /// Refresh all players (by performing some random changes, for demo purpose). - func refreshPlayers() throws { - try dbWriter.write { db in + func refreshPlayers() async throws { + try await dbWriter.write { [self] db in if try Player.all().isEmpty(db) { // When database is empty, insert new random players try createRandomPlayers(db) @@ -193,8 +179,8 @@ extension AppDatabase { // In your app, you are free to choose another path, and define focused // reading methods. extension AppDatabase { - /// Provides a read-only access to the database - var reader: DatabaseReader { + /// Provides a read-only access to the database. + var reader: any GRDB.DatabaseReader { dbWriter } } diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/Models/Player.swift similarity index 57% rename from Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift rename to Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/Models/Player.swift index 7876b049d..d92014c55 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/Models/Player.swift @@ -5,7 +5,7 @@ import GRDB /// Identifiable conformance supports SwiftUI list animations, and type-safe /// GRDB primary key methods. /// Equatable conformance supports tests. -struct Player: Identifiable, Equatable { +struct Player: Equatable { /// The player id. /// /// Int64 is the recommended type for auto-incremented database ids. @@ -47,14 +47,14 @@ extension Player { } } -// MARK: - Persistence +// MARK: - Database /// Make Player a Codable Record. /// /// See extension Player: Codable, FetchableRecord, MutablePersistableRecord { // Define database columns from CodingKeys - fileprivate enum Columns { + enum Columns { static let name = Column(CodingKeys.name) static let score = Column(CodingKeys.score) } @@ -64,42 +64,3 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord { id = inserted.rowID } } - -// MARK: - Player Database Requests - -/// Define some player requests used by the application. -/// -/// See -extension DerivableRequest { - /// A request of players ordered by name. - /// - /// For example: - /// - /// let players: [Player] = try dbWriter.read { db in - /// try Player.all().orderedByName().fetchAll(db) - /// } - func orderedByName() -> Self { - // Sort by name in a localized case insensitive fashion - // See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison - order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare)) - } - - /// A request of players ordered by score. - /// - /// For example: - /// - /// let players: [Player] = try dbWriter.read { db in - /// try Player.all().orderedByScore().fetchAll(db) - /// } - /// let bestPlayer: Player? = try dbWriter.read { db in - /// try Player.all().orderedByScore().fetchOne(db) - /// } - func orderedByScore() -> Self { - // Sort by descending score, and then by name, in a - // localized case insensitive fashion - // See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison - order( - Player.Columns.score.desc, - Player.Columns.name.collating(.localizedCaseInsensitiveCompare)) - } -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Persistence.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/Persistence.swift similarity index 69% rename from Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Persistence.swift rename to Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/Persistence.swift index 96267e684..51f3e4fd7 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Persistence.swift +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Database/Persistence.swift @@ -8,8 +8,8 @@ extension AppDatabase { private static func makeShared() -> AppDatabase { do { // Apply recommendations from - // - // + // + // Create the "Application Support/Database" directory if needed let fileManager = FileManager.default let appSupportURL = try fileManager.url( @@ -20,11 +20,8 @@ extension AppDatabase { // Open or create the database let databaseURL = directoryURL.appendingPathComponent("db.sqlite") - NSLog("Database stored at \(databaseURL.path)") - let dbPool = try DatabasePool( - path: databaseURL.path, - // Use default AppDatabase configuration - configuration: AppDatabase.makeConfiguration()) + let config = AppDatabase.makeConfiguration() + let dbPool = try DatabasePool(path: databaseURL.path, configuration: config) // Create the AppDatabase let appDatabase = try AppDatabase(dbPool) @@ -46,4 +43,19 @@ extension AppDatabase { fatalError("Unresolved error \(error)") } } + + /// 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 + let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration()) + return try! AppDatabase(dbQueue) + } + + /// Creates a database full of random players for SwiftUI previews + static func random() -> AppDatabase { + let appDatabase = empty() + try! appDatabase.createRandomPlayersIfEmpty() + return appDatabase + } } diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/GRDBDemoApp.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/GRDBDemoApp.swift new file mode 100644 index 000000000..a08232a76 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/GRDBDemoApp.swift @@ -0,0 +1,22 @@ +import SwiftUI + +@main +struct GRDBDemoApp: App { + var body: some Scene { + WindowGroup { + PlayersNavigationView().appDatabase(.shared) + } + } +} + +// MARK: - Give SwiftUI access to the database + +extension EnvironmentValues { + @Entry var appDatabase = AppDatabase.empty() +} + +extension View { + func appDatabase(_ appDatabase: AppDatabase) -> some View { + self.environment(\.appDatabase, appDatabase) + } +} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Info.plist similarity index 65% rename from Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist rename to Documentation/DemoApps/GRDBDemo/GRDBDemo/Info.plist index 18d981003..0427f524a 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Info.plist @@ -2,7 +2,10 @@ - IDEDidComputeMac32BitWarning - + UILaunchScreen + + UIImageName + LaunchScreen + diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Preview Content/Preview Assets.xcassets/Contents.json b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Preview Content/Preview Assets.xcassets/Contents.json similarity index 100% rename from Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Preview Content/Preview Assets.xcassets/Contents.json rename to Documentation/DemoApps/GRDBDemo/GRDBDemo/Preview Content/Preview Assets.xcassets/Contents.json diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AccentColor.colorset/Contents.json b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AccentColor.colorset/Contents.json similarity index 100% rename from Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/AccentColor.colorset/Contents.json rename to Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AccentColor.colorset/Contents.json diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..3395dad77 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,37 @@ +{ + "images" : [ + { + "filename" : "Icon-Light-1024×1024.png", + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "filename" : "Icon-Dark-1024×1024.png", + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "tinted" + } + ], + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon-Dark-1024×1024.png b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon-Dark-1024×1024.png new file mode 100644 index 000000000..d20dbec5c Binary files /dev/null and b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon-Dark-1024×1024.png differ diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon-Light-1024×1024.png b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon-Light-1024×1024.png new file mode 100644 index 000000000..f456cd22f Binary files /dev/null and b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/AppIcon.appiconset/Icon-Light-1024×1024.png differ diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/Contents.json b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/Contents.json similarity index 100% rename from Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/Contents.json rename to Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/Contents.json diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/LaunchScreen.imageset/Contents.json b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/LaunchScreen.imageset/Contents.json new file mode 100644 index 000000000..898861471 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/LaunchScreen.imageset/Contents.json @@ -0,0 +1,22 @@ +{ + "images" : [ + { + "filename" : "LaunchIcon.pdf", + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "filename" : "LaunchIcon~Dark.pdf", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/LaunchIcon.imageset/LaunchIcon.pdf b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/LaunchScreen.imageset/LaunchIcon.pdf similarity index 100% rename from Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo/Resources/Assets.xcassets/LaunchIcon.imageset/LaunchIcon.pdf rename to Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/LaunchScreen.imageset/LaunchIcon.pdf diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/LaunchScreen.imageset/LaunchIcon~Dark.pdf b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/LaunchScreen.imageset/LaunchIcon~Dark.pdf new file mode 100644 index 000000000..cc67d9796 Binary files /dev/null and b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Assets.xcassets/LaunchScreen.imageset/LaunchIcon~Dark.pdf differ diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Localizable.xcstrings b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Localizable.xcstrings new file mode 100644 index 000000000..8d20dbef0 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Resources/Localizable.xcstrings @@ -0,0 +1,89 @@ +{ + "sourceLanguage" : "en", + "strings" : { + "" : { + + }, + "%lld Players" : { + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 Player" + } + }, + "other" : { + "stringUnit" : { + "state" : "new", + "value" : "%lld Players" + } + }, + "zero" : { + "stringUnit" : { + "state" : "translated", + "value" : "No Player" + } + } + } + } + } + } + }, + "%lld points" : { + "localizations" : { + "en" : { + "variations" : { + "plural" : { + "one" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 point" + } + }, + "other" : { + "stringUnit" : { + "state" : "new", + "value" : "%lld points" + } + }, + "zero" : { + "stringUnit" : { + "state" : "translated", + "value" : "0 point" + } + } + } + } + } + } + }, + "Add Player" : { + + }, + "Anonymous" : { + + }, + "Cancel" : { + + }, + "Name" : { + + }, + "New Player" : { + + }, + "Save" : { + + }, + "Score" : { + + }, + "The team is empty!" : { + + } + }, + "version" : "1.0" +} \ No newline at end of file diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerCreationSheet.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerCreationSheet.swift new file mode 100644 index 000000000..c52634804 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerCreationSheet.swift @@ -0,0 +1,39 @@ +import SwiftUI + +/// A view that creates a `Player`. Display it as a sheet. +struct PlayerCreationSheet: View { + @Environment(\.appDatabase) var appDatabase + @Environment(\.dismiss) var dismiss + @State var form = PlayerForm(name: "", score: nil) + + var body: some View { + NavigationStack { + Form { + PlayerFormView(form: $form) + } + .navigationTitle("New Player") + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { + save() + } + } + } + } + } + + private func save() { + var player = Player(name: form.name, score: form.score ?? 0) + try? appDatabase.savePlayer(&player) + dismiss() + } +} + +// MARK: - Previews + +#Preview { + PlayerCreationSheet() +} diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerEditionView.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerEditionView.swift new file mode 100644 index 000000000..0bbe76aa7 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerEditionView.swift @@ -0,0 +1,41 @@ +import SwiftUI + +struct PlayerEditionView: View { + @Environment(\.isPresented) var isPresented + @Environment(\.appDatabase) var appDatabase + @State var form: PlayerForm + var player: Player + + init(player: Player) { + self.player = player + self._form = State(initialValue: PlayerForm(name: player.name, score: player.score)) + } + + var body: some View { + Form { + PlayerFormView(form: $form) + } + .navigationTitle(player.name) + .onChange(of: isPresented) { + if !isPresented { + // Back button was pressed + save() + } + } + } + + private func save() { + var player = player + player.name = form.name + player.score = form.score ?? 0 + try? appDatabase.savePlayer(&player) + } +} + +// MARK: - Previews + +#Preview { + NavigationStack { + PlayerEditionView(player: .makeRandom()) + } +} diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerFormView.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerFormView.swift new file mode 100644 index 000000000..32172b020 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerFormView.swift @@ -0,0 +1,64 @@ +import SwiftUI + +/// A view that edits a `PlayerForm`. +struct PlayerFormView: View { + @Binding var form: PlayerForm + + private enum FocusElement { + case name + case score + } + @FocusState private var focusedElement: FocusElement? + + var body: some View { + Group { + LabeledContent { + TextField(text: $form.name) { EmptyView() } + .textInputAutocapitalization(.words) + .autocorrectionDisabled() + .submitLabel(.next) + .focused($focusedElement, equals: .name) + .labelsHidden() + .onSubmit { + focusedElement = .score + } + } label: { + Text("Name").foregroundStyle(.secondary) + } + + LabeledContent { + TextField(value: $form.score, format: .number) { EmptyView() } + .keyboardType(.numberPad) + .focused($focusedElement, equals: .score) + .labelsHidden() + } label: { + Text("Score").foregroundStyle(.secondary) + } + } + .onAppear { focusedElement = .name } + } +} + +/// The model edited by `PlayerFormView`. +struct PlayerForm { + var name: String + var score: Int? +} + +// MARK: - Previews + +#Preview("Prefilled") { + @Previewable @State var form = PlayerForm(name: "John", score: 100) + + Form { + PlayerFormView(form: $form) + } +} + +#Preview("Empty") { + @Previewable @State var form = PlayerForm(name: "", score: nil) + + Form { + PlayerFormView(form: $form) + } +} diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListModel.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListModel.swift new file mode 100644 index 000000000..0ea0b85ef --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListModel.swift @@ -0,0 +1,95 @@ +import Foundation +import Observation +import GRDB + +/// The observable model that drives the main navigation view. +/// +/// It observes the database in order to always display an up-to-date list +/// of players. +/// +/// This class is testable. See `PlayerListModelTests.swift`. +@Observable @MainActor final class PlayerListModel { + /// A player ordering + enum Ordering { + case byName + case byScore + } + + /// The player ordering + var ordering = Ordering.byScore { + didSet { observePlayers() } + } + + /// The players. + /// + /// The array remains empty until `observePlayers()` is called. + var players: [Player] = [] + + private let appDatabase: AppDatabase + @ObservationIgnored private var cancellable: AnyDatabaseCancellable? + + // MARK: - Initialization + + /// Creates a `PlayerListModel`. + init(appDatabase: AppDatabase) { + self.appDatabase = appDatabase + } + + /// Start observing the database. + func observePlayers() { + // We observe all players, sorted according to `ordering`. + let observation = ValueObservation.tracking { [ordering] db in + switch ordering { + case .byName: + try Player + .order { $0.name.collating(.localizedCaseInsensitiveCompare) } + .fetchAll(db) + case .byScore: + try Player + .order { [ + $0.score.desc, + $0.name.collating(.localizedCaseInsensitiveCompare), + ] } + .fetchAll(db) + } + } + + // Start observing the database. + // Previous observation, if any, is cancelled. + cancellable = observation.start(in: appDatabase.reader) { error in + // Handle error + } onChange: { [unowned self] players in + self.players = players + } + } + + // MARK: - Actions + + /// Delete players at specified indexes in `self.players`. + func deletePlayers(at offsets: IndexSet) throws { + let playerIds = offsets.compactMap { players[$0].id } + try appDatabase.deletePlayers(ids: playerIds) + } + + /// Delete all players. + func deleteAllPlayers() throws { + try appDatabase.deleteAllPlayers() + } + + /// Refresh all players (by performing some random changes, for demo purpose). + func refreshPlayers() async throws { + try await appDatabase.refreshPlayers() + } + + /// Perform 50 refreshes in parallel, for demo purpose. + func refreshPlayersManyTimes() async throws { + try await withThrowingTaskGroup(of: Void.self) { group in + for _ in 0..<50 { + group.addTask { + try await AppDatabase.shared.refreshPlayers() + } + } + for try await _ in group { } + } + } +} diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListView.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListView.swift new file mode 100644 index 000000000..0f3316512 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayerListView.swift @@ -0,0 +1,76 @@ +import SwiftUI + +/// A view that displays a list of players. +struct PlayerListView: View { + @Bindable var model: PlayerListModel + + var body: some View { + List { + ForEach(model.players, id: \.id) { player in + NavigationLink { + PlayerEditionView(player: player) + } label: { + PlayerRow(player: player) + } + } + .onDelete { offsets in + try? model.deletePlayers(at: offsets) + } + } + .animation(.default, value: model.players) + .listStyle(.plain) + .navigationTitle("\(model.players.count) Players") + } +} + +struct PlayerRow: View { + var player: Player + + var body: some View { + HStack { + Group { + if player.name.isEmpty { + Text("Anonymous").italic() + } else { + Text(player.name) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + + Text("\(player.score) points") + .monospacedDigit() + .foregroundStyle(.secondary) + } + } +} + +// MARK: - Previews + +#Preview { + struct Preview: View { + @Environment(\.appDatabase) var appDatabase + + var body: some View { + // This technique makes it possible to create an observable object + // (PlayerListModel) from the SwiftUI environment. + ContentView(appDatabase: appDatabase) + } + } + + struct ContentView: View { + @State var model: PlayerListModel + + init(appDatabase: AppDatabase) { + _model = State(initialValue: PlayerListModel(appDatabase: appDatabase)) + } + + var body: some View { + NavigationStack { + PlayerListView(model: model) + } + .onAppear { model.observePlayers() } + } + } + + return Preview().appDatabase(.random()) +} diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayersNavigationView.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayersNavigationView.swift new file mode 100644 index 000000000..b6e96ac2d --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemo/Views/PlayersNavigationView.swift @@ -0,0 +1,181 @@ +import SwiftUI + +/// The main navigation view. +struct PlayersNavigationView: View { + @Environment(\.appDatabase) var appDatabase + + var body: some View { + // This technique makes it possible to create an observable object + // (PlayerListModel) from the SwiftUI environment. + ContentView(appDatabase: appDatabase) + } +} + +private struct ContentView: View { + /// The model for the player list. + @State var model: PlayerListModel + + /// Tracks the edit mode of the player list. + @State var editMode = EditMode.inactive + + /// Tracks the presentation of the player creation sheet. + @State var presentsCreationSheet = false + + init(appDatabase: AppDatabase) { + _model = State(initialValue: PlayerListModel(appDatabase: appDatabase)) + } + + var body: some View { + NavigationStack { + contentView + .toolbar { bottomBarContent } + .environment(\.editMode, $editMode) + } + .onAppear { + model.observePlayers() + } + .onChange(of: model.ordering) { + // Stop editing when ordering is modified + stopEditing() + } + .onChange(of: model.players.isEmpty) { + // Stop editing when the last player is deleted. + if model.players.isEmpty { + stopEditing() + } + } + .sheet(isPresented: $presentsCreationSheet) { + PlayerCreationSheet() + } + } + + @ViewBuilder + private var contentView: some View { + if model.players.isEmpty { + emptyPlayersView + } else { + PlayerListView(model: model) + .toolbar { + ToolbarItemGroup(placement: .topBarLeading) { + presentCreationSheetButton + EditButton() + } + ToolbarItem(placement: .topBarTrailing) { + ToggleOrderingButton(ordering: $model.ordering) + } + } + } + } + + private var emptyPlayersView: some View { + ContentUnavailableView { + Label("The team is empty!", systemImage: "person.slash") + } actions: { + Button("Add Player") { + presentsCreationSheet = true + } + .buttonStyle(.borderedProminent) + } + // Hide the title, but set a string anyway in order to avoid + // an odd relayout when player list becomes empty during + // the tornado. + .navigationTitle("") + } + + @ToolbarContentBuilder + private var bottomBarContent: some ToolbarContent { + ToolbarItemGroup(placement: .bottomBar) { + deleteAllButton + Spacer() + refreshButton + Spacer() + tornadoButton + } + } + + private var presentCreationSheetButton: some View { + Button { + stopEditing() + presentsCreationSheet = true + } label: { + Image(systemName: "plus") + } + } + + private var deleteAllButton: some View { + Button { + try? model.deleteAllPlayers() + } label: { + Image(systemName: "trash") + } + } + + private var refreshButton: some View { + Button { + Task { + stopEditing() + try? await model.refreshPlayers() + } + } label: { + Image(systemName: "arrow.clockwise") + } + } + + private var tornadoButton: some View { + Button { + Task { + stopEditing() + try? await model.refreshPlayersManyTimes() + } + } label: { + Image(systemName: "tornado") + } + } + + private func stopEditing() { + withAnimation { + editMode = .inactive + } + } +} + +private struct ToggleOrderingButton: View { + @Binding var ordering: PlayerListModel.Ordering + + var body: some View { + switch ordering { + case .byName: + Button { + ordering = .byScore + } label: { + buttonLabel("Name", systemImage: "arrowtriangle.up.fill") + } + case .byScore: + Button { + ordering = .byName + } label: { + buttonLabel("Score", systemImage: "arrowtriangle.down.fill") + } + } + } + + private func buttonLabel(_ title: LocalizedStringKey, systemImage: String) -> some View { + HStack { + Text(title) + Image(systemName: systemImage) + .imageScale(.medium) + } + } +} + +// MARK: - Previews + +#Preview("Populated") { + PlayersNavigationView() + .appDatabase(.random()) +} + +#Preview("Empty") { + PlayersNavigationView() + .appDatabase(.empty()) +} diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemoTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemoTests/AppDatabaseTests.swift new file mode 100644 index 000000000..29b22ad86 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemoTests/AppDatabaseTests.swift @@ -0,0 +1,58 @@ +import Testing +import GRDB +@testable import GRDBDemo + +struct AppDatabaseTests { + @Test func insert() throws { + // Given an empty database + let appDatabase = try makeEmptyTestDatabase() + + // When we insert a player + var insertedPlayer = Player(name: "Arthur", score: 1000) + try appDatabase.savePlayer(&insertedPlayer) + + // Then the inserted player has an id + #expect(insertedPlayer.id != nil) + + // Then the inserted player exists in the database + let fetchedPlayer = try appDatabase.reader.read(Player.fetchOne) + #expect(fetchedPlayer == insertedPlayer) + } + + @Test func update() throws { + // Given a database that contains a player + let appDatabase = try makeEmptyTestDatabase() + var insertedPlayer = Player(name: "Arthur", score: 1000) + try appDatabase.savePlayer(&insertedPlayer) + + // When we update a player + var updatedPlayer = insertedPlayer + updatedPlayer.name = "Barbara" + updatedPlayer.score = 0 + try appDatabase.savePlayer(&updatedPlayer) + + // Then the player is updated + let fetchedPlayer = try appDatabase.reader.read(Player.fetchOne) + #expect(fetchedPlayer == updatedPlayer) + } + + @Test func deleteAll() throws { + // Given a database that contains a player + let appDatabase = try makeEmptyTestDatabase() + var player = Player(name: "Arthur", score: 1000) + try appDatabase.savePlayer(&player) + + // When we delete all players + try appDatabase.deleteAllPlayers() + + // Then no player exists + let count = try appDatabase.reader.read(Player.fetchCount(_:)) + #expect(count == 0) + } + + /// Return an empty, in-memory, `AppDatabase`. + private func makeEmptyTestDatabase() throws -> AppDatabase { + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) + return try AppDatabase(dbQueue) + } +} diff --git a/Documentation/DemoApps/GRDBDemo/GRDBDemoTests/PlayerListModelTests.swift b/Documentation/DemoApps/GRDBDemo/GRDBDemoTests/PlayerListModelTests.swift new file mode 100644 index 000000000..0a1857365 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/GRDBDemoTests/PlayerListModelTests.swift @@ -0,0 +1,78 @@ +import Testing +import GRDB +@testable import GRDBDemo + +struct PlayerListModelTests { + // MARK: - PlayerListModel.observePlayers tests + + @Test(.timeLimit(.minutes(1))) + @MainActor func observation_grabs_current_database_state() async throws { + // Given a PlayerListModel on a database that contains one player + let appDatabase = try makeEmptyTestDatabase() + var player = Player(name: "Arthur", score: 1000) + try appDatabase.savePlayer(&player) + let model = PlayerListModel(appDatabase: appDatabase) + + // When the model starts observing the database + model.observePlayers() + + // Then the model eventually has one player. + try await pollUntil { model.players.count == 1 } + } + + @Test(.timeLimit(.minutes(1))) + @MainActor func observation_grabs_database_changes() async throws { + // Given a PlayerListModel that has one player + let appDatabase = try makeEmptyTestDatabase() + var player1 = Player(name: "Arthur", score: 1000) + try appDatabase.savePlayer(&player1) + let model = PlayerListModel(appDatabase: appDatabase) + model.observePlayers() + try await pollUntil { model.players.count == 1 } + + // When we insert a second player + var player2 = Player(name: "Barbara", score: 800) + try appDatabase.savePlayer(&player2) + + // Then the model eventually has two players. + try await pollUntil { model.players.count == 2 } + } + + @Test + @MainActor func test_deleteAllPlayers_deletes_players_in_the_database() async throws { + // Given a PlayerListModel on a database that contains a player + let appDatabase = try makeEmptyTestDatabase() + var player = Player(name: "Arthur", score: 1000) + try appDatabase.savePlayer(&player) + let model = PlayerListModel(appDatabase: appDatabase) + + // When we delete all players + try model.deleteAllPlayers() + + // Then the database is empty. + let playerCount = try await appDatabase.reader.read { db in + try Player.fetchCount(db) + } + #expect(playerCount == 0) + } + + /// Return an empty, in-memory, `AppDatabase`. + private func makeEmptyTestDatabase() throws -> AppDatabase { + let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) + return try AppDatabase(dbQueue) + } + + /// Convenience method that loops until a condition is met. + private func pollUntil(condition: @escaping @MainActor () async -> Bool) async throws { + try await confirmation { confirmation in + while true { + if await condition() { + confirmation() + return + } else { + try await Task.sleep(for: .seconds(0.01)) + } + } + } + } +} diff --git a/Documentation/DemoApps/GRDBDemo/README.md b/Documentation/DemoApps/GRDBDemo/README.md new file mode 100644 index 000000000..5281e4866 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemo/README.md @@ -0,0 +1,46 @@ +GRDBDemo Application +==================== + + + +**GRDBDemo demonstrates how GRDB can fuel a SwiftUI application.** + +> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration. + +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 feed SwiftUI previews with a transient database. + +**Files of interest:** + +- [GRDBDemoApp.swift](GRDBDemo/GRDBDemoApp.swift) + + `GRDBDemoApp` feeds the SwiftUI app with a database, through the SwiftUI environment. + +- [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 [tested](GRDBDemoTests/AppDatabaseTests.swift). + +- [Persistence.swift](GRDBDemo/Database/Persistence.swift) + + This file instantiates various `AppDatabase` for the various projects needs: one database on disk for the application, and in-memory databases for SwiftUI previews. + +- [Player.swift](GRDBDemo/Database/Models/Player.swift) + + `Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). + +- [PlayerListModel.swift](GRDBDemo/Views/PlayerListModel.swift) + + `PlayerListModel` is an `@Observable` object that observes the database, displays always fresh values on screen, and performs actions. + + `PlayerListModel` is [tested](GRDBDemoTests/PlayerListModelTests.swift). + +- [PlayersNavigationView.swift](GRDBDemo/Views/PlayersNavigationView.swift) + + `PlayersNavigationView` is the main navigation view of the application. It instantiates a `PlayerListModel` from the `AppDatabase` stored in the SwiftUI environment. diff --git a/Documentation/DemoApps/GRDBDemo/Screenshot.png b/Documentation/DemoApps/GRDBDemo/Screenshot.png new file mode 100644 index 000000000..ded3f50ac Binary files /dev/null and b/Documentation/DemoApps/GRDBDemo/Screenshot.png differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Circular.imageset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Circular.imageset/Contents.json deleted file mode 100644 index 9be9adbf7..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Circular.imageset/Contents.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "images" : [ - { - "idiom" : "watch", - "screenWidth" : "{130,145}", - "scale" : "2x" - }, - { - "idiom" : "watch", - "screenWidth" : "{146,165}", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Contents.json deleted file mode 100644 index 2eca9a1f4..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Contents.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "assets" : [ - { - "idiom" : "watch", - "filename" : "Circular.imageset", - "role" : "circular" - }, - { - "idiom" : "watch", - "filename" : "Extra Large.imageset", - "role" : "extra-large" - }, - { - "idiom" : "watch", - "filename" : "Modular.imageset", - "role" : "modular" - }, - { - "idiom" : "watch", - "filename" : "Utilitarian.imageset", - "role" : "utilitarian" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Extra Large.imageset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Extra Large.imageset/Contents.json deleted file mode 100644 index 9be9adbf7..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Extra Large.imageset/Contents.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "images" : [ - { - "idiom" : "watch", - "screenWidth" : "{130,145}", - "scale" : "2x" - }, - { - "idiom" : "watch", - "screenWidth" : "{146,165}", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Modular.imageset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Modular.imageset/Contents.json deleted file mode 100644 index 9be9adbf7..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Modular.imageset/Contents.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "images" : [ - { - "idiom" : "watch", - "screenWidth" : "{130,145}", - "scale" : "2x" - }, - { - "idiom" : "watch", - "screenWidth" : "{146,165}", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Utilitarian.imageset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Utilitarian.imageset/Contents.json deleted file mode 100644 index 9be9adbf7..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Assets.xcassets/Complication.complicationset/Utilitarian.imageset/Contents.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "images" : [ - { - "idiom" : "watch", - "screenWidth" : "{130,145}", - "scale" : "2x" - }, - { - "idiom" : "watch", - "screenWidth" : "{146,165}", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/ExtensionDelegate.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/ExtensionDelegate.swift deleted file mode 100644 index 320f84a6b..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/ExtensionDelegate.swift +++ /dev/null @@ -1,48 +0,0 @@ -import WatchKit - -class ExtensionDelegate: NSObject, WKExtensionDelegate { - - func applicationDidFinishLaunching() { - // Perform any final initialization of your application. - } - - func applicationDidBecomeActive() { - // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - } - - func applicationWillResignActive() { - // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - // Use this method to pause ongoing tasks, disable timers, etc. - } - - func handle(_ backgroundTasks: Set) { - // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one. - for task in backgroundTasks { - // Use a switch statement to check the task type - switch task { - case let backgroundTask as WKApplicationRefreshBackgroundTask: - // Be sure to complete the background task once you’re done. - backgroundTask.setTaskCompletedWithSnapshot(false) - case let snapshotTask as WKSnapshotRefreshBackgroundTask: - // Snapshot tasks have a unique completion call, make sure to set your expiration date - snapshotTask.setTaskCompleted(restoredDefaultState: true, estimatedSnapshotExpiration: Date.distantFuture, userInfo: nil) - case let connectivityTask as WKWatchConnectivityRefreshBackgroundTask: - // Be sure to complete the connectivity task once you’re done. - connectivityTask.setTaskCompletedWithSnapshot(false) - case let urlSessionTask as WKURLSessionRefreshBackgroundTask: - // Be sure to complete the URL session task once you’re done. - urlSessionTask.setTaskCompletedWithSnapshot(false) - case let relevantShortcutTask as WKRelevantShortcutRefreshBackgroundTask: - // Be sure to complete the relevant-shortcut task once you're done. - relevantShortcutTask.setTaskCompletedWithSnapshot(false) - case let intentDidRunTask as WKIntentDidRunRefreshBackgroundTask: - // Be sure to complete the intent-did-run task once you're done. - intentDidRunTask.setTaskCompletedWithSnapshot(false) - default: - // make sure to complete unhandled task types - task.setTaskCompletedWithSnapshot(false) - } - } - } - -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Info.plist b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Info.plist deleted file mode 100644 index 0881b8b30..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/Info.plist +++ /dev/null @@ -1,36 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleDisplayName - GRDBDemoWatchOS Extension - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - XPC! - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - NSExtension - - NSExtensionAttributes - - WKAppBundleIdentifier - com.github.groue.GRDBDemoiOS2.watchkitapp - - NSExtensionPointIdentifier - com.apple.watchkit - - WKExtensionDelegateClassName - $(PRODUCT_MODULE_NAME).ExtensionDelegate - - diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/InterfaceController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/InterfaceController.swift deleted file mode 100644 index 71d59c794..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS Extension/InterfaceController.swift +++ /dev/null @@ -1,15 +0,0 @@ -import WatchKit -import Foundation -import GRDB - -class InterfaceController: WKInterfaceController { - - @IBOutlet var versionLabel: WKInterfaceLabel! - - override func awake(withContext context: Any?) { - super.awake(withContext: context) - - let sqliteVersion = String(cString: sqlite3_libversion(), encoding: .utf8) - versionLabel.setText(sqliteVersion) - } -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Assets.xcassets/AppIcon.appiconset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index dd221ba54..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "images" : [ - { - "size" : "24x24", - "idiom" : "watch", - "scale" : "2x", - "role" : "notificationCenter", - "subtype" : "38mm" - }, - { - "size" : "27.5x27.5", - "idiom" : "watch", - "scale" : "2x", - "role" : "notificationCenter", - "subtype" : "42mm" - }, - { - "size" : "29x29", - "idiom" : "watch", - "role" : "companionSettings", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "watch", - "role" : "companionSettings", - "scale" : "3x" - }, - { - "size" : "40x40", - "idiom" : "watch", - "scale" : "2x", - "role" : "appLauncher", - "subtype" : "38mm" - }, - { - "size" : "86x86", - "idiom" : "watch", - "scale" : "2x", - "role" : "quickLook", - "subtype" : "38mm" - }, - { - "size" : "98x98", - "idiom" : "watch", - "scale" : "2x", - "role" : "quickLook", - "subtype" : "42mm" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Base.lproj/Interface.storyboard b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Base.lproj/Interface.storyboard deleted file mode 100644 index 4988b4b68..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Base.lproj/Interface.storyboard +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Info.plist b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Info.plist deleted file mode 100644 index 0478fa15f..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoWatchOS/Info.plist +++ /dev/null @@ -1,33 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleDisplayName - GRDBDemoiOS - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - APPL - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - - WKCompanionAppBundleIdentifier - com.github.groue.GRDBDemoiOS2 - WKWatchKitApp - - - diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj deleted file mode 100644 index 4d38142d0..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ /dev/null @@ -1,908 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 54; - objects = { - -/* Begin PBXBuildFile section */ - 56185BBF25B8036100B9C30F /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BBE25B8036100B9C30F /* Persistence.swift */; }; - 56185BF325B80B8900B9C30F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */; }; - 56185C0725B80CEC00B9C30F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185C0625B80CEC00B9C30F /* PlayerTests.swift */; }; - 567940C528BA33D2004A0298 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; }; - 567940C628BA33D2004A0298 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; - 567940C728BA33DE004A0298 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; }; - 567940C828BA33DE004A0298 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D0A2355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; - 568E5FC31E926430002582E0 /* Interface.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC11E926430002582E0 /* Interface.storyboard */; }; - 568E5FC51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FC41E926430002582E0 /* Assets.xcassets */; }; - 568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; - 568E5FD11E926430002582E0 /* InterfaceController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD01E926430002582E0 /* InterfaceController.swift */; }; - 568E5FD31E926430002582E0 /* ExtensionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568E5FD21E926430002582E0 /* ExtensionDelegate.swift */; }; - 568E5FD51E926430002582E0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 568E5FD41E926430002582E0 /* Assets.xcassets */; }; - 568E5FD91E926430002582E0 /* GRDBDemoWatchOS.app in Embed Watch Content */ = {isa = PBXBuildFile; fileRef = 568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */; }; - 56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */; }; - 56B0360C1E8D9EBE003B6DA4 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */; }; - 56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */; }; - 56B036111E8D9EBE003B6DA4 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */; }; - 56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */; }; - 56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361A1E8D9F38003B6DA4 /* Player.swift */; }; - 56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */; }; - 56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */; }; - 56FE6F2624A90CE400711EDF /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FE6F2524A90CE400711EDF /* SceneDelegate.swift */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 56B036021E8D9EBE003B6DA4; - remoteInfo = GRDBDemoiOS; - }; - 5642252F29A2390800D714BF /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = DC3773F219C8CBB3004FCF85; - remoteInfo = GRDB; - }; - 5642253329A2391900D714BF /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 1; - remoteGlobalIDString = DC3773F219C8CBB3004FCF85; - remoteInfo = GRDB; - }; - 56606D092355931F00185962 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = DC3773F319C8CBB3004FCF85; - remoteInfo = GRDBOSX; - }; - 56606D0B2355931F00185962 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - proxyType = 2; - remoteGlobalIDString = 56E5D7F91B4D422D00430942; - remoteInfo = GRDBOSXTests; - }; - 568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 568E5FCA1E926430002582E0; - remoteInfo = "GRDBDemoWatchOS Extension"; - }; - 568E5FD71E926430002582E0 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 568E5FBE1E926430002582E0; - remoteInfo = GRDBDemoWatchOS; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 568E5FDD1E926430002582E0 /* Embed Foundation Extensions */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 13; - files = ( - 568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed Foundation Extensions */, - ); - name = "Embed Foundation Extensions"; - runOnlyForDeploymentPostprocessing = 0; - }; - 568E5FE11E926430002582E0 /* Embed Watch Content */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = "$(CONTENTS_FOLDER_PATH)/Watch"; - dstSubfolderSpec = 16; - files = ( - 568E5FD91E926430002582E0 /* GRDBDemoWatchOS.app in Embed Watch Content */, - ); - name = "Embed Watch Content"; - runOnlyForDeploymentPostprocessing = 0; - }; - 568E5FE81E926547002582E0 /* Embed Frameworks */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - 567940C828BA33DE004A0298 /* GRDB.framework in Embed Frameworks */, - ); - name = "Embed Frameworks"; - runOnlyForDeploymentPostprocessing = 0; - }; - 56B036621E8D9FB1003B6DA4 /* Embed Frameworks */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - 567940C628BA33D2004A0298 /* GRDB.framework in Embed Frameworks */, - ); - name = "Embed Frameworks"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 56185BBE25B8036100B9C30F /* Persistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = ""; }; - 56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBDemoiOSTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = ""; }; - 56185BF425B80B8900B9C30F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 56185C0625B80CEC00B9C30F /* PlayerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = ""; }; - 568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoWatchOS.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 568E5FC21E926430002582E0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Interface.storyboard; sourceTree = ""; }; - 568E5FC41E926430002582E0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 568E5FC61E926430002582E0 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "GRDBDemoWatchOS Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; }; - 568E5FD01E926430002582E0 /* InterfaceController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InterfaceController.swift; sourceTree = ""; }; - 568E5FD21E926430002582E0 /* ExtensionDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExtensionDelegate.swift; sourceTree = ""; }; - 568E5FD41E926430002582E0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 568E5FD61E926430002582E0 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 56B036031E8D9EBE003B6DA4 /* GRDBDemoiOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoiOS.app; sourceTree = BUILT_PRODUCTS_DIR; }; - 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 56B0360B1E8D9EBE003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; - 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; - 56B036101E8D9EBE003B6DA4 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; - 56B036121E8D9EBE003B6DA4 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabase.swift; sourceTree = ""; }; - 56B0361A1E8D9F38003B6DA4 /* Player.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = ""; }; - 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerEditionViewController.swift; sourceTree = ""; }; - 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerListViewController.swift; sourceTree = ""; }; - 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = ../../../GRDB.xcodeproj; sourceTree = ""; }; - 56FE6F2524A90CE400711EDF /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 56185BED25B80B8900B9C30F /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 568E5FC81E926430002582E0 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 567940C728BA33DE004A0298 /* GRDB.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 56B036001E8D9EBE003B6DA4 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 567940C528BA33D2004A0298 /* GRDB.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 56185BF125B80B8900B9C30F /* GRDBDemoiOSTests */ = { - isa = PBXGroup; - children = ( - 56185BF425B80B8900B9C30F /* Info.plist */, - 56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */, - 56185C0625B80CEC00B9C30F /* PlayerTests.swift */, - ); - path = GRDBDemoiOSTests; - sourceTree = ""; - }; - 56606CFD2355931F00185962 /* Products */ = { - isa = PBXGroup; - children = ( - 56606D0A2355931F00185962 /* GRDB.framework */, - 56606D0C2355931F00185962 /* GRDBTests.xctest */, - ); - name = Products; - sourceTree = ""; - }; - 56606D1F2355938A00185962 /* Frameworks */ = { - isa = PBXGroup; - children = ( - ); - name = Frameworks; - sourceTree = ""; - }; - 568E5FC01E926430002582E0 /* GRDBDemoWatchOS */ = { - isa = PBXGroup; - children = ( - 568E5FC11E926430002582E0 /* Interface.storyboard */, - 568E5FC41E926430002582E0 /* Assets.xcassets */, - 568E5FC61E926430002582E0 /* Info.plist */, - ); - path = GRDBDemoWatchOS; - sourceTree = ""; - }; - 568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */ = { - isa = PBXGroup; - children = ( - 568E5FD01E926430002582E0 /* InterfaceController.swift */, - 568E5FD21E926430002582E0 /* ExtensionDelegate.swift */, - 568E5FD41E926430002582E0 /* Assets.xcassets */, - 568E5FD61E926430002582E0 /* Info.plist */, - ); - path = "GRDBDemoWatchOS Extension"; - sourceTree = ""; - }; - 56B035FA1E8D9EBE003B6DA4 = { - isa = PBXGroup; - children = ( - 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */, - 56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */, - 568E5FC01E926430002582E0 /* GRDBDemoWatchOS */, - 568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */, - 56185BF125B80B8900B9C30F /* GRDBDemoiOSTests */, - 56B036041E8D9EBE003B6DA4 /* Products */, - 56606D1F2355938A00185962 /* Frameworks */, - ); - sourceTree = ""; - }; - 56B036041E8D9EBE003B6DA4 /* Products */ = { - isa = PBXGroup; - children = ( - 56B036031E8D9EBE003B6DA4 /* GRDBDemoiOS.app */, - 568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */, - 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */, - 56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */, - ); - name = Products; - sourceTree = ""; - }; - 56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */ = { - isa = PBXGroup; - children = ( - 56B036121E8D9EBE003B6DA4 /* Info.plist */, - 56B036191E8D9F38003B6DA4 /* AppDatabase.swift */, - 56B036061E8D9EBE003B6DA4 /* AppDelegate.swift */, - 56185BBE25B8036100B9C30F /* Persistence.swift */, - 56B0361A1E8D9F38003B6DA4 /* Player.swift */, - 56FE6F2524A90CE400711EDF /* SceneDelegate.swift */, - 56FE6F4E24A9112900711EDF /* Resources */, - 56FE6F4F24A9114200711EDF /* ViewControllers */, - ); - path = GRDBDemoiOS; - sourceTree = ""; - }; - 56FE6F4E24A9112900711EDF /* Resources */ = { - isa = PBXGroup; - children = ( - 56B0360D1E8D9EBE003B6DA4 /* Assets.xcassets */, - 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */, - 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */, - ); - path = Resources; - sourceTree = ""; - }; - 56FE6F4F24A9114200711EDF /* ViewControllers */ = { - isa = PBXGroup; - children = ( - 56B0361F1E8D9F4C003B6DA4 /* PlayerEditionViewController.swift */, - 56B036201E8D9F4C003B6DA4 /* PlayerListViewController.swift */, - ); - path = ViewControllers; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 56185BEF25B80B8900B9C30F /* GRDBDemoiOSTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 56185BFF25B80B8900B9C30F /* Build configuration list for PBXNativeTarget "GRDBDemoiOSTests" */; - buildPhases = ( - 56185BEC25B80B8900B9C30F /* Sources */, - 56185BED25B80B8900B9C30F /* Frameworks */, - 56185BEE25B80B8900B9C30F /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 56185BF625B80B8900B9C30F /* PBXTargetDependency */, - ); - name = GRDBDemoiOSTests; - productName = GRDBDemoiOSTests; - productReference = 56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; - 568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */ = { - isa = PBXNativeTarget; - buildConfigurationList = 568E5FDE1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS" */; - buildPhases = ( - 568E5FBD1E926430002582E0 /* Resources */, - 568E5FDD1E926430002582E0 /* Embed Foundation Extensions */, - ); - buildRules = ( - ); - dependencies = ( - 568E5FCE1E926430002582E0 /* PBXTargetDependency */, - ); - name = GRDBDemoWatchOS; - productName = GRDBDemoWatchOS; - productReference = 568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */; - productType = "com.apple.product-type.application.watchapp2"; - }; - 568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */ = { - isa = PBXNativeTarget; - buildConfigurationList = 568E5FDA1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS Extension" */; - buildPhases = ( - 568E5FC71E926430002582E0 /* Sources */, - 568E5FC81E926430002582E0 /* Frameworks */, - 568E5FC91E926430002582E0 /* Resources */, - 568E5FE81E926547002582E0 /* Embed Frameworks */, - ); - buildRules = ( - ); - dependencies = ( - 5642253429A2391900D714BF /* PBXTargetDependency */, - ); - name = "GRDBDemoWatchOS Extension"; - productName = "GRDBDemoWatchOS Extension"; - productReference = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; - productType = "com.apple.product-type.watchkit2-extension"; - }; - 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */ = { - isa = PBXNativeTarget; - buildConfigurationList = 56B036151E8D9EBE003B6DA4 /* Build configuration list for PBXNativeTarget "GRDBDemoiOS" */; - buildPhases = ( - 56B035FF1E8D9EBE003B6DA4 /* Sources */, - 56B036001E8D9EBE003B6DA4 /* Frameworks */, - 56B036011E8D9EBE003B6DA4 /* Resources */, - 56B036621E8D9FB1003B6DA4 /* Embed Frameworks */, - 568E5FE11E926430002582E0 /* Embed Watch Content */, - ); - buildRules = ( - ); - dependencies = ( - 5642253029A2390800D714BF /* PBXTargetDependency */, - 568E5FD81E926430002582E0 /* PBXTargetDependency */, - ); - name = GRDBDemoiOS; - productName = GRDBDemoiOS; - productReference = 56B036031E8D9EBE003B6DA4 /* GRDBDemoiOS.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 56B035FB1E8D9EBE003B6DA4 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 1230; - LastUpgradeCheck = 1400; - ORGANIZATIONNAME = "Gwendal Roué"; - TargetAttributes = { - 56185BEF25B80B8900B9C30F = { - CreatedOnToolsVersion = 12.3; - DevelopmentTeam = AMD8W895CT; - ProvisioningStyle = Automatic; - TestTargetID = 56B036021E8D9EBE003B6DA4; - }; - 568E5FBE1E926430002582E0 = { - CreatedOnToolsVersion = 8.3; - DevelopmentTeam = AMD8W895CT; - ProvisioningStyle = Automatic; - }; - 568E5FCA1E926430002582E0 = { - CreatedOnToolsVersion = 8.3; - DevelopmentTeam = AMD8W895CT; - LastSwiftMigration = 1020; - ProvisioningStyle = Automatic; - }; - 56B036021E8D9EBE003B6DA4 = { - CreatedOnToolsVersion = 8.3; - DevelopmentTeam = AMD8W895CT; - LastSwiftMigration = 1020; - ProvisioningStyle = Automatic; - }; - }; - }; - buildConfigurationList = 56B035FE1E8D9EBE003B6DA4 /* Build configuration list for PBXProject "GRDBDemoiOS" */; - compatibilityVersion = "Xcode 12.0"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 56B035FA1E8D9EBE003B6DA4; - productRefGroup = 56B036041E8D9EBE003B6DA4 /* Products */; - projectDirPath = ""; - projectReferences = ( - { - ProductGroup = 56606CFD2355931F00185962 /* Products */; - ProjectRef = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; - }, - ); - projectRoot = ""; - targets = ( - 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */, - 568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */, - 568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */, - 56185BEF25B80B8900B9C30F /* GRDBDemoiOSTests */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXReferenceProxy section */ - 56606D0A2355931F00185962 /* GRDB.framework */ = { - isa = PBXReferenceProxy; - fileType = wrapper.framework; - path = GRDB.framework; - remoteRef = 56606D092355931F00185962 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; - 56606D0C2355931F00185962 /* GRDBTests.xctest */ = { - isa = PBXReferenceProxy; - fileType = wrapper.cfbundle; - path = GRDBTests.xctest; - remoteRef = 56606D0B2355931F00185962 /* PBXContainerItemProxy */; - sourceTree = BUILT_PRODUCTS_DIR; - }; -/* End PBXReferenceProxy section */ - -/* Begin PBXResourcesBuildPhase section */ - 56185BEE25B80B8900B9C30F /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 568E5FBD1E926430002582E0 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 568E5FC51E926430002582E0 /* Assets.xcassets in Resources */, - 568E5FC31E926430002582E0 /* Interface.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 568E5FC91E926430002582E0 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 568E5FD51E926430002582E0 /* Assets.xcassets in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 56B036011E8D9EBE003B6DA4 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 56B036111E8D9EBE003B6DA4 /* LaunchScreen.storyboard in Resources */, - 56B0360E1E8D9EBE003B6DA4 /* Assets.xcassets in Resources */, - 56B0360C1E8D9EBE003B6DA4 /* Main.storyboard in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 56185BEC25B80B8900B9C30F /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 56185C0725B80CEC00B9C30F /* PlayerTests.swift in Sources */, - 56185BF325B80B8900B9C30F /* AppDatabaseTests.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 568E5FC71E926430002582E0 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 568E5FD31E926430002582E0 /* ExtensionDelegate.swift in Sources */, - 568E5FD11E926430002582E0 /* InterfaceController.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 56B035FF1E8D9EBE003B6DA4 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 56FE6F2624A90CE400711EDF /* SceneDelegate.swift in Sources */, - 56B0361C1E8D9F38003B6DA4 /* Player.swift in Sources */, - 56B0361B1E8D9F38003B6DA4 /* AppDatabase.swift in Sources */, - 56185BBF25B8036100B9C30F /* Persistence.swift in Sources */, - 56B036071E8D9EBE003B6DA4 /* AppDelegate.swift in Sources */, - 56B036241E8D9F4C003B6DA4 /* PlayerListViewController.swift in Sources */, - 56B036231E8D9F4C003B6DA4 /* PlayerEditionViewController.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 56185BF625B80B8900B9C30F /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */; - targetProxy = 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */; - }; - 5642253029A2390800D714BF /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = GRDB; - targetProxy = 5642252F29A2390800D714BF /* PBXContainerItemProxy */; - }; - 5642253429A2391900D714BF /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = GRDB; - targetProxy = 5642253329A2391900D714BF /* PBXContainerItemProxy */; - }; - 568E5FCE1E926430002582E0 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */; - targetProxy = 568E5FCD1E926430002582E0 /* PBXContainerItemProxy */; - }; - 568E5FD81E926430002582E0 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */; - targetProxy = 568E5FD71E926430002582E0 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin PBXVariantGroup section */ - 568E5FC11E926430002582E0 /* Interface.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 568E5FC21E926430002582E0 /* Base */, - ); - name = Interface.storyboard; - sourceTree = ""; - }; - 56B0360A1E8D9EBE003B6DA4 /* Main.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 56B0360B1E8D9EBE003B6DA4 /* Base */, - ); - name = Main.storyboard; - sourceTree = ""; - }; - 56B0360F1E8D9EBE003B6DA4 /* LaunchScreen.storyboard */ = { - isa = PBXVariantGroup; - children = ( - 56B036101E8D9EBE003B6DA4 /* Base */, - ); - name = LaunchScreen.storyboard; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 56185BF725B80B8900B9C30F /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = AMD8W895CT; - GCC_C_LANGUAGE_STANDARD = gnu11; - INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOSTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemoiOS.app/GRDBDemoiOS"; - }; - name = Debug; - }; - 56185BF825B80B8900B9C30F /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CODE_SIGN_STYLE = Automatic; - DEVELOPMENT_TEAM = AMD8W895CT; - GCC_C_LANGUAGE_STANDARD = gnu11; - INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@loader_path/Frameworks", - ); - MTL_FAST_MATH = YES; - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOSTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TARGETED_DEVICE_FAMILY = "1,2"; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemoiOS.app/GRDBDemoiOS"; - }; - name = Release; - }; - 568E5FDB1E926430002582E0 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_COMPLICATION_NAME = Complication; - CLANG_ENABLE_OBJC_WEAK = YES; - DEVELOPMENT_TEAM = AMD8W895CT; - INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@executable_path/../../Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension; - PRODUCT_NAME = "${TARGET_NAME}"; - SDKROOT = watchos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = 4; - }; - name = Debug; - }; - 568E5FDC1E926430002582E0 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ASSETCATALOG_COMPILER_COMPLICATION_NAME = Complication; - CLANG_ENABLE_OBJC_WEAK = YES; - DEVELOPMENT_TEAM = AMD8W895CT; - INFOPLIST_FILE = "GRDBDemoWatchOS Extension/Info.plist"; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - "@executable_path/../../Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp.watchkitextension; - PRODUCT_NAME = "${TARGET_NAME}"; - SDKROOT = watchos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = 4; - }; - name = Release; - }; - 568E5FDF1E926430002582E0 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_OBJC_WEAK = YES; - DEVELOPMENT_TEAM = AMD8W895CT; - IBSC_MODULE = GRDBDemoWatchOS_Extension; - INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist; - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp; - PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = watchos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = 4; - }; - name = Debug; - }; - 568E5FE01E926430002582E0 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_OBJC_WEAK = YES; - DEVELOPMENT_TEAM = AMD8W895CT; - IBSC_MODULE = GRDBDemoWatchOS_Extension; - INFOPLIST_FILE = GRDBDemoWatchOS/Info.plist; - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2.watchkitapp; - PRODUCT_NAME = "$(TARGET_NAME)"; - SDKROOT = watchos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = 4; - }; - name = Release; - }; - 56B036131E8D9EBE003B6DA4 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 15.0; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = iphoneos; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - WATCHOS_DEPLOYMENT_TARGET = 8.0; - }; - name = Debug; - }; - 56B036141E8D9EBE003B6DA4 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 15.0; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - SWIFT_VERSION = 5.0; - VALIDATE_PRODUCT = YES; - WATCHOS_DEPLOYMENT_TARGET = 8.0; - }; - name = Release; - }; - 56B036161E8D9EBE003B6DA4 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_OBJC_WEAK = YES; - DEVELOPMENT_TEAM = AMD8W895CT; - INFOPLIST_FILE = GRDBDemoiOS/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Debug; - }; - 56B036171E8D9EBE003B6DA4 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_OBJC_WEAK = YES; - DEVELOPMENT_TEAM = AMD8W895CT; - INFOPLIST_FILE = GRDBDemoiOS/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/Frameworks", - ); - PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOS2; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 56185BFF25B80B8900B9C30F /* Build configuration list for PBXNativeTarget "GRDBDemoiOSTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 56185BF725B80B8900B9C30F /* Debug */, - 56185BF825B80B8900B9C30F /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 568E5FDA1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS Extension" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 568E5FDB1E926430002582E0 /* Debug */, - 568E5FDC1E926430002582E0 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 568E5FDE1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 568E5FDF1E926430002582E0 /* Debug */, - 568E5FE01E926430002582E0 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 56B035FE1E8D9EBE003B6DA4 /* Build configuration list for PBXProject "GRDBDemoiOS" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 56B036131E8D9EBE003B6DA4 /* Debug */, - 56B036141E8D9EBE003B6DA4 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 56B036151E8D9EBE003B6DA4 /* Build configuration list for PBXNativeTarget "GRDBDemoiOS" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 56B036161E8D9EBE003B6DA4 /* Debug */, - 56B036171E8D9EBE003B6DA4 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 56B035FB1E8D9EBE003B6DA4 /* Project object */; -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme deleted file mode 100644 index bd03393c0..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme +++ /dev/null @@ -1,116 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift deleted file mode 100644 index 07edceeed..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDelegate.swift +++ /dev/null @@ -1,22 +0,0 @@ -import UIKit - -@UIApplicationMain -class AppDelegate: UIResponder, UIApplicationDelegate { - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { - return true - } - - // MARK: UISceneSession Lifecycle - - func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { - // Called when a new scene session is being created. - // Use this method to select a configuration to create the new scene with. - return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) - } - - func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { - // Called when the user discards a scene session. - // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. - // Use this method to release any resources that were specific to the discarded scenes, as they will not return. - } -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Info.plist b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Info.plist deleted file mode 100644 index b5f9c0796..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Info.plist +++ /dev/null @@ -1,62 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - LSRequiresIPhoneOS - - UIApplicationSceneManifest - - UIApplicationSupportsMultipleScenes - - UISceneConfigurations - - UIWindowSceneSessionRoleApplication - - - UISceneConfigurationName - Default Configuration - UISceneDelegateClassName - $(PRODUCT_MODULE_NAME).SceneDelegate - UISceneStoryboardFile - Main - - - - - UILaunchStoryboardName - LaunchScreen - UIMainStoryboardFile - Main - UIRequiredDeviceCapabilities - - armv7 - - UISupportedInterfaceOrientations - - UIInterfaceOrientationPortrait - - UISupportedInterfaceOrientations~ipad - - UIInterfaceOrientationPortrait - UIInterfaceOrientationPortraitUpsideDown - UIInterfaceOrientationLandscapeLeft - UIInterfaceOrientationLandscapeRight - - - diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift deleted file mode 100644 index 82204b62c..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift +++ /dev/null @@ -1,104 +0,0 @@ -import GRDB - -/// The Player struct. -/// -/// Identifiable conformance supports type-safe GRDB primary key methods. -/// Hashable conformance supports table view updates -struct Player: Identifiable, Hashable { - /// The player id. - /// - /// Int64 is the recommended type for auto-incremented database ids. - /// Use nil for players that are not inserted yet in the database. - var id: Int64? - var name: String - var score: Int -} - -extension Player { - private static let names = [ - "Arthur", "Anita", "Barbara", "Bernard", "Craig", "Chiara", "David", - "Dean", "Éric", "Elena", "Fatima", "Frederik", "Gilbert", "Georgette", - "Henriette", "Hassan", "Ignacio", "Irene", "Julie", "Jack", "Karl", - "Kristel", "Louis", "Liz", "Masashi", "Mary", "Noam", "Nicole", - "Ophelie", "Oleg", "Pascal", "Patricia", "Quentin", "Quinn", "Raoul", - "Rachel", "Stephan", "Susie", "Tristan", "Tatiana", "Ursule", "Urbain", - "Victor", "Violette", "Wilfried", "Wilhelmina", "Yvon", "Yann", - "Zazie", "Zoé"] - - /// Creates a new player with empty name and zero score - static func new() -> Player { - Player(id: nil, name: "", score: 0) - } - - /// Creates a new player with random name and random score - static func makeRandom() -> Player { - Player(id: nil, name: randomName(), score: randomScore()) - } - - /// Returns a random name - static func randomName() -> String { - names.randomElement()! - } - - /// Returns a random score - static func randomScore() -> Int { - 10 * Int.random(in: 0...100) - } -} - -// MARK: - Persistence - -/// Make Player a Codable Record. -/// -/// See -extension Player: Codable, FetchableRecord, MutablePersistableRecord { - // Define database columns from CodingKeys - fileprivate enum Columns { - static let name = Column(CodingKeys.name) - static let score = Column(CodingKeys.score) - } - - /// Updates a player id after it has been inserted in the database. - mutating func didInsert(_ inserted: InsertionSuccess) { - id = inserted.rowID - } -} - -// MARK: - Player Database Requests - -/// Define some player requests used by the application. -/// -/// See -extension DerivableRequest { - /// A request of players ordered by name. - /// - /// For example: - /// - /// let players: [Player] = try dbWriter.read { db in - /// try Player.all().orderedByName().fetchAll(db) - /// } - func orderedByName() -> Self { - // Sort by name in a localized case insensitive fashion - // See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison - order(Player.Columns.name.collating(.localizedCaseInsensitiveCompare)) - } - - /// A request of players ordered by score. - /// - /// For example: - /// - /// let players: [Player] = try dbWriter.read { db in - /// try Player.all().orderedByScore().fetchAll(db) - /// } - /// let bestPlayer: Player? = try dbWriter.read { db in - /// try Player.all().orderedByScore().fetchOne(db) - /// } - func orderedByScore() -> Self { - // Sort by descending score, and then by name, in a - // localized case insensitive fashion - // See https://github.com/groue/GRDB.swift/blob/master/README.md#string-comparison - order( - Player.Columns.score.desc, - Player.Columns.name.collating(.localizedCaseInsensitiveCompare)) - } -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index 29d91251d..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,116 +0,0 @@ -{ - "images" : [ - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "icon_20pt@2x.png", - "scale" : "2x" - }, - { - "size" : "20x20", - "idiom" : "iphone", - "filename" : "icon_20pt@3x.png", - "scale" : "3x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "icon_29pt@2x.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "iphone", - "filename" : "icon_29pt@3x.png", - "scale" : "3x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "icon_40pt@2x.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "iphone", - "filename" : "icon_40pt@3x.png", - "scale" : "3x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "icon_60pt@2x.png", - "scale" : "2x" - }, - { - "size" : "60x60", - "idiom" : "iphone", - "filename" : "icon_60pt@3x.png", - "scale" : "3x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "icon_20pt.png", - "scale" : "1x" - }, - { - "size" : "20x20", - "idiom" : "ipad", - "filename" : "icon_20pt@2x-1.png", - "scale" : "2x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "icon_29pt.png", - "scale" : "1x" - }, - { - "size" : "29x29", - "idiom" : "ipad", - "filename" : "icon_29pt@2x-1.png", - "scale" : "2x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "icon_40pt.png", - "scale" : "1x" - }, - { - "size" : "40x40", - "idiom" : "ipad", - "filename" : "icon_40pt@2x-1.png", - "scale" : "2x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "icon_76pt.png", - "scale" : "1x" - }, - { - "size" : "76x76", - "idiom" : "ipad", - "filename" : "icon_76pt@2x.png", - "scale" : "2x" - }, - { - "size" : "83.5x83.5", - "idiom" : "ipad", - "filename" : "icon_83.5@2x.png", - "scale" : "2x" - }, - { - "size" : "1024x1024", - "idiom" : "ios-marketing", - "filename" : "Icon.png", - "scale" : "1x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} \ No newline at end of file diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/Icon.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/Icon.png deleted file mode 100644 index 66b1931a1..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/Icon.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt.png deleted file mode 100644 index 90648b3f4..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x-1.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x-1.png deleted file mode 100644 index a077a6f49..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x-1.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x.png deleted file mode 100644 index a077a6f49..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@3x.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@3x.png deleted file mode 100644 index 600bdbd9c..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_20pt@3x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt.png deleted file mode 100644 index 8e04af0dd..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x-1.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x-1.png deleted file mode 100644 index 686e8d99e..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x-1.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x.png deleted file mode 100644 index 686e8d99e..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@3x.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@3x.png deleted file mode 100644 index 1d013c3d3..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_29pt@3x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt.png deleted file mode 100644 index a077a6f49..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x-1.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x-1.png deleted file mode 100644 index da66b9ba8..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x-1.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x.png deleted file mode 100644 index da66b9ba8..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@3x.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@3x.png deleted file mode 100644 index 59346ef4b..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_40pt@3x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@2x.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@2x.png deleted file mode 100644 index 59346ef4b..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@3x.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@3x.png deleted file mode 100644 index d4640afc9..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_60pt@3x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt.png deleted file mode 100644 index e3a04522b..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt@2x.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt@2x.png deleted file mode 100644 index 593ebd783..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_76pt@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_83.5@2x.png b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_83.5@2x.png deleted file mode 100644 index ca02cd03b..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/AppIcon.appiconset/icon_83.5@2x.png and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/LaunchIcon.imageset/LaunchIcon.pdf b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/LaunchIcon.imageset/LaunchIcon.pdf deleted file mode 100644 index 266089149..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/LaunchIcon.imageset/LaunchIcon.pdf and /dev/null differ diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Base.lproj/LaunchScreen.storyboard b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Base.lproj/LaunchScreen.storyboard deleted file mode 100644 index 307d45b11..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Base.lproj/LaunchScreen.storyboard +++ /dev/null @@ -1,38 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Base.lproj/Main.storyboard b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Base.lproj/Main.storyboard deleted file mode 100644 index 0f36128da..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Base.lproj/Main.storyboard +++ /dev/null @@ -1,213 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SceneDelegate.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SceneDelegate.swift deleted file mode 100644 index b484ed11d..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/SceneDelegate.swift +++ /dev/null @@ -1,40 +0,0 @@ -import UIKit - -class SceneDelegate: UIResponder, UIWindowSceneDelegate { - var window: UIWindow? - - func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { - // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. - // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. - // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). - guard let _ = (scene as? UIWindowScene) else { return } - } - - func sceneDidDisconnect(_ scene: UIScene) { - // Called as the scene is being released by the system. - // This occurs shortly after the scene enters the background, or when its session is discarded. - // Release any resources associated with this scene that can be re-created the next time the scene connects. - // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). - } - - func sceneDidBecomeActive(_ scene: UIScene) { - // Called when the scene has moved from an inactive state to an active state. - // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. - } - - func sceneWillResignActive(_ scene: UIScene) { - // Called when the scene will move from an active state to an inactive state. - // This may occur due to temporary interruptions (ex. an incoming phone call). - } - - func sceneWillEnterForeground(_ scene: UIScene) { - // Called as the scene transitions from the background to the foreground. - // Use this method to undo the changes made on entering the background. - } - - func sceneDidEnterBackground(_ scene: UIScene) { - // Called as the scene transitions from the foreground to the background. - // Use this method to save data, release shared resources, and store enough scene-specific state information - // to restore the scene back to its current state. - } -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift deleted file mode 100644 index e9988462a..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift +++ /dev/null @@ -1,128 +0,0 @@ -import UIKit - -class PlayerEditionViewController: UITableViewController { - enum Mode { - /// Edition ends with the "Commit" unwind segue. - case creation - - /// Edition ends when user hits the back button. - case edition - } - - /// The edited player - private(set) var player: Player - - /// The presentation mode - let mode: Mode - - @IBOutlet private weak var cancelButtonItem: UIBarButtonItem! - @IBOutlet private weak var saveButtonItem: UIBarButtonItem! - @IBOutlet private weak var nameCell: UITableViewCell! - @IBOutlet private weak var nameTextField: UITextField! - @IBOutlet private weak var scoreCell: UITableViewCell! - @IBOutlet private weak var scoreTextField: UITextField! - - init?(_ coder: NSCoder, mode: Mode, player: Player) { - self.mode = mode - self.player = player - super.init(coder: coder) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - override func viewDidLoad() { - super.viewDidLoad() - configureNavigationItem() - configureForm() - } -} - -// MARK: - Navigation - -extension PlayerEditionViewController { - override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { - // Force keyboard to dismiss early - view.endEditing(true) - return true - } - - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - if segue.identifier == "Commit" { - saveChanges() - } - } - - override func willMove(toParent parent: UIViewController?) { - super.willMove(toParent: parent) - - if mode == .edition, parent == nil { - // Self is popping from its navigation controller - saveChanges() - } - } - - private func configureNavigationItem() { - switch mode { - case .creation: - navigationItem.title = "New Player" - navigationItem.leftBarButtonItem = cancelButtonItem - navigationItem.rightBarButtonItem = saveButtonItem - case .edition: - navigationItem.title = player.name - navigationItem.leftBarButtonItem = nil - navigationItem.rightBarButtonItem = nil - } - } -} - -// MARK: - Form - -extension PlayerEditionViewController: UITextFieldDelegate { - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - nameTextField.becomeFirstResponder() - } - - override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { - tableView.deselectRow(at: indexPath, animated: false) - let cell = tableView.cellForRow(at: indexPath) - if cell === nameCell { - nameTextField.becomeFirstResponder() - } else if cell === scoreCell { - scoreTextField.becomeFirstResponder() - } - } - - func textFieldShouldReturn(_ textField: UITextField) -> Bool { - if textField == nameTextField { - scoreTextField.becomeFirstResponder() - } - return false - } - - @IBAction func textFieldDidChange(_ textField: UITextField) { - // User has edited the player: prevent interactive dismissal - isModalInPresentation = true - } - - private func configureForm() { - nameTextField.text = player.name - - if player.score == 0 && player.id == nil { - scoreTextField.text = "" - } else { - scoreTextField.text = "\(player.score)" - } - } - - private func saveChanges() { - var player = self.player - player.name = nameTextField.text ?? "" - player.score = scoreTextField.text.flatMap { Int($0) } ?? 0 - try! AppDatabase.shared.savePlayer(&player) - self.player = player - } -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift deleted file mode 100644 index 0ef0c52d4..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/ViewControllers/PlayerListViewController.swift +++ /dev/null @@ -1,194 +0,0 @@ -import UIKit -import GRDB - -/// PlayerListViewController displays the list of players. -class PlayerListViewController: UITableViewController { - private enum PlayerOrdering { - case byName - case byScore - } - - @IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem! - private var dataSource: PlayerDataSource! - private var playersCancellable: DatabaseCancellable? - private var playerOrdering: PlayerOrdering = .byScore { - didSet { - configureOrderingBarButtonItem() - observePlayers() - } - } - - override func viewDidLoad() { - super.viewDidLoad() - configureToolbar() - configureNavigationItem() - configureDataSource() - observePlayers() - } - - override func viewWillAppear(_ animated: Bool) { - super.viewWillAppear(animated) - navigationController?.isToolbarHidden = false - } - - private func configureToolbar() { - toolbarItems = [ - UIBarButtonItem(systemItem: .trash, primaryAction: UIAction { [unowned self] _ in - setEditing(false, animated: true) - try! AppDatabase.shared.deleteAllPlayers() - }), - UIBarButtonItem(systemItem: .flexibleSpace), - UIBarButtonItem(systemItem: .refresh, primaryAction: UIAction { [unowned self] _ in - setEditing(false, animated: true) - try! AppDatabase.shared.refreshPlayers() - }), - UIBarButtonItem(systemItem: .flexibleSpace), - UIBarButtonItem(image: UIImage(systemName: "tornado"), primaryAction: UIAction { [unowned self] _ in - setEditing(false, animated: true) - for _ in 0..<50 { - DispatchQueue.global().async { - try! AppDatabase.shared.refreshPlayers() - } - } - }), - ] - } - - private func configureNavigationItem() { - navigationItem.backBarButtonItem = UIBarButtonItem(title: "Players") - navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem] - configureOrderingBarButtonItem() - } - - private func configureOrderingBarButtonItem() { - switch playerOrdering { - case .byScore: - navigationItem.rightBarButtonItem = UIBarButtonItem( - title: "Score ▼", - primaryAction: UIAction { [unowned self] _ in - setEditing(false, animated: true) - playerOrdering = .byName - }) - case .byName: - navigationItem.rightBarButtonItem = UIBarButtonItem( - title: "Name ▲", - primaryAction: UIAction { [unowned self] _ in - setEditing(false, animated: true) - playerOrdering = .byScore - }) - } - } - - private func configureDataSource() { - dataSource = PlayerDataSource(tableView: tableView) { (tableView, indexPath, player) in - let cell = tableView.dequeueReusableCell(withIdentifier: "Player", for: indexPath) - if player.name.isEmpty { - cell.textLabel?.text = "(anonymous)" - } else { - cell.textLabel?.text = player.name - } - cell.detailTextLabel?.text = abs(player.score) > 1 ? "\(player.score) points" : "0 point" - return cell - } - dataSource.defaultRowAnimation = .fade - tableView.dataSource = dataSource - } - - private func configureTitle(from players: [Player]) { - switch players.count { - case 0: - navigationItem.title = "No Player" - case 1: - navigationItem.title = "1 Player" - case let count: - navigationItem.title = "\(count) Players" - } - } - - private func configureDataSource(from players: [Player]) { - var snapshot = NSDiffableDataSourceSnapshot() - snapshot.appendSections([0]) - snapshot.appendItems(players, toSection: 0) - - // Remember selection - let selectedPlayerId = tableView.indexPathForSelectedRow.flatMap { - dataSource.itemIdentifier(for: $0)?.id - } - - // Avoid a UIKit warning; don't animate when popping from edition - let animated = view.window != nil - - dataSource.apply(snapshot, animatingDifferences: animated, completion: { - // Restore selection - if let index = players.firstIndex(where: { $0.id == selectedPlayerId }) { - self.tableView.selectRow(at: IndexPath(row: index, section: 0), animated: false, scrollPosition: .none) - } - }) - } - - private func observePlayers() { - let request: QueryInterfaceRequest - switch playerOrdering { - case .byName: - request = Player.all().orderedByName() - case .byScore: - request = Player.all().orderedByScore() - } - - playersCancellable = ValueObservation - .tracking(request.fetchAll(_:)) - .start( - in: AppDatabase.shared.reader, - // Immediate scheduling feeds the data source right on subscription, - // and avoids an undesired animation when the application starts. - scheduling: .immediate, - onError: { error in fatalError("Unexpected error: \(error)") }, - onChange: { [weak self] players in - guard let self else { return } - self.configureTitle(from: players) - self.configureDataSource(from: players) - }) - } -} - - -// MARK: - Navigation - -extension PlayerListViewController { - @IBSegueAction func makePlayerEditionViewController(_ coder: NSCoder) -> PlayerEditionViewController? { - guard let indexPath = tableView.indexPathForSelectedRow, - let player = dataSource.itemIdentifier(for: indexPath) - else { return nil } - return PlayerEditionViewController(coder, mode: .edition, player: player) - } - - @IBSegueAction func makePlayerCreationViewController(_ coder: NSCoder) -> PlayerEditionViewController? { - let player = Player(id: nil, name: "", score: 0) - return PlayerEditionViewController(coder, mode: .creation, player: player) - } - - @IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) { - // Player creation cancelled - } - - @IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) { - // Player creation committed - } -} - - -// MARK: - UITableViewDataSource - -/// Subclass of UITableViewDiffableDataSource that supports row deletion -private class PlayerDataSource: UITableViewDiffableDataSource { - override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { - true - } - - override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { - // Delete the player - if let player = itemIdentifier(for: indexPath), let id = player.id { - try! AppDatabase.shared.deletePlayers(ids: [id]) - } - } -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift deleted file mode 100644 index 2c359a898..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift +++ /dev/null @@ -1,146 +0,0 @@ -import XCTest -import GRDB -@testable import GRDBDemoiOS - -class AppDatabaseTests: XCTestCase { - func test_database_schema() throws { - // Given an empty database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - - // When we instantiate an AppDatabase - _ = try AppDatabase(dbQueue) - - // Then the player table exists, with id, name & score columns - try dbQueue.read { db in - try XCTAssert(db.tableExists("player")) - let columns = try db.columns(in: "player") - let columnNames = Set(columns.map { $0.name }) - XCTAssertEqual(columnNames, ["id", "name", "score"]) - } - } - - func test_savePlayer_inserts() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - - // When we save a new player - var player = Player(id: nil, name: "Arthur", score: 100) - try appDatabase.savePlayer(&player) - - // Then the player exists in the database - try XCTAssertTrue(dbQueue.read(player.exists)) - } - - func test_savePlayer_updates() throws { - // Given a players database that contains a player - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - var player = Player(id: nil, name: "Arthur", score: 100) - try dbQueue.write { db in - try player.insert(db) - } - - // When we modify and save the player - player.name = "Barbara" - player.score = 1000 - try appDatabase.savePlayer(&player) - - // Then the player has been updated in the database - let fetchedPlayer = try dbQueue.read { db in - try XCTUnwrap(Player.fetchOne(db, key: player.id)) - } - XCTAssertEqual(fetchedPlayer, player) - } - - func test_deletePlayers() throws { - // Given a players database that contains four players - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - var player1 = Player(id: nil, name: "Arthur", score: 100) - var player2 = Player(id: nil, name: "Barbara", score: 200) - var player3 = Player(id: nil, name: "Craig", score: 150) - var player4 = Player(id: nil, name: "David", score: 120) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we delete two players - try appDatabase.deletePlayers(ids: [player1.id!, player3.id!]) - - // Then the deleted players no longer exist - try dbQueue.read { db in - try XCTAssertFalse(player1.exists(db)) - try XCTAssertFalse(player3.exists(db)) - } - - // Then the database still contains two players - try XCTAssertEqual(dbQueue.read(Player.fetchCount), 2) - } - - func test_deleteAllPlayers() throws { - // Given a players database that contains players - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - var player1 = Player(id: nil, name: "Arthur", score: 100) - var player2 = Player(id: nil, name: "Barbara", score: 200) - var player3 = Player(id: nil, name: "Craig", score: 150) - var player4 = Player(id: nil, name: "David", score: 120) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we delete all players - try appDatabase.deleteAllPlayers() - - // Then the database does not contain any player - try XCTAssertEqual(dbQueue.read(Player.fetchCount), 0) - } - - func test_refreshPlayers_populates_an_empty_database() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - - // When we refresh players - try appDatabase.refreshPlayers() - - // Then the database is not empty - try XCTAssert(dbQueue.read(Player.fetchCount) > 0) - } - - func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - - // When we create random players - try appDatabase.createRandomPlayersIfEmpty() - - // Then the database is not empty - try XCTAssert(dbQueue.read(Player.fetchCount) > 0) - } - - func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws { - // Given a players database that contains one player - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - let appDatabase = try AppDatabase(dbQueue) - var player = Player(id: nil, name: "Arthur", score: 100) - try dbQueue.write { db in - try player.insert(db) - } - - // When we create random players - try appDatabase.createRandomPlayersIfEmpty() - - // Then the database still only contains the original player - let players = try dbQueue.read(Player.fetchAll) - XCTAssertEqual(players, [player]) - } -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/Info.plist b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/Info.plist deleted file mode 100644 index 64d65ca49..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/Info.plist +++ /dev/null @@ -1,22 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - $(PRODUCT_BUNDLE_PACKAGE_TYPE) - CFBundleShortVersionString - 1.0 - CFBundleVersion - 1 - - diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift deleted file mode 100644 index 64d1c1d2b..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift +++ /dev/null @@ -1,108 +0,0 @@ -import XCTest -import GRDB -@testable import GRDBDemoiOS - -class PlayerTests: XCTestCase { - // MARK: - CRUD - // Test that our Player type properly talks to GRDB. - - func testInsert() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - - // When we insert a player - var player = Player(id: nil, name: "Arthur", score: 100) - try dbQueue.write { db in - try player.insert(db) - } - - // Then the player gets a non-nil id - XCTAssertNotNil(player.id) - } - - func testRoundtrip() throws { - // Given an empty players database - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - - // When we insert a player and fetch the player with the same id - var insertedPlayer = Player(id: nil, name: "Arthur", score: 100) - let fetchedPlayer: Player? = try dbQueue.write { db in - try insertedPlayer.insert(db) - return try Player.fetchOne(db, key: insertedPlayer.id) - } - - // Then the fetched player is equal to the inserted player - XCTAssertEqual(insertedPlayer, fetchedPlayer) - } - - // MARK: - Requests - // Test that requests defined on the Player type behave as expected. - - func testOrderedByScore() throws { - // Given a players database that contains players with distinct scores - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: 1, name: "Arthur", score: 100) - var player2 = Player(id: 2, name: "Barbara", score: 200) - var player3 = Player(id: 3, name: "Craig", score: 150) - var player4 = Player(id: 4, name: "David", score: 120) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we fetch players ordered by score - let players = try dbQueue.read(Player.all().orderedByScore().fetchAll) - - // Then fetched players are ordered by score descending - XCTAssertEqual(players, [player2, player3, player4, player1]) - } - - func testOrderedByScoreSortsIdenticalScoresByName() throws { - // Given a players database that contains players with common scores - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: 1, name: "Arthur", score: 100) - var player2 = Player(id: 2, name: "Barbara", score: 200) - var player3 = Player(id: 3, name: "Craig", score: 200) - var player4 = Player(id: 4, name: "David", score: 200) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we fetch players ordered by score - let players = try dbQueue.read(Player.all().orderedByScore().fetchAll) - - // Then fetched players are ordered by score descending and by name - XCTAssertEqual(players, [player2, player3, player4, player1]) - } - - func testOrderedByName() throws { - // Given a players database that contains players with distinct names - let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration()) - _ = try AppDatabase(dbQueue) - var player1 = Player(id: 1, name: "Arthur", score: 100) - var player2 = Player(id: 2, name: "Barbara", score: 200) - var player3 = Player(id: 3, name: "Craig", score: 150) - var player4 = Player(id: 4, name: "David", score: 120) - try dbQueue.write { db in - try player1.insert(db) - try player2.insert(db) - try player3.insert(db) - try player4.insert(db) - } - - // When we fetch players ordered by name - let players = try dbQueue.read(Player.all().orderedByName().fetchAll) - - // Then fetched players are ordered by name - XCTAssertEqual(players, [player1, player2, player3, player4]) - } -} diff --git a/Documentation/DemoApps/GRDBDemoiOS/README.md b/Documentation/DemoApps/GRDBDemoiOS/README.md deleted file mode 100644 index ab854697c..000000000 --- a/Documentation/DemoApps/GRDBDemoiOS/README.md +++ /dev/null @@ -1,45 +0,0 @@ -UIKit Demo Application -====================== - - - -**This demo application is a storyboard-based UIKit application.** For a demo application that uses Combine + SwiftUI, see [GRDBCombineDemo](../GRDBCombineDemo/README.md), and for Async/Await + SwiftUI, see [GRDBAsyncDemo](../GRDBAsyncDemo/README.md). - -**Requirements**: iOS 15.0+ / Xcode 12+ - -> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as an inspiration. - -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 table view 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). - -**Files of interest:** - -- [AppDatabase.swift](GRDBDemoiOS/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 [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) in order to let the application observe database changes. - -- [Persistence.swift](GRDBDemoiOS/Persistence.swift) - - This file defines the `AppDatabase` instance used by the application. - -- [Player.swift](GRDBDemoiOS/Player.swift) - - `Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records). It defines the database requests used by the application. - -- [PlayerListViewController.swift](GRDBDemoiOS/ViewControllers/PlayerListViewController.swift) - - `PlayerListViewController` displays the list of players. - -- [PlayerEditionViewController.swift](GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift) - - `PlayerEditionViewController` can create or edit a player, and save it in the database. - -- [GRDBDemoiOSTests](GRDBDemoiOSTests) - - - Test the database schema - - Test the `Player` record and its requests - - Test the `AppDatabase` methods that let the app access the database. diff --git a/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png b/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png deleted file mode 100644 index 7a0fccd71..000000000 Binary files a/Documentation/DemoApps/GRDBDemoiOS/Screenshot.png and /dev/null differ diff --git a/Documentation/DemoApps/README.md b/Documentation/DemoApps/README.md index 136665c68..8c6ce177f 100644 --- a/Documentation/DemoApps/README.md +++ b/Documentation/DemoApps/README.md @@ -1,13 +1,9 @@ Demo Applications ================= -- [GRDBDemoiOS]: a storyboard-based UIKit application. -- [GRDBCombineDemo]: a Combine + SwiftUI application. -- [GRDBAsyncDemo]: a Async/Await + SwiftUI application. +[GRDBDemo] demonstrates how GRDB can fuel a SwiftUI application. -[GRDBCombineDemo] and [GRDBAsyncDemo] use the same `@Query` property wrapper, that lets SwiftUI views automatically update their content when the database changes. It is defined in the [GRDBQuery] package. +See also the demo apps of the [GRDBQuery] package: they use the `@Query` property wrapper that helps SwiftUI views automatically update their content when the database changes. -[GRDBDemoiOS]: GRDBDemoiOS -[GRDBCombineDemo]: GRDBCombineDemo -[GRDBAsyncDemo]: GRDBAsyncDemo +[GRDBDemo]: GRDBDemo [GRDBQuery]: https://github.com/groue/GRDBQuery diff --git a/Documentation/FTS5Tokenizers.md b/Documentation/FTS5Tokenizers.md index 29c9d7572..2a3bccf5a 100644 --- a/Documentation/FTS5Tokenizers.md +++ b/Documentation/FTS5Tokenizers.md @@ -3,7 +3,7 @@ FTS5 Tokenizers **[FTS5](https://www.sqlite.org/fts5.html) is an extensible full-text search engine.** -GRDB lets you define your own custom FST5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are: +GRDB lets you define your own custom FTS5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are: - Have "fi" match the ligature "fi" (U+FB01) - Have "first" match "1st" @@ -95,7 +95,7 @@ let documents = try Document.matching(pattern).fetchAll(db) ## FTS5Tokenizer -**FST5Tokenizer** is the protocol for all FTS5 tokenizers. +**FTS5Tokenizer** is the protocol for all FTS5 tokenizers. It only requires a tokenization method that matches the low-level `xTokenize` C function documented at https://www.sqlite.org/fts5.html#custom_tokenizers. We'll discuss it more when describing custom tokenizers. diff --git a/Documentation/FetchedRecordsController.md b/Documentation/FetchedRecordsController.md index baf6c945a..e0fd779c0 100644 --- a/Documentation/FetchedRecordsController.md +++ b/Documentation/FetchedRecordsController.md @@ -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. diff --git a/Documentation/FullTextSearch.md b/Documentation/FullTextSearch.md index 69b1ae757..a3b93112d 100644 --- a/Documentation/FullTextSearch.md +++ b/Documentation/FullTextSearch.md @@ -82,7 +82,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do - **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables. -- See [FST3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences. +- See [FTS3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences. > **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html). @@ -91,7 +91,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do **FTS3 and FTS4 full-text tables store and index textual content.** -Create tables with the `create(virtualTable:using:)` method: +Create tables with the `create(virtualTable:options:using:_:)` method: ```swift // CREATE VIRTUAL TABLE document USING fts3(content) @@ -301,7 +301,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil ``` -FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/statementarguments): +FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments): ```swift let documents = try Document.fetchAll(db, @@ -316,7 +316,7 @@ Use them in the [query interface](../README.md#the-query-interface): let documents = try Document.matching(pattern).fetchAll(db) // Search in a specific column: -let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db) +let documents = try Document.filter { $0.content.match(pattern) }.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, @@ -565,7 +565,7 @@ Use them in the [query interface](../README.md#the-query-interface): let documents = try Document.matching(pattern).fetchAll(db) // Search in a specific column: -let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db) +let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db) ``` @@ -689,7 +689,7 @@ let books = Book.fetchAll(db, sql: sql, arguments: [pattern]) **You can define [record](../README.md#records) types around the full-text virtual tables.** -The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) for more information. +The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) for more information. ## Unicode Full-Text Gotchas diff --git a/Documentation/GRDB5MigrationGuide.md b/Documentation/GRDB5MigrationGuide.md index 797d1099f..fe674fde0 100644 --- a/Documentation/GRDB5MigrationGuide.md +++ b/Documentation/GRDB5MigrationGuide.md @@ -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 diff --git a/Documentation/GRDB6MigrationGuide.md b/Documentation/GRDB6MigrationGuide.md index 2d09a48ea..bccc9cb88 100644 --- a/Documentation/GRDB6MigrationGuide.md +++ b/Documentation/GRDB6MigrationGuide.md @@ -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: diff --git a/Documentation/GRDB7MigrationGuide.md b/Documentation/GRDB7MigrationGuide.md new file mode 100644 index 000000000..5bdadd11f --- /dev/null +++ b/Documentation/GRDB7MigrationGuide.md @@ -0,0 +1,282 @@ +Migrating From GRDB 6 to GRDB 7 +=============================== + +**This guide helps you upgrade your applications from GRDB 6 to GRDB 7.** + +- [Preparing the Migration to GRDB 7](#preparing-the-migration-to-grdb-7) +- [Recommendations Regarding Swift Concurrency](#recommendations-regarding-swift-concurrency) +- [New requirements](#new-requirements) +- [Companion Libraries](#companion-libraries) +- [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) +- [Other Changes](#other-changes) + +## Preparing the Migration to GRDB 7 + +Before upgrading, ensure you are using the [latest GRDB 6 release](https://github.com/groue/GRDB.swift/tags) and address any deprecation warnings. Once this is done, proceed with upgrading to GRDB 7. Due to breaking changes, your application may no longer compile. Follow the fix-it suggestions for simple syntax updates, and review the specific modifications described below. + +## Recommendations Regarding Swift Concurrency + +GRDB 7 requires Xcode 16+ and a Swift 6 compiler. + +Depending of the language mode and level of concurrency checkings used by your application, you may see warnings or errors. See [Migrating to Swift 6] on swift.org for more information about Swift 6. See [Swift Concurrency and GRDB] for GRDB-focused advice. + +## New requirements + +GRDB requirements have been bumped: + +- **Swift Compiler 6+** (was Swift 5.7+). +- **Xcode 16.0+** (was Xcode 14.0+) +- **iOS 13+** (was iOS 11+) +- **macOS 10.15+** (was macOS 10.13+) +- **tvOS 13+** (was tvOS 11+) +- **watchOS 7.0+** (was watchOS 4+) +- **SQLite 3.20.0+** (was SQLite 3.19.3+) + +## Companion Libraries + +Companion libraries have been updated for GRDB 7: + +- [GRDBQuery releases](https://github.com/groue/GRDBQuery/releases) (SwiftUI) +- [GRDBSnapshotTesting releases](https://github.com/groue/GRDBSnapshotTesting/releases) (Snapshot Testing) + +## Column Coding Strategies + +In GRDB 6, Codable record types can specify how `Data`, `Date`, and `UUID` properties are stored in the database: + +```swift +// GRDB 6 +struct Player { + static let databaseDataDecodingStrategy = ... + static let databaseDateDecodingStrategy = ... + static let databaseDataEncodingStrategy = ... + static let databaseDateEncodingStrategy = ... + static let databaseUUIDEncodingStrategy = ... +} +``` + +These properties have been removed in GRDB 7. You must now define methods that accept a column argument: + +```swift +// GRDB 7 +struct Player { + static func databaseDataDecodingStrategy(for column: String) -> DatabaseDataDecodingStrategy { ... } + static func databaseDateDecodingStrategy(for column: String) -> DatabaseDateDecodingStrategy { ...} + static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy { ... } + static func databaseDateEncodingStrategy(for column: String) -> DatabaseDateEncodingStrategy { ... } + static func databaseUUIDEncodingStrategy(for column: String) -> DatabaseUUIDEncodingStrategy { ... } +} +``` + +## Cancellable Async Database Accesses + +In GRDB 6, asynchronous database accesses such as `try await read { ... }` or `try await write { ... }` complete even if the wrapper Task is cancelled. + +In GRDB 7, asynchronous database accesses respect Task cancellation. If a Task is cancelled, reads and writes throw a `CancellationError`, pending transactions are rolled back, and the database is not modified. The only SQL statement that can execute in a cancelled database access is `ROLLBACK`. + +The effect of this change on your application depends on how it uses tasks. For example, take care of database jobs initiated frop the [`task`](https://developer.apple.com/documentation/swiftui/view/task(priority:_:)) SwiftUI modifier. + +If you want an asynchronous database access to always complete, regardless of Task cancellation, wrap it in an unstructured Task: + +```swift +// Create a new Task in order to ignore +// cancellation of the current task, and +// make sure database changes are always +// committed to disk. +let task = Task { + try await writer.write { ... } +} +// If needed, wait for the database job to complete: +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: + +```swift +// GRDB 6 +var config = Configuration() +config.defaultTransactionKind = .immediate +``` + +In GRDB 7, `Configuration` no longer has a `defaultTransactionKind` property, because transactions are automatically managed. Reads use DEFERRED transactions, and writes use IMMEDIATE transactions. + +You can still specify a transaction kind explicitly when necessary. See [Transaction Kinds] for details. + +## ValueObservation and the Main Actor + +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. + +It is not necessary to call `MainActor.assumeIsolated` in `ValueObservation` callbacks: + +```swift +// GRDB 7 +@MainActor func startObservation() { + let observation = ValueObservation.tracking { ... } + + let cancellable = observation.start(in: dbQueue) { error in + // This closure is MainActor-isolated. + } onChange: { value in + // This closure is MainActor-isolated. + print("Fresh value", value) + } +} +``` + +You can opt-out of the main actor with a specific scheduler such as `.async(onQueue:)`: + +```swift +func startObservation() { + let observation = ValueObservation.tracking { ... } + + let cancellable = observation.start( + in: dbQueue, + scheduling: .async(onQueue: .main)) + { error in + // Called on the specified dispatch queue. + } onChange: { value in + // Called on the specified dispatch queue. + print("Fresh value", value) + } +} +``` + +## Access to SQLite C functions + +In GRDB 6, the underlying C SQLite library is implicitly available: + +```swift +// GRDB 6 +import GRDB + +let sqliteVersion = sqlite3_libversion_number() +``` + +In GRDB 7, you may need an additional import, depending on how GRDB is integrated: + +- If your app uses the GRDB Swift Package Manager (SPM) package: + + ```swift + import SQLite3 + + let sqliteVersion = sqlite3_libversion_number() + ``` + + The GRDB 6 SPM package included a product named "CSQLite." In GRDB 7, this product has been renamed "GRDBSQLite." Update your dependencies accordingly. It is unclear at the time of writing whether some projects can remove this dependency. + +- If your app uses SQLCipher: + + ```swift + import SQLCipher + + let sqliteVersion = sqlite3_libversion_number() + ``` + +- In other cases, no additional import is needed. + +## The Record Base Class is Discouraged + +Subclassing the [Record] class is **discouraged** in GRDB 7. Present in GRDB 1.0, in 2017, it has served its purpose. + +It is not recommended to define any new type that subclass `Record`. + +It is recommended to refactor `Record` subclasses into Swift structs, before you enable the strict concurrency checkings or the Swift 6 language mode. See [Migrating to Swift 6] for more information about Swift 6 language modes. + +For example: + +```swift +// GRDB 6 +class Player: Record { + var id: UUID + var name: String + var score: Int + + override class var databaseTableName: String { "player" } + + init(id: UUID, name: String, score: Int) { ... } + required init(row: Row) throws { ... } + override func encode(to container: inout PersistenceContainer) throws { ...} +} + +// GRDB 7 +struct Player: Codable { + var id: UUID + var name: String + var score: Int +} + +extension Player: FetchableRecord, PersistableRecord { } +``` + +Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non-Sendable record types in GRDB. + +## Other Changes + +- `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. + +[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide +[Sharing a Database]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing +[Transaction Kinds]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactions#Transaction-Kinds +[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/swiftconcurrency +[Record]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/record diff --git a/Documentation/GoodPracticesForDesigningRecordTypes.md b/Documentation/GoodPracticesForDesigningRecordTypes.md index 1bcdbd223..9c53da1d5 100644 --- a/Documentation/GoodPracticesForDesigningRecordTypes.md +++ b/Documentation/GoodPracticesForDesigningRecordTypes.md @@ -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). diff --git a/Documentation/Migrations.md b/Documentation/Migrations.md index ab404434b..15822fb0a 100644 --- a/Documentation/Migrations.md +++ b/Documentation/Migrations.md @@ -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). diff --git a/Documentation/Playgrounds/Tour.playground/Contents.swift b/Documentation/Playgrounds/Tour.playground/Contents.swift index baa8f20c2..a7d10416f 100644 --- a/Documentation/Playgrounds/Tour.playground/Contents.swift +++ b/Documentation/Playgrounds/Tour.playground/Contents.swift @@ -32,14 +32,14 @@ try dbQueue.inDatabase { db in CREATE TABLE place ( id INTEGER PRIMARY KEY, title TEXT, - favorite BOOLEAN NOT NULL, + isFavorite BOOLEAN NOT NULL, latitude DOUBLE NOT NULL, longitude DOUBLE NOT NULL ) """) try db.execute(sql: """ - INSERT INTO place (title, favorite, latitude, longitude) + INSERT INTO place (title, isFavorite, latitude, longitude) VALUES (?, ?, ?, ?) """, arguments: ["Paris", true, 48.85341, 2.3488]) let parisId = db.lastInsertedRowID @@ -52,11 +52,11 @@ try! dbQueue.inDatabase { db in let rows = try Row.fetchCursor(db, sql: "SELECT * FROM place") while let row = try rows.next() { let title: String = row["title"] - let favorite: Bool = row["favorite"] + let isFavorite: Bool = row["isFavorite"] let coordinate = CLLocationCoordinate2D( latitude: row["latitude"], longitude: row["longitude"]) - print("Fetched", title, favorite, coordinate) + print("Fetched", title, isFavorite, coordinate) } let placeCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! // Int @@ -69,35 +69,43 @@ try! dbQueue.inDatabase { db in struct Place { var id: Int64? var title: String? - var favorite: Bool + var isFavorite: Bool var coordinate: CLLocationCoordinate2D } // Adopt FetchableRecord extension Place : FetchableRecord { init(row: Row) { - id = row["id"] - title = row["title"] - favorite = row["favorite"] + id = row[Columns.id] + title = row[Columns.title] + isFavorite = row[Columns.isFavorite] coordinate = CLLocationCoordinate2DMake( - row["latitude"], - row["longitude"]) + row[Columns.latitude], + row[Columns.longitude]) } } // Adopt TableRecord extension Place : TableRecord { static let databaseTableName = "place" + + enum Columns { + static let id = Column("id") + static let title = Column("title") + static let isFavorite = Column("isFavorite") + static let latitude = Column("latitude") + static let longitude = Column("longitude") + } } // Adopt MutablePersistableRecord extension Place : MutablePersistableRecord { func encode(to container: inout PersistenceContainer) throws { - container["id"] = id - container["title"] = title - container["favorite"] = favorite - container["latitude"] = coordinate.latitude - container["longitude"] = coordinate.longitude + container[Columns.id] = id + container[Columns.title] = title + container[Columns.isFavorite] = isFavorite + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude } mutating func didInsert(_ inserted: InsertionSuccess) { @@ -109,13 +117,13 @@ try dbQueue.inDatabase { db in var berlin = Place( id: nil, title: "Berlin", - favorite: false, + isFavorite: false, coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053)) try berlin.insert(db) berlin.id // some value - berlin.favorite = true + berlin.isFavorite = true try berlin.update(db) // Fetch from SQL @@ -124,13 +132,10 @@ try dbQueue.inDatabase { db in //: Avoid SQL with the query interface: - let title = Column("title") - let favorite = Column("favorite") - - berlin = try Place.filter(title == "Berlin").fetchOne(db)! // Place + berlin = try Place.filter { $0.title == "Berlin" }.fetchOne(db)! // Place let paris = try Place.fetchOne(db, key: 1) // Place? let favoritePlaces = try Place // [Place] - .filter(favorite == true) - .order(title) + .filter { $0.isFavorite == true } + .order { $0.title } .fetchAll(db) } diff --git a/Documentation/QueryInterfaceOrganization.md b/Documentation/QueryInterfaceOrganization.md index e78e652a0..4a3b44d62 100644 --- a/Documentation/QueryInterfaceOrganization.md +++ b/Documentation/QueryInterfaceOrganization.md @@ -93,7 +93,7 @@ Columns are special expressions that allow some optimizations and niceties: ValueObservation.tracking { db in try Player.fetchOne(db, id: 1) // or - try Player.filter(Column("id") == 1).fetchOne(db) + try Player.filter { $0.id == 1 }.fetchOne(db) } // Non-optimized observations @@ -110,7 +110,7 @@ Columns are special expressions that allow some optimizations and niceties: // Nicer SQL // SELECT * FROM player WHERE id = 1 try Player.fetchOne(db, id: 1) - try Player.filter(Column("id") == 1).fetchOne(db) + try Player.filter { $0.id == 1 }.fetchOne(db) // Less nice SQL // SELECT * FROM player WHERE id = 1 LIMIT 1 @@ -195,7 +195,7 @@ protocol DerivableRequest: 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 @@ -261,7 +261,7 @@ The basic value types conform to [DatabaseValueConvertible] so that they can fee ```swift // SELECT * FROM player WHERE name = 'O''Brien' // ~~~~~~~~~~ -Player.filter(Column("name") == "O'Brien") +Player.filter { $0.name == "O'Brien" } ``` ### QueryInterfaceRequest @@ -346,8 +346,9 @@ Functions and methods that build an SQL expression should return an SQLExpressio ```swift // SELECT * FROM player WHERE LENGTH(name) > 0 -let expression = length(Column("name")) > 0 // SQLExpression -Player.filter(expression) +Player.filter { + length($0.name) > 0 // SQLExpression +} ``` When it looks like GRDB APIs are unable to build a particular expression, use [SQL]: @@ -358,7 +359,7 @@ func date(_ value: SQLSpecificExpressible) -> SQLExpression { } // SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23' -let request = Player.filter(date(Column("createdAt")) == "2020-01-23") +let request = Player.filter { date($0.createdAt) == "2020-01-23" } ``` This technique, based on [SQL Interpolation], is composable and works well even when several tables are involved. See how the `createdAt` column below is correctly attributed to the `player` table: @@ -368,7 +369,7 @@ This technique, based on [SQL Interpolation], is composable and works well even // JOIN team ON team.id = player.teamId // WHERE DATE(player.createdAt) = '2020-01-23' let request = Player - .filter(date(Column("createdAt")) == "2020-01-23") + .filter { date($0.createdAt) == "2020-01-23" } .including(required: Player.team) ``` @@ -497,7 +498,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 +506,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")) @@ -583,7 +584,7 @@ SQLSubqueryable provides the GRDB support for subqueries. Its [SQLSpecificExpres // SELECT * FROM player // WHERE score >= (SELECT AVG(score) FROM player) let averageScore = Player.select(average(Column("score"))) -Player.filter(Column("score") >= averageScore) +Player.filter { $0.score >= averageScore } ``` SQLSubqueryable has the `contains(_:)` and `exists()` methods that support the `value IN (subquery)` and `EXISTS (subquery)` expressions. @@ -607,8 +608,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 diff --git a/Documentation/ReleaseProcess.md b/Documentation/ReleaseProcess.md index 008b24d66..30379d434 100644 --- a/Documentation/ReleaseProcess.md +++ b/Documentation/ReleaseProcess.md @@ -7,8 +7,7 @@ To release a new GRDB version: - Tests - `make distclean test` - - Build and run GRDBDemoiOS in Release configuration on a device - - Archive GRDBDemoiOS + - Build and run GRDBDemo - Check for performance regression with GRDBOSXPerformanceTests - On https://github.com/groue/sqlcipher.git upgrade, update SQLCipher version in README.md - On https://github.com/swiftlyfalling/SQLiteLib upgrade, update SQLite version in Documentation/CustomSQLiteBuilds.md @@ -18,8 +17,10 @@ To release a new GRDB version: - README.md - Support/Info.plist - Commit and tag -- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags` -- Push to the master & development branch +- Look for undesired tags: `git for-each-ref --format '%(refname) %(authorname)' refs/tags` +- Push to the `master` branch +- Push to the `development` branch +- Push to the `GRDB7` branch - `pod trunk push --allow-warnings GRDB.swift.podspec` - Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance): diff --git a/Documentation/SQLInterpolation.md b/Documentation/SQLInterpolation.md index 2af59d2fb..0de946d3c 100644 --- a/Documentation/SQLInterpolation.md +++ b/Documentation/SQLInterpolation.md @@ -175,7 +175,7 @@ func date(_ expression: SQLExpressible) -> SQLExpression { SQL("DATE(\(expression))").sqlExpression } -let request = Player.filter(date(Column("createdAt")) == "2020-01-23") +let request = Player.filter { date($0.createdAt) == "2020-01-23" } ``` @@ -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 { ... } @@ -395,7 +395,9 @@ This chapter lists all kinds of supported interpolations. struct AltPlayer: TableRecord { static let databaseTableName = "player" - static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")] + static var databaseSelection: [any SQLSelectable] { + [Column("id"), Column("name")] + } } // SELECT player.id, player.name FROM player diff --git a/Documentation/SharingADatabase.md b/Documentation/SharingADatabase.md index 962b5adf7..b87e85d71 100644 --- a/Documentation/SharingADatabase.md +++ b/Documentation/SharingADatabase.md @@ -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). diff --git a/Documentation/SingleRowTables.md b/Documentation/SingleRowTables.md index 2ecb8bb4a..330a5ed39 100644 --- a/Documentation/SingleRowTables.md +++ b/Documentation/SingleRowTables.md @@ -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). diff --git a/Documentation/WhyAdoptGRDB.md b/Documentation/WhyAdoptGRDB.md index 8ce463636..dabfb4dcf 100644 --- a/Documentation/WhyAdoptGRDB.md +++ b/Documentation/WhyAdoptGRDB.md @@ -90,7 +90,7 @@ For your convenience, those record protocols can be derived from the [Decodable Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages. -See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for some practical advice. +See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) for some practical advice. ### Allow database records to cross threads @@ -149,16 +149,16 @@ Next, you choose the dispatch queue on which notifications happen (generally the Finally, all changes are notified, no matter how they are performed: record methods, raw SQL statements, foreign key cascades, or SQL triggers. GRDB roots its notification system in the rock-solid SQLite itself, so that high-level requests and raw SQL queries are equally supported. -See [Database Observation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation) for further information. +See [Database Observation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation) for further information. ### Non-blocking database reads -GRDB ships with two ways to access databases, [database queues](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasequeue) and [pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool). +GRDB ships with two ways to access databases, [database queues](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasequeue) and [pools](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool). Database queues look a lot like FMDB's [FMDatabaseQueue](https://github.com/ccgus/fmdb#using-fmdatabasequeue-and-thread-safety): they serialize database accesses in a serial dispatch queue. There is never more than one thread that is accessing the database. This means that a long running database transaction that happens in a background thread, such as the synchronization of your local database from a remote server, can block your UI. As long as the queue is busy, the main thread can't fetch the values it wants to display on screen. -[Database pools](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured). +[Database pools](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool) can lift these unwanted locks. With database pools, reads are generally non-blocking, unless the maximum number of concurrent reads has been reached (and this maximum number can be configured). ### Strong and clear multi-threading guarantees @@ -190,7 +190,7 @@ Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and For detailed information about GRDB concurrency, check the [Concurrency Guide]. -For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices). +For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices). ### Never pay for using raw SQL @@ -207,13 +207,13 @@ try player.updateChanges { // SELECT * FROM player ORDER BY score DESC LIMIT 10 let bestPlayers: [Player] = try Player - .order(scoreColumn.desc) + .order(\.score.desc) .limit(10) .fetchAll(db) // SELECT MAX(score) FROM player let maximumScore: Int? = try Player - .select(max(scoreColumn)) + .select { max($0.score) } .asRequestOf(Int.self) .fetchOne(db) @@ -285,12 +285,12 @@ If this little tour of GRDB has convinced you, the real trip starts here: [GRDB] Happy GRDB! :gift: -[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency +[Concurrency Guide]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/concurrency [Core Data]: https://developer.apple.com/documentation/coredata -[DatabasePool]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool +[DatabasePool]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool [Diesel]: http://diesel.rs [FCModel]: https://github.com/marcoarment/FCModel -[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation +[ValueObservation]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation [Fluent]: https://github.com/vapor/fluent [FMDB]: https://github.com/ccgus/fmdb [GRDB]: https://github.com/groue/GRDB.swift diff --git a/GRDB.swift.podspec b/GRDB.swift.podspec index 9c58025bc..25cfbaeb4 100644 --- a/GRDB.swift.podspec +++ b/GRDB.swift.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'GRDB.swift' - s.version = '6.28.0' + s.version = '7.5.0' s.license = { :type => 'MIT', :file => 'LICENSE' } s.summary = 'A toolkit for SQLite databases, with a focus on application development.' @@ -9,11 +9,11 @@ Pod::Spec.new do |s| s.source = { :git => 'https://github.com/groue/GRDB.swift.git', :tag => "v#{s.version}" } s.module_name = 'GRDB' - s.swift_versions = ['5.7'] - s.ios.deployment_target = '11.0' - s.osx.deployment_target = '10.13' - s.watchos.deployment_target = '4.0' - s.tvos.deployment_target = '11.0' + s.swift_versions = ['6'] + s.ios.deployment_target = '13.0' + s.osx.deployment_target = '10.15' + s.watchos.deployment_target = '7.0' + s.tvos.deployment_target = '13.0' s.default_subspec = 'standard' s.subspec 'standard' do |ss| diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index 9c13f9eb0..9ad49d0b6 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -68,6 +68,7 @@ 562206071E420EA4005860AC /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; }; 562206081E420EA4005860AC /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 5622060C1E420EB3005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; }; + 56231A442DCF3A19007676E4 /* TableAlias.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231A432DCF3A19007676E4 /* TableAlias.swift */; }; 562393181DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; }; 562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */; }; @@ -88,6 +89,7 @@ 563363C01C942C04000BE133 /* DatabaseReader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BF1C942C04000BE133 /* DatabaseReader.swift */; }; 563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363C31C942C37000BE133 /* DatabaseWriter.swift */; }; 5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5636E9BB1D22574100B9B05F /* FetchRequest.swift */; }; + 563866CB2C847659004C515A /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563866CA2C847654004C515A /* AsyncSemaphore.swift */; }; 563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */; }; 563B06BD2185CCD300B38F35 /* ValueObservationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06BC2185CCD300B38F35 /* ValueObservationTests.swift */; }; 563B06C72185D29F00B38F35 /* ValueObservationReadonlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */; }; @@ -105,6 +107,7 @@ 563C67B324628BEA00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */; }; 563CBBE12A595131008905CE /* SQLIndexGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563CBBE02A595131008905CE /* SQLIndexGenerator.swift */; }; 563DE4F3231A91E2005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */; }; + 563EA3E12C7B3A22001BE0D4 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EA3E02C7B3A22001BE0D4 /* Mutex.swift */; }; 563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF414215F87EB007DAACD /* OrderedDictionary.swift */; }; 563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF42C2161180D007DAACD /* AssociationAggregate.swift */; }; 563EF43F216131D1007DAACD /* AssociationAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF43E216131D1007DAACD /* AssociationAggregateTests.swift */; }; @@ -165,7 +168,7 @@ 5657AAB91D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; }; 5657AB0F1D10899D006283EF /* URL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB0E1D10899D006283EF /* URL.swift */; }; 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F4871EA8D94E004A4992 /* Utils.swift */; }; - 5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */; }; + 5659F4901EA8D964004A4992 /* ReadWriteLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F48F1EA8D964004A4992 /* ReadWriteLock.swift */; }; 5659F4981EA8D989004A4992 /* Pool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F4971EA8D989004A4992 /* Pool.swift */; }; 5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475991D97D8A000FF74B8 /* SQLCollection.swift */; }; 566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */; }; @@ -186,7 +189,7 @@ 566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */; }; 566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */; }; - 566BE71E2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; }; + 566BE71E2342542F00A8254B /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* Mutex.swift */; }; 566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.swift */; }; 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; }; @@ -267,7 +270,6 @@ 56A2388B1B9C75030082EB20 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; }; 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */; }; 56A238A41B9C753B0082EB20 /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; }; - 56A2FA3624424D2A00E97D23 /* Export.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2FA3524424D2A00E97D23 /* Export.swift */; }; 56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */; }; 56A8C2301D1914540096E9D4 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; }; 56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AACAA722ACED7100A40F2A /* Fetch.swift */; }; @@ -486,6 +488,7 @@ 561F38D72AC88A550051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = ""; }; 561F38EE2AC9CE130051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = ""; }; 561F38F32AC9CE510051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = ""; }; + 56231A432DCF3A19007676E4 /* TableAlias.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableAlias.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = EnumeratedCursorTests.swift; sourceTree = ""; }; @@ -518,6 +521,7 @@ 563363D41C94484E000BE133 /* DatabaseQueueReleaseMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReleaseMemoryTests.swift; sourceTree = ""; }; 5634B1061CF9B970005360B9 /* TransactionObserverSavepointsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverSavepointsTests.swift; sourceTree = ""; }; 5636E9BB1D22574100B9B05F /* FetchRequest.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequest.swift; sourceTree = ""; }; + 563866CA2C847654004C515A /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = ""; }; 563B06AA217EF0CC00B38F35 /* ValueObservation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservation.swift; sourceTree = ""; }; 563B06BC2185CCD300B38F35 /* ValueObservationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationTests.swift; sourceTree = ""; }; 563B06C22185D29F00B38F35 /* ValueObservationReadonlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueObservationReadonlyTests.swift; sourceTree = ""; }; @@ -535,6 +539,7 @@ 563C67B224628BEA00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = ""; }; 563CBBE02A595131008905CE /* SQLIndexGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIndexGenerator.swift; sourceTree = ""; }; 563DE4EC231A91E2005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; + 563EA3E02C7B3A22001BE0D4 /* Mutex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = ""; }; 563EF414215F87EB007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; 563EF42C2161180D007DAACD /* AssociationAggregate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregate.swift; sourceTree = ""; }; 563EF43E216131D1007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = ""; }; @@ -602,7 +607,7 @@ 5657AB341D108BA9006283EF /* FoundationNSURLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSURLTests.swift; sourceTree = ""; }; 5657AB351D108BA9006283EF /* FoundationURLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationURLTests.swift; sourceTree = ""; }; 5659F4871EA8D94E004A4992 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; - 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; + 5659F48F1EA8D964004A4992 /* ReadWriteLock.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteLock.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; @@ -629,7 +634,7 @@ 566B912A1FA4D0CC0012D5B0 /* StatementAuthorizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatementAuthorizer.swift; sourceTree = ""; }; 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; 566B9C1F25C6CC24004542CF /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = ""; }; - 566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; }; + 566BE7172342542F00A8254B /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = ""; }; 566DDE0C288D763C0000DCFB /* Fixits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Fixits.swift; sourceTree = ""; }; 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = ""; }; @@ -717,6 +722,7 @@ 5698AD151DAAD16F0056AF8C /* FTS5Tokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5Tokenizer.swift; sourceTree = ""; }; 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizer.swift; sourceTree = ""; }; 5698AD341DABAF4A0056AF8C /* FTS5CustomTokenizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5CustomTokenizer.swift; sourceTree = ""; }; + 5698C1C32CA844F4001C0EB0 /* GRDBTests.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBTests.xcconfig; sourceTree = ""; }; 569BBA20228DE51800478429 /* AssociationPrefetchingFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingFetchableRecordTests.swift; sourceTree = ""; }; 569BBA3522905FFA00478429 /* InflectionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InflectionsTests.swift; sourceTree = ""; }; 569BBA4522906A8200478429 /* InflectionsTests.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = InflectionsTests.json; sourceTree = ""; }; @@ -756,7 +762,6 @@ 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = ""; }; 56A238A11B9C753B0082EB20 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = ""; }; 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTimestampTests.swift; sourceTree = ""; }; - 56A2FA3524424D2A00E97D23 /* Export.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Export.swift; sourceTree = ""; }; 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionLiteralTests.swift; sourceTree = ""; }; 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordWithColumnNameManglingTests.swift; sourceTree = ""; }; 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyInfoTests.swift; sourceTree = ""; }; @@ -1010,8 +1015,10 @@ 56176C581EACC2D8000F3F2B /* GRDBTests */ = { isa = PBXGroup; children = ( + 563866CA2C847654004C515A /* AsyncSemaphore.swift */, 56677C14241D14450050755D /* FailureTestCase.swift */, 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, + 563EA3E02C7B3A22001BE0D4 /* Mutex.swift */, 562EA81E1F17B26F00FA528C /* Compilation */, 56A238111B9C74A90082EB20 /* Core */, 567B5BDA2AD3281B00629622 /* Dump */, @@ -1279,6 +1286,7 @@ 568D13182207213E00674B58 /* SQLQueryGenerator.swift */, 56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */, 56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */, + 56231A432DCF3A19007676E4 /* TableAlias.swift */, ); path = SQLGeneration; sourceTree = ""; @@ -1320,11 +1328,11 @@ 56717270261C68E900423B6F /* CaseInsensitiveIdentifier.swift */, 563EF4492161F179007DAACD /* Inflections.swift */, 569BBA482291707D00478429 /* Inflections+English.swift */, - 566BE7172342542F00A8254B /* LockedBox.swift */, + 566BE7172342542F00A8254B /* Mutex.swift */, 563B8FC424A1D3B9007A48C9 /* OnDemandFuture.swift */, 563EF414215F87EB007DAACD /* OrderedDictionary.swift */, 5659F4971EA8D989004A4992 /* Pool.swift */, - 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */, + 5659F48F1EA8D964004A4992 /* ReadWriteLock.swift */, 563B8FB424A1D029007A48C9 /* ReceiveValuesOn.swift */, 56781B0A243F86E600650A83 /* Refinable.swift */, 5659F4871EA8D94E004A4992 /* Utils.swift */, @@ -1740,7 +1748,6 @@ DC37742D19C8CC90004FCF85 /* GRDB */ = { isa = PBXGroup; children = ( - 56A2FA3524424D2A00E97D23 /* Export.swift */, 566DDE0C288D763C0000DCFB /* Fixits.swift */, 648704AD2B7E66390036480B /* PrivacyInfo.xcprivacy */, 56A2386F1B9C75030082EB20 /* Core */, @@ -1766,6 +1773,7 @@ 56C48E731C9A9923005DF1D9 /* module.modulemap */, DC3773F719C8CBB3004FCF85 /* Info.plist */, 56B8F49A1B4E2F3600C24296 /* GRDB.xcconfig */, + 5698C1C32CA844F4001C0EB0 /* GRDBTests.xcconfig */, 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */, ); name = "Supporting Files"; @@ -2061,6 +2069,7 @@ 5615B275222B107900061C1C /* AssociationHasOneThroughFetchableRecordTests.swift in Sources */, 56D4966F1D81309E008276D7 /* RecordPrimaryKeyNoneTests.swift in Sources */, 56D496621D81304E008276D7 /* StatementArguments+FoundationTests.swift in Sources */, + 563EA3E12C7B3A22001BE0D4 /* Mutex.swift in Sources */, 56176C5D1EACCCC7000F3F2B /* FTS5TokenizerTests.swift in Sources */, 56D496B21D8133CE008276D7 /* DatabaseQueueInMemoryTests.swift in Sources */, 562393601DEE06D300A6B01F /* CursorTests.swift in Sources */, @@ -2114,6 +2123,7 @@ 56D496681D813086008276D7 /* FetchableRecord+QueryInterfaceRequestTests.swift in Sources */, 5623934E1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */, + 563866CB2C847659004C515A /* AsyncSemaphore.swift in Sources */, 56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, 5676FBA622F5CAD9004717D9 /* ValueObservationRegionRecordingTests.swift in Sources */, 56D496B41D8133F8008276D7 /* DatabaseTests.swift in Sources */, @@ -2161,6 +2171,7 @@ buildActionMask = 2147483647; files = ( 568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */, + 56231A442DCF3A19007676E4 /* TableAlias.swift in Sources */, 56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */, 5685C1932AD52EE600DA4B7A /* ListDumpFormat.swift in Sources */, 56158780288D875E00A67323 /* Optional.swift in Sources */, @@ -2180,7 +2191,7 @@ 563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */, 56D110FA28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */, 56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */, - 5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */, + 5659F4901EA8D964004A4992 /* ReadWriteLock.swift in Sources */, 566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */, 569EF0E2200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */, 56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, @@ -2226,7 +2237,6 @@ 5617294E223533F40006E219 /* EncodableRecord.swift in Sources */, 56B7EE832863781300C0525F /* WALSnapshot.swift in Sources */, 5698AD181DAAD17A0056AF8C /* FTS5Tokenizer.swift in Sources */, - 56A2FA3624424D2A00E97D23 /* Export.swift in Sources */, 56B964B11DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, 4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */, 560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */, @@ -2269,7 +2279,7 @@ 5690C3401D23E82A00E59934 /* Data.swift in Sources */, 5659F4881EA8D94E004A4992 /* Utils.swift in Sources */, 567B5BE82AD3284100629622 /* DumpFormat.swift in Sources */, - 566BE71E2342542F00A8254B /* LockedBox.swift in Sources */, + 566BE71E2342542F00A8254B /* Mutex.swift in Sources */, 56A238931B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */, 5603CEBB2AC862EC00CF097D /* SQLJSONExpressible.swift in Sources */, 56F89DF72A57EAA9002FE2AA /* ColumnDefinition.swift in Sources */, @@ -2340,7 +2350,7 @@ /* Begin XCBuildConfiguration section */ 56E5D8021B4D422E00430942 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */; + baseConfigurationReference = 5698C1C32CA844F4001C0EB0 /* GRDBTests.xcconfig */; buildSettings = { CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_WEAK = YES; @@ -2370,7 +2380,7 @@ }; 56E5D8031B4D422E00430942 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */; + baseConfigurationReference = 5698C1C32CA844F4001C0EB0 /* GRDBTests.xcconfig */; buildSettings = { CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_WEAK = YES; diff --git a/GRDB.xcworkspace/contents.xcworkspacedata b/GRDB.xcworkspace/contents.xcworkspacedata index 3258ed7a7..26f0eae47 100644 --- a/GRDB.xcworkspace/contents.xcworkspacedata +++ b/GRDB.xcworkspace/contents.xcworkspacedata @@ -45,12 +45,6 @@ location = "group:Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj"> - - - - + location = "group:Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj"> diff --git a/GRDB/Core/Configuration.swift b/GRDB/Core/Configuration.swift index 6b261902b..067260d62 100644 --- a/GRDB/Core/Configuration.swift +++ b/GRDB/Core/Configuration.swift @@ -1,7 +1,19 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + +#if !canImport(Darwin) +@preconcurrency +#endif import Dispatch import Foundation -public struct Configuration { +public struct Configuration: Sendable { // MARK: - Misc options @@ -132,7 +144,7 @@ public struct Configuration { /// do { /// // The sensitive information to protect /// let email = "..." - /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// let player = try Player.filter { $0.email == email }.fetchOne(db) /// } catch { /// // By default, sensitive information is NOT printed /// // when an error occurs: @@ -161,7 +173,7 @@ public struct Configuration { /// do { /// // The sensitive information to protect /// let email = "..." - /// let player = try Player.filter(Column("email") == email).fetchOne(db) + /// let player = try Player.filter { $0.email == email }.fetchOne(db) /// } catch { /// // Sensitive information is printed in DEBUG builds: /// print(error) @@ -186,7 +198,7 @@ public struct Configuration { // MARK: - Managing SQLite Connections - private var setups: [(Database) throws -> Void] = [] + private var setups: [@Sendable (Database) throws -> Void] = [] /// Defines a function to run whenever an SQLite connection is opened. /// @@ -223,34 +235,12 @@ public struct Configuration { /// /// On newly created databases files, ``DatabasePool`` activates the WAL /// mode after the preparation functions have run. - public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) { + public mutating func prepareDatabase(_ setup: @escaping @Sendable (Database) throws -> Void) { setups.append(setup) } // MARK: - Transactions - /// The default kind of write transactions. - /// - /// The default is ``Database/TransactionKind/deferred``. - /// - /// You can change the default transaction kind. For example, you can force - /// all write transactions to be `IMMEDIATE`: - /// - /// ```swift - /// var config = Configuration() - /// config.defaultTransactionKind = .immediate - /// let dbQueue = try DatabaseQueue(configuration: config) - /// - /// // BEGIN IMMEDIATE TRANSACTION; ...; COMMIT TRANSACTION; - /// try dbQueue.write { db in ... } - /// ``` - /// - /// This property is ignored for read-only transactions. Those always open - /// `DEFERRED` SQLite transactions. - /// - /// Related SQLite documentation: - public var defaultTransactionKind: Database.TransactionKind = .deferred - /// A boolean value indicating whether it is valid to leave a transaction /// opened at the end of a database access method. /// @@ -445,9 +435,25 @@ public struct Configuration { /// through a `SerializedDatabase`. var threadingMode = Database.ThreadingMode.default - var SQLiteConnectionDidOpen: (() -> Void)? - var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)? - var SQLiteConnectionDidClose: (() -> Void)? + private(set) var SQLiteConnectionDidOpen: (@Sendable () -> Void)? + private(set) var SQLiteConnectionWillClose: (@Sendable (SQLiteConnection) -> Void)? + private(set) var SQLiteConnectionDidClose: (@Sendable () -> Void)? + + // Workaround https://github.com/apple/swift/issues/72727 + mutating func onConnectionDidOpen(_ callback: @escaping @Sendable () -> Void) { + SQLiteConnectionDidOpen = callback + } + + // Workaround https://github.com/apple/swift/issues/72727 + mutating func onConnectionWillClose(_ callback: @escaping @Sendable (SQLiteConnection) -> Void) { + SQLiteConnectionWillClose = callback + } + + // Workaround https://github.com/apple/swift/issues/72727 + mutating func onConnectionDidClose(_ callback: @escaping @Sendable () -> Void) { + SQLiteConnectionDidClose = callback + } + var SQLiteOpenFlags: CInt { var flags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE) if sqlite3_libversion_number() >= 3037000 { diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index af874297c..68baeab44 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -670,9 +670,6 @@ extension Cursor where Element: Equatable { extension Cursor where Element: Comparable { /// Returns the maximum element in the cursor. /// - /// - Parameter areInIncreasingOrder: A predicate that returns `true` - /// if its first argument should be ordered before its second - /// argument; otherwise, `false`. /// - Returns: The cursor's maximum element, according to /// `areInIncreasingOrder`. If the cursor has no elements, returns /// `nil`. @@ -682,9 +679,6 @@ extension Cursor where Element: Comparable { /// Returns the minimum element in the cursor. /// - /// - Parameter areInIncreasingOrder: A predicate that returns `true` - /// if its first argument should be ordered before its second - /// argument; otherwise, `false`. /// - Returns: The cursor's minimum element, according to /// `areInIncreasingOrder`. If the cursor has no elements, returns /// `nil`. @@ -754,17 +748,13 @@ public final class AnyCursor: Cursor { } /// Creates a new cursor whose elements are elements of `iterator`. - public convenience init(iterator: I) - where I: IteratorProtocol, I.Element == Element - { + public convenience init(iterator: some IteratorProtocol) { var iterator = iterator self.init { iterator.next() } } /// Creates a new cursor whose elements are elements of `sequence`. - public convenience init(_ sequence: S) - where S: Sequence, S.Element == Element - { + public convenience init(_ sequence: some Sequence) { self.init(iterator: sequence.makeIterator()) } @@ -915,6 +905,10 @@ public final class FilterCursor { } } +// Explicit non-conformance to Sendable. +@available(*, unavailable) +extension FilterCursor: Sendable { } + extension FilterCursor: Cursor { public func next() throws -> Base.Element? { while let element = try base.next() { diff --git a/GRDB/Core/Database+Schema.swift b/GRDB/Core/Database+Schema.swift index 878cbe72b..ff8f9bf1d 100644 --- a/GRDB/Core/Database+Schema.swift +++ b/GRDB/Core/Database+Schema.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + extension Database { /// A cache for the available database schemas. struct SchemaCache { @@ -87,7 +96,15 @@ extension Database { // MARK: - Database Schema - /// Returns the current schema version. + /// Returns the current schema version (`PRAGMA schema_version`). + /// + /// For example: + /// + /// ```swift + /// let version = try dbQueue.read { db in + /// try db.schemaVersion() + /// } + /// ``` /// /// Related SQLite documentation: public func schemaVersion() throws -> Int32 { @@ -225,8 +242,19 @@ extension Database { /// Returns whether a table exists /// - /// When `schemaName` is not specified, known schemas are iterated in - /// SQLite resolution order and the first matching result is returned. + /// When `schemaName` is not specified, the result is true if any known + /// schema contains the table. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// if try db.tableExists("player") { ... } + /// if try db.tableExists("player", in: "main") { ... } + /// if try db.tableExists("player", in: "temp") { ... } + /// if try db.tableExists("player", in: "attached") { ... } + /// } + /// ``` /// /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or /// if the specified schema does not exist @@ -269,8 +297,19 @@ extension Database { /// Returns whether a view exists, in the main or temp schema, or in an /// attached database. /// - /// When `schemaName` is not specified, known schemas are iterated in - /// SQLite resolution order and the first matching result is returned. + /// When `schemaName` is not specified, the result is true if any known + /// schema contains the table. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// if try db.viewExists("player") { ... } + /// if try db.viewExists("player", in: "main") { ... } + /// if try db.viewExists("player", in: "temp") { ... } + /// if try db.viewExists("player", in: "attached") { ... } + /// } + /// ``` /// /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or /// if the specified schema does not exist @@ -287,8 +326,19 @@ extension Database { /// Returns whether a trigger exists, in the main or temp schema, or in an /// attached database. /// - /// When `schemaName` is not specified, known schemas are iterated in - /// SQLite resolution order and the first matching result is returned. + /// When `schemaName` is not specified, the result is true if any known + /// schema contains the table. + /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// if try db.triggerExists("on_player_update") { ... } + /// if try db.triggerExists("on_player_update", in: "main") { ... } + /// if try db.triggerExists("on_player_update", in: "temp") { ... } + /// if try db.triggerExists("on_player_update", in: "attached") { ... } + /// } + /// ``` /// /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or /// if the specified schema does not exist @@ -331,6 +381,15 @@ extension Database { /// table has no explicit primary key, the result is the hidden /// "rowid" column. /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let primaryKey = try db.primaryKey("player") + /// print(primaryKey.columns) + /// } + /// ``` + /// /// When `schemaName` is not specified, known schemas are iterated in /// SQLite resolution order and the first matching result is returned. /// @@ -350,6 +409,36 @@ extension Database { throw DatabaseError.noSuchTable(tableName) } + /// Returns the name of the single-column primary key. + /// + /// A fatal error is raised if the primary key has several columns, or + /// if `tableName` is the name of a database view. + func filteringPrimaryKeyColumn(_ tableName: String) throws -> String { + do { + let primaryKey = try primaryKey(tableName) + GRDBPrecondition( + primaryKey.columns.count == 1, + "Filtering by primary key requires a single-column primary key in the table '\(tableName)'") + return primaryKey.columns[0] + } catch let error as DatabaseError { + // Maybe the user tries to filter a view by primary key, + // as in . + // In this case, raise a fatalError because this is a + // programmer error which is very likely to be detected + // during development. + if case .SQLITE_ERROR = error.resultCode, + (try? viewExists(tableName)) == true + { + fatalError(""" + Filtering by primary key is not available on the database view '\(tableName)'. \ + Use `filter(Column("...") == value)` instead. + """) + } else { + throw error + } + } + } + /// Returns nil if table does not exist private func primaryKey(_ table: TableIdentifier) throws -> PrimaryKeyInfo? { SchedulingWatchdog.preconditionValidQueue(self) @@ -490,14 +579,26 @@ extension Database { /// The indexes on table named `tableName`. /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let indexes = db.indexes(in: "player") + /// for index in indexes { + /// print(index.columns) + /// } + /// } + /// ``` + /// /// Only indexes on columns are returned. Indexes on expressions are /// not returned. /// - /// SQLite does not define any index for INTEGER PRIMARY KEY columns: this - /// method does not return any index that represents the primary key. + /// SQLite does not define any index for INTEGER PRIMARY KEY columns: + /// this method does not return any index that represents the + /// primary key. /// - /// If you want to know if a set of columns uniquely identifies a row, because - /// the columns contain the primary key or a unique index, use + /// If you want to know if a set of columns uniquely identifies a row, + /// because the columns contain the primary key or a unique index, use /// ``table(_:hasUniqueKey:)``. /// /// When `schemaName` is not specified, known schemas are iterated in @@ -578,24 +679,25 @@ extension Database { /// For example: /// /// ```swift - /// // One table with one primary key (id), and a unique index (a, b): - /// // - /// // > CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c); - /// // > CREATE UNIQUE INDEX i ON t(a, b); - /// try db.table("t", hasUniqueKey: ["id"]) // true - /// try db.table("t", hasUniqueKey: ["a", "b"]) // true - /// try db.table("t", hasUniqueKey: ["b", "a"]) // true - /// try db.table("t", hasUniqueKey: ["c"]) // false - /// try db.table("t", hasUniqueKey: ["id", "a"]) // true - /// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true + /// try dbQueue.read { db in + /// // One table with one primary key (id) + /// // and a unique index (a, b): + /// // + /// // > CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c); + /// // > CREATE UNIQUE INDEX i ON t(a, b); + /// try db.table("t", hasUniqueKey: ["id"]) // true + /// try db.table("t", hasUniqueKey: ["a", "b"]) // true + /// try db.table("t", hasUniqueKey: ["b", "a"]) // true + /// try db.table("t", hasUniqueKey: ["c"]) // false + /// try db.table("t", hasUniqueKey: ["id", "a"]) // true + /// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true + /// } /// ``` - public func table( + public func table( _ tableName: String, - hasUniqueKey columns: Columns) - throws -> Bool - where Columns: Sequence, Columns.Element == String - { - try columnsForUniqueKey(Array(columns), in: tableName) != nil + hasUniqueKey columns: some Collection + ) throws -> Bool { + try columnsForUniqueKey(columns, in: tableName) != nil } /// Returns the foreign keys defined on table named `tableName`. @@ -603,6 +705,17 @@ extension Database { /// When `schemaName` is not specified, known schemas are iterated in /// SQLite resolution order and the first matching result is returned. /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let foreignKeys = try db.foreignKeys(in: "player") + /// for foreignKey in foreignKeys { + /// print(foreignKey.destinationTable) + /// } + /// } + /// ``` + /// /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if /// the specified schema does not exist, or if no such table or view /// with this name exists in the main or temp schema, or in an attached @@ -824,6 +937,17 @@ extension Database { /// When `schemaName` is not specified, known schemas are iterated in /// SQLite resolution order and the first matching result is returned. /// + /// For example: + /// + /// ```swift + /// try dbQueue.read { db in + /// let columns = try db.columns(in: "player") + /// for column in columns { + /// print(column.name) + /// } + /// } + /// ``` + /// /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if /// the specified schema does not exist,or if no such table or view /// with this name exists in the main or temp schema, or in an attached @@ -920,12 +1044,10 @@ extension Database { /// returns the columns of the unique key, ordered as the matching index (or /// primary key). The case of returned columns is not guaranteed to match /// the case of input columns. - func columnsForUniqueKey( - _ columns: Columns, - in tableName: String) - throws -> [String]? - where Columns: Sequence, Columns.Element == String - { + func columnsForUniqueKey( + _ columns: some Collection, + in tableName: String + ) throws -> [String]? { let lowercasedColumns = Set(columns.map { $0.lowercased() }) if lowercasedColumns.isEmpty { // Don't hit the database for trivial case diff --git a/GRDB/Core/Database+Statements.swift b/GRDB/Core/Database+Statements.swift index 061c5b364..f4d98fc14 100644 --- a/GRDB/Core/Database+Statements.swift +++ b/GRDB/Core/Database+Statements.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation extension Database { @@ -430,6 +439,7 @@ extension Database { // documentation of this method for more information). try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments) + // Cancelled database accesses must not execute. // Suspended databases must not execute statements that create the risk // of `0xdead10cc` exception (see the documentation of this method for // more information). @@ -482,6 +492,15 @@ extension Database { // and throws the user-provided cancelled commit error. try observationBroker?.statementDidFail(statement) + switch ResultCode(rawValue: resultCode) { + case .SQLITE_INTERRUPT, .SQLITE_ABORT: + // The only error that a user sees when a Task is cancelled + // is CancellationError. + try suspensionMutex.load().checkCancellation() + default: + break + } + // Throw statement failure throw DatabaseError( resultCode: resultCode, @@ -531,19 +550,7 @@ struct StatementCache { // > time and probably reused many times. // // This looks like a perfect match for cached statements. - // - // However SQLITE_PREPARE_PERSISTENT was only introduced in - // SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20 - #if GRDBCUSTOMSQLITE || GRDBCIPHER let statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT)) - #else - let statement: Statement - if #available(iOS 12, macOS 10.14, watchOS 5, *) { // SQLite 3.20+ - statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT)) - } else { - statement = try db.makeStatement(sql: sql) - } - #endif statements[sql] = statement return statement } diff --git a/GRDB/Core/Database.swift b/GRDB/Core/Database.swift index 6281109b3..92948c31c 100644 --- a/GRDB/Core/Database.swift +++ b/GRDB/Core/Database.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// A raw SQLite connection, suitable for the SQLite C API. @@ -112,9 +121,16 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_ /// - ``clearSchemaCache()`` /// - ``logError`` /// - ``releaseMemory()`` +/// - ``sqliteLibVersionNumber`` /// - ``trace(options:_:)`` +/// +/// ### Supporting Types +/// +/// - ``BusyCallback`` +/// - ``BusyMode`` /// - ``CheckpointMode`` /// - ``DatabaseBackupProgress`` +/// - ``LogErrorFunction`` /// - ``StorageClass`` /// - ``TraceEvent`` /// - ``TracingOptions`` @@ -124,8 +140,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // MARK: - SQLite C API - // TODO: make it non optional, since one can't get a `Database` instance - // after `close()`. /// The raw SQLite connection, suitable for the SQLite C API. /// /// The result is nil after the database has been successfully closed with @@ -136,8 +150,26 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// The error logging function. /// + /// SQLite can be configured to invoke a callback function containing + /// an error code and a terse error message whenever anomalies occur. + /// + /// This global error callback must be configured early in the lifetime + /// of your application: + /// + /// ```swift + /// Database.logError = { (resultCode, message) in + /// NSLog("%@", "SQLite error \(resultCode): \(message)") + /// } + /// ``` + /// + /// - warning: Database.logError must be set before any database + /// connection is opened. This includes the connections that your + /// application opens with GRDB, but also connections opened by + /// other tools, such as third-party libraries. Setting it after a + /// connection has been opened is an SQLite misuse, and has no effect. + /// /// Related SQLite documentation: - public static var logError: LogErrorFunction? = nil { + nonisolated(unsafe) public static var logError: LogErrorFunction? = nil { didSet { if logError != nil { _registerErrorLogCallback { (_, code, message) in @@ -271,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(_:)`. /// @@ -281,18 +328,41 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// `isRecordingSelectedRegion` is true. var selectedRegion = DatabaseRegion() - /// Support for `checkForAbortedTransaction()` - var isInsideTransactionBlock = false - - /// Support for `checkForSuspensionViolation(from:)` - @LockedBox var isSuspended = false - /// Support for `checkForSuspensionViolation(from:)` /// This cache is never cleared: we assume journal mode never changes. var journalModeCache: String? + // MARK: - Suspension + + struct Suspension { + /// If true, the database is suspended and should not acquire any + /// write lock in order to avoid the 0xDEAD10CC exception. + var isSuspended: Bool + + /// If true, the database access has been cancelled. + var isCancelled: Bool + + /// If true, the database throws an error when it is cancelled. + var interruptsWhenCancelled: Bool + + func checkCancellation() throws { + if isCancelled, interruptsWhenCancelled { + throw CancellationError() + } + } + } + + /// Support for `checkForSuspensionViolation(from:)` + let suspensionMutex = Mutex(Suspension( + isSuspended: false, + isCancelled: false, + interruptsWhenCancelled: true)) + // MARK: - Transaction Date + /// Support for `checkForAbortedTransaction()` + var isInsideTransactionBlock = false + enum AutocommitState { case off case on @@ -354,10 +424,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib private var trace: ((TraceEvent) -> Void)? /// The registered custom SQL functions. - private var functions = Set() + private var functions: [DatabaseFunction.ID: DatabaseFunction] = [:] /// The registered custom SQL collations. - private var collations = Set() + private var collations: [DatabaseCollation.ID: DatabaseCollation] = [:] /// Support for `beginReadOnly()` and `endReadOnly()`. private var readOnlyDepth = 0 @@ -604,7 +674,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib guard code == SQLITE_OK else { // So there remain some unfinalized prepared statement somewhere. if let log = Self.logError { - if code == SQLITE_BUSY { + if ResultCode(rawValue: code).primaryResultCode == .SQLITE_BUSY { // Let the user know about unfinalized statements that did // prevent the connection from closing properly. var stmt: SQLiteStatement? = sqlite3_next_stmt(sqliteConnection, nil) @@ -700,13 +770,13 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// let dbPool = try DatabasePool(path: ..., configuration: config) /// ``` public func add(function: DatabaseFunction) { - functions.update(with: function) + functions[function.id] = function function.install(in: self) } /// Removes a custom SQL function. public func remove(function: DatabaseFunction) { - functions.remove(function) + functions.removeValue(forKey: function.id) function.uninstall(in: self) } @@ -727,7 +797,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// let dbPool = try DatabasePool(path: ..., configuration: config) /// ``` public func add(collation: DatabaseCollation) { - collations.update(with: collation) + collations[collation.id] = collation let collationPointer = Unmanaged.passUnretained(collation).toOpaque() let code = sqlite3_create_collation_v2( sqliteConnection, @@ -746,7 +816,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Removes a collation. public func remove(collation: DatabaseCollation) { - collations.remove(collation) + collations.removeValue(forKey: collation.id) sqlite3_create_collation_v2( sqliteConnection, collation.name, @@ -1118,22 +1188,25 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// /// Suspension ends with `resume()`. func suspend() { - $isSuspended.update { isSuspended in - if isSuspended { - return + let needsInterrupt = suspensionMutex.withLock { suspension in + if suspension.isSuspended { + return false } - // Prevent future lock acquisition - isSuspended = true - - // Interrupt the database because this may trigger an - // SQLITE_INTERRUPT error which may itself abort a transaction and - // release a lock. See + suspension.isSuspended = true + return true + } + + if needsInterrupt { + // Interrupting the database can trigger an SQLITE_INTERRUPT + // error which may itself abort a transaction and + // release a database lock, which is our goal. + // See + // + // Maybe interrupt will not release any lock. To address this, + // we'll issue a rollback on next database access which requires + // a lock. See `checkForSuspensionViolation(from:).` interrupt() - - // Now what about the eventual remaining lock? We'll issue a - // rollback on next database access which requires a lock, in - // checkForSuspensionViolation(from:). } } @@ -1145,7 +1218,53 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// /// See suspend(). func resume() { - isSuspended = false + suspensionMutex.withLock { + $0.isSuspended = false + } + } + + /// Cancels the current database access. All statements but ROLLBACK + /// will throw `CancellationError`, until `uncancel()` is called. + /// + /// This method can be called from any thread. + func cancel() { + let needsInterrupt = suspensionMutex.withLock { suspension in + if suspension.isCancelled { + return false + } + + suspension.isCancelled = true + return suspension.interruptsWhenCancelled + } + + if needsInterrupt { + interrupt() + } + } + + /// Undo `cancel()`. + func uncancel() { + suspensionMutex.withLock { + $0.isCancelled = false + } + } + + /// Within the given closure, Task cancellation does not interrupt + /// database accesses. + func ignoringCancellation(_ value: () throws -> T) rethrows -> T { + let previous = suspensionMutex.withLock { + let previous = $0.interruptsWhenCancelled + $0.interruptsWhenCancelled = false + return previous + } + + defer { + suspensionMutex.withLock { + $0.interruptsWhenCancelled = previous + } + } + + return try value() } /// Support for `checkForSuspensionViolation(from:)` @@ -1169,15 +1288,57 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib return journalMode } - /// If the database is suspended, and executing the statement would lock the - /// database in a way that may trigger the [`0xdead10cc` exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report), - /// this method rollbacks the current transaction and throws `SQLITE_ABORT`. + /// Prevents a statement from running, if the database is suspended, or + /// if the current database access is cancelled by Task cancellation. /// - /// See `suspend()` and ``Configuration/observesSuspensionNotifications``. + /// Transaction rollbacks are always allowed. For other statements: + /// + /// - When database access is cancelled, this method + /// throws `CancellationError`. + /// + /// - When database is suspensed, and if the statement would lock the + /// database in a way that may trigger the 0xDEAD10CC exception, this + /// method rollbacks the current transaction and throws `SQLITE_ABORT`. + /// + /// See `cancel()`, `suspend()` and + /// ``Configuration/observesSuspensionNotifications``. func checkForSuspensionViolation(from statement: Statement) throws { - try $isSuspended.read { isSuspended in - guard isSuspended else { - return + // No reason for suspension should prevent rollbacks: + // + // - A rollback releases the write lock when the database + // is interrupted, when preventing 0xDEAD10CC. + // + // - A rollback properly closes a transaction that fails because + // it runs in a Task that was cancelled. + // + // Finally, a rollback must be run by GRDB, not by a direct call + // to `sqlite3_exec`, so that transaction observers are + // properly notified. + if statement.transactionEffect == .rollbackTransaction { + return + } + + // Suspension should not prevent adjusting the read-only mode. + // See . + if statement.isQueryOnlyPragma { + return + } + + // How should we interrupt the statement? + enum Interrupt { + case abort // Rollback and throw SQLITE_ABORT + case cancel // Throw CancellationError + } + + let interrupt: Interrupt? = try suspensionMutex.withLock { suspension in + // Check for cancellation first, so that the only error that + // a user sees when a Task is cancelled is CancellationError. + if suspension.isCancelled, suspension.interruptsWhenCancelled { + return .cancel + } + + guard suspension.isSuspended else { + return nil } if try journalMode() == "wal" && statement.isReadonly { @@ -1188,7 +1349,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // Those are not read-only: // - INSERT ... // - BEGIN IMMEDIATE TRANSACTION - return + return nil } if statement.releasesDatabaseLock { @@ -1197,15 +1358,24 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // - ROLLBACK // - ROLLBACK TRANSACTION TO SAVEPOINT // - RELEASE SAVEPOINT - return + return nil } + // Assume statement can acquire a write lock: abort. + return .abort + } + + switch interrupt { + case nil: + break + + case .cancel: + throw CancellationError() + + case .abort: // Attempt at releasing an eventual lock with ROLLBACk, // as explained in Database.suspend(). - // - // Use sqlite3_exec instead of `try? rollback()` in order to avoid - // an infinite loop in checkForSuspensionViolation(from:) - _ = sqlite3_exec(sqliteConnection, "ROLLBACK", nil, nil, nil) + try? rollback() throw DatabaseError( resultCode: .SQLITE_ABORT, @@ -1275,14 +1445,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Use ``inSavepoint(_:)`` instead. /// /// - parameters: - /// - kind: The transaction type (default nil). + /// - kind: The transaction type. /// - /// If nil, and the database connection is read-only, the transaction - /// kind is ``TransactionKind/deferred``. - /// - /// If nil, and the database connection is not read-only, the - /// transaction kind is the ``Configuration/defaultTransactionKind`` - /// of the ``configuration``. + /// If nil, the transaction kind is DEFERRED when the current + /// database access is read-only, and IMMEDIATE otherwise. /// - operations: A function that executes SQL statements and returns /// either ``TransactionCompletion/commit`` or ``TransactionCompletion/rollback``. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the @@ -1406,8 +1572,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib // By default, top level SQLite savepoints open a // deferred transaction. // - // But GRDB database configuration mandates a default transaction - // kind that we have to honor. + // But GRDB prefers immediate transactions for writes. // // Besides, starting some (?) SQLCipher/SQLite version, SQLite has a // bug. Returning 1 from `sqlite3_commit_hook` does not leave the @@ -1495,18 +1660,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Related SQLite documentation: /// /// - parameters: - /// - kind: The transaction type (default nil). + /// - kind: The transaction type. /// - /// If nil, and the database connection is read-only, the transaction - /// kind is ``TransactionKind/deferred``. - /// - /// If nil, and the database connection is not read-only, the - /// transaction kind is the ``Configuration/defaultTransactionKind`` - /// of the ``configuration``. + /// If nil, the transaction kind is DEFERRED when the current + /// database access is read-only, and IMMEDIATE otherwise. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func beginTransaction(_ kind: TransactionKind? = nil) throws { // SQLite throws an error for non-deferred transactions when read-only. - let kind = kind ?? (isReadOnly ? .deferred : configuration.defaultTransactionKind) + // We prefer immediate transactions for writes, so that write + // transactions can not overlap. This reduces the opportunity for + // SQLITE_BUSY, which is immediately thrown whenever a transaction + // is upgraded after an initial read and a concurrent processes + // has acquired the write lock beforehand. This SQLITE_BUSY error + // can not be avoided with a busy timeout. + // + // See . + let kind = kind ?? (isReadOnly ? .deferred : .immediate) try execute(sql: "BEGIN \(kind.rawValue) TRANSACTION") assert(sqlite3_get_autocommit(sqliteConnection) == 0) } @@ -1577,7 +1746,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib /// Frees as much memory as possible. public func releaseMemory() { SchedulingWatchdog.preconditionValidQueue(self) - sqlite3_db_release_memory(sqliteConnection) + if let sqliteConnection { + sqlite3_db_release_memory(sqliteConnection) + } schemaCache.clear() internalStatementCache.clear() publicStatementCache.clear() @@ -1816,8 +1987,8 @@ extension Database { // MARK: - Database-Related Types - /// See BusyMode and - public typealias BusyCallback = (_ numberOfTries: Int) -> Bool + /// See ``BusyMode`` and + public typealias BusyCallback = @Sendable (_ numberOfTries: Int) -> Bool /// When there are several connections to a database, a connection may try /// to access the database while it is locked by another connection. @@ -1845,7 +2016,7 @@ extension Database { /// - /// - /// - - public enum BusyMode { + public enum BusyMode: Sendable { /// The `SQLITE_BUSY` error is immediately returned to the connection /// that tries to access the locked database. case immediateError @@ -1923,7 +2094,6 @@ extension Database { /// The SQL for the column type (`"TEXT"`, `"BLOB"`, etc.) public let rawValue: String - // TODO: GRDB7 make it an failable initializer that returns nil when rawValue is empty (or blank). /// Creates an SQL column type. public init(rawValue: String) { self.rawValue = rawValue @@ -1940,6 +2110,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") @@ -2006,7 +2179,7 @@ extension Database { } /// An error log function that takes an error code and message. - public typealias LogErrorFunction = (_ resultCode: ResultCode, _ message: String) -> Void + public typealias LogErrorFunction = @Sendable (_ resultCode: ResultCode, _ message: String) -> Void /// An SQLite storage class. /// diff --git a/GRDB/Core/DatabaseCollation.swift b/GRDB/Core/DatabaseCollation.swift index 2f76223c5..6748874c8 100644 --- a/GRDB/Core/DatabaseCollation.swift +++ b/GRDB/Core/DatabaseCollation.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// `DatabaseCollation` is a custom string comparison function used by SQLite. @@ -20,10 +29,36 @@ import Foundation /// - ``localizedCompare`` /// - ``localizedStandardCompare`` /// - ``unicodeCompare`` -public final class DatabaseCollation { +public final class DatabaseCollation: Identifiable, Sendable { + /// The identifier of an SQLite collation. + /// + /// SQLite identifies collations by their name (case insensitive). + public struct ID: Hashable { + var name: String + + // Collation equality is based on the sqlite3_strnicmp SQLite function. + // (see https://www.sqlite.org/c3ref/create_collation.html). Computing + // a hash value that honors the Swift Hashable contract (value equality + // implies hash equality) is thus non trivial. But it's not that + // important, since this hashValue is only used when one adds + // or removes a collation from a database connection. + public func hash(into hasher: inout Hasher) { + hasher.combine(0) + } + + /// Two collations are equal if they share the same name (case insensitive) + public static func == (lhs: Self, rhs: Self) -> Bool { + // See + return sqlite3_stricmp(lhs.name, rhs.name) == 0 + } + } + + /// The identifier of the collation. + public var id: ID { ID(name: name) } + /// The name of the collation. public let name: String - let function: (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult + let function: @Sendable (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult /// Creates a collation. /// @@ -40,7 +75,7 @@ public final class DatabaseCollation { /// - parameters: /// - name: The collation name. /// - function: A function that compares two strings. - public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) { + public init(_ name: String, function: @escaping @Sendable (String, String) -> ComparisonResult) { self.name = name self.function = { (length1, buffer1, length2, buffer2) in // Buffers are not C strings: they do not end with \0. @@ -58,21 +93,3 @@ public final class DatabaseCollation { } } } - -extension DatabaseCollation: Hashable { - // Collation equality is based on the sqlite3_strnicmp SQLite function. - // (see https://www.sqlite.org/c3ref/create_collation.html). Computing - // a hash value that honors the Swift Hashable contract (value equality - // implies hash equality) is thus non trivial. But it's not that - // important, since this hashValue is only used when one adds - // or removes a collation from a database connection. - public func hash(into hasher: inout Hasher) { - hasher.combine(0) - } - - /// Two collations are equal if they share the same name (case insensitive) - public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool { - // See - return sqlite3_stricmp(lhs.name, rhs.name) == 0 - } -} diff --git a/GRDB/Core/DatabaseError.swift b/GRDB/Core/DatabaseError.swift index 53eb009b3..bf808dbaa 100644 --- a/GRDB/Core/DatabaseError.swift +++ b/GRDB/Core/DatabaseError.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// An SQLite result code. @@ -406,6 +415,10 @@ extension DatabaseError { static func connectionIsClosed() -> Self { DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed") } + + static func snapshotIsLost() -> Self { + DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.") + } } // Support for `catch DatabaseError.SQLITE_XXX` diff --git a/GRDB/Core/DatabaseFunction.swift b/GRDB/Core/DatabaseFunction.swift index 81fe82574..11387222c 100644 --- a/GRDB/Core/DatabaseFunction.swift +++ b/GRDB/Core/DatabaseFunction.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + /// A custom SQL function or aggregate. /// /// ## Topics @@ -20,16 +29,20 @@ /// - ``localizedUppercase`` /// - ``lowercase`` /// - ``uppercase`` -public final class DatabaseFunction: Hashable { - // SQLite identifies functions by (name + argument count) - private struct Identity: Hashable { +public final class DatabaseFunction: Identifiable, Sendable { + /// The identifier of an SQLite function. + /// + /// SQLite identifies functions by their name and argument count. + public struct ID: Hashable, Sendable { let name: String let nArg: CInt // -1 for variadic functions } - /// The name of the SQL function - public var name: String { identity.name } - private let identity: Identity + /// The name of the SQL function. + public var name: String { id.name } + + /// The identifier of the SQL function. + public let id: ID let isPure: Bool private let kind: Kind private var eTextRep: CInt { (SQLITE_UTF8 | (isPure ? SQLITE_DETERMINISTIC : 0)) } @@ -73,11 +86,11 @@ public final class DatabaseFunction: Hashable { _ name: String, argumentCount: Int? = nil, pure: Bool = false, - function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?) + function: @escaping @Sendable ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?) { - self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1) + self.id = ID(name: name, nArg: argumentCount.map(CInt.init) ?? -1) self.isPure = pure - self.kind = .function{ (argc, argv) in + self.kind = .function { (argc, argv) in let arguments = (0.. - private enum Kind { + private enum Kind: Sendable { /// A regular function: SELECT f(1) - case function((CInt, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)?) + case function(@Sendable (CInt, UnsafeMutablePointer?) throws -> (any DatabaseValueConvertible)?) /// An aggregate: SELECT f(foo) FROM bar GROUP BY baz - case aggregate(() -> any DatabaseAggregate) + case aggregate(@Sendable () -> any DatabaseAggregate) /// Feeds the `pApp` parameter of sqlite3_create_function_v2 /// @@ -415,17 +435,6 @@ public final class DatabaseFunction: Hashable { } } -extension DatabaseFunction { - public func hash(into hasher: inout Hasher) { - hasher.combine(identity) - } - - /// Two functions are equal if they share the same name and arity. - public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool { - lhs.identity == rhs.identity - } -} - /// The protocol for custom SQLite aggregates. /// /// For example: diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 7dd0525fc..ce1bae833 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -11,7 +11,7 @@ public final class DatabasePool { /// It is constant, until close() sets it to nil. private var readerPool: Pool? - @LockedBox var databaseSnapshotCount = 0 + let databaseSnapshotCountMutex = Mutex(0) /// If Database Suspension is enabled, this array contains the necessary `NotificationCenter` observers. private var suspensionObservers: [NSObjectProtocol] = [] @@ -62,17 +62,15 @@ public final class DatabasePool { // an opened transaction. readerConfiguration.allowsUnsafeTransactions = false - var readerCount = 0 readerPool = Pool( maximumCount: configuration.maximumReaderCount, qos: configuration.readQoS, - makeElement: { - readerCount += 1 // protected by Pool (TODO: document this protection behavior) + makeElement: { [readerConfiguration] index in return try SerializedDatabase( path: path, configuration: readerConfiguration, defaultLabel: "GRDB.DatabasePool", - purpose: "reader.\(readerCount)") + purpose: "reader.\(index)") }) // Set up journal mode unless readonly @@ -118,10 +116,6 @@ public final class DatabasePool { configuration.readonly = true - // Readers use deferred transactions by default. - // Other transaction kinds are forbidden by SQLite in read-only connections. - configuration.defaultTransactionKind = .deferred - // // > But there are some obscure cases where a query against a WAL-mode // > database can return SQLITE_BUSY, so applications should be prepared @@ -148,7 +142,7 @@ public final class DatabasePool { } } -// @unchecked because of databaseSnapshotCount, readerPool and suspensionObservers +// @unchecked because of readerPool and suspensionObservers extension DatabasePool: @unchecked Sendable { } extension DatabasePool { @@ -357,7 +351,47 @@ extension DatabasePool: DatabaseReader { } } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func read( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.") + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + readerPool.asyncGet { result in + do { + let (reader, releaseReader) = try result.get() + // Second async jump because that's how `Pool.async` has to be used. + reader.async { db in + defer { + try? db.commit() // Ignore commit error + releaseReader(.reuse) + } + do { + let result = try dbAccess.inDatabase(db) { + // The block isolation comes from the DEFERRED transaction. + try db.beginTransaction(.deferred) + try db.clearSchemaCacheIfNeeded() + return try value(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } catch { + continuation.resume(throwing: error) + } + } + } + } + + public func asyncRead( + _ value: @escaping @Sendable (Result) -> Void + ) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return @@ -401,7 +435,43 @@ extension DatabasePool: DatabaseReader { } } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func unsafeRead( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + readerPool.asyncGet { result in + do { + let (reader, releaseReader) = try result.get() + // Second async jump because that's how `Pool.async` has to be used. + reader.async { db in + defer { + releaseReader(.reuse) + } + do { + let result = try dbAccess.inDatabase(db) { + try db.clearSchemaCacheIfNeeded() + return try value(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } catch { + continuation.resume(throwing: error) + } + } + } + } + + public func asyncUnsafeRead( + _ value: @escaping @Sendable (Result) -> Void + ) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return @@ -446,25 +516,9 @@ extension DatabasePool: DatabaseReader { } } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { - // The semaphore that blocks until futureResult is defined: - let futureSemaphore = DispatchSemaphore(value: 0) - var futureResult: Result? = nil - - asyncConcurrentRead { dbResult in - // Fetch and release the future - futureResult = dbResult.flatMap { db in Result { try value(db) } } - futureSemaphore.signal() - } - - return DatabaseFuture { - // Block the future until results are fetched - _ = futureSemaphore.wait(timeout: .distantFuture) - return try futureResult!.get() - } - } - - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + public func spawnConcurrentRead( + _ value: @escaping @Sendable (Result) -> Void + ) { asyncConcurrentRead(value) } @@ -505,7 +559,9 @@ extension DatabasePool: DatabaseReader { /// ``` /// /// - parameter value: A function that accesses the database. - public func asyncConcurrentRead(_ value: @escaping (Result) -> Void) { + public func asyncConcurrentRead( + _ value: @escaping @Sendable (Result) -> Void + ) { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -644,8 +700,7 @@ extension DatabasePool: DatabaseReader { // MARK: - WAL Snapshot Transactions - // swiftlint:disable:next line_length -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) /// Returns a long-lived WAL snapshot transaction on a reader connection. func walSnapshotTransaction() throws -> WALSnapshotTransaction { guard let readerPool else { @@ -665,7 +720,9 @@ extension DatabasePool: DatabaseReader { /// /// - important: The `completion` argument is executed in a serial /// dispatch queue, so make sure you use the transaction asynchronously. - func asyncWALSnapshotTransaction(_ completion: @escaping (Result) -> Void) { + func asyncWALSnapshotTransaction( + _ completion: @escaping @Sendable (Result) -> Void + ) { guard let readerPool else { completion(.failure(DatabaseError.connectionIsClosed())) return @@ -691,9 +748,8 @@ extension DatabasePool: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) - -> AnyDatabaseCancellable - { + onChange: @escaping @Sendable (Reducer.Value) -> Void + ) -> AnyDatabaseCancellable { if configuration.readonly { // The easy case: the database does not change return _addReadOnly( @@ -722,9 +778,8 @@ extension DatabasePool: DatabaseReader { private func _addConcurrent( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) - -> AnyDatabaseCancellable - { + onChange: @escaping @Sendable (Reducer.Value) -> Void + ) -> AnyDatabaseCancellable { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead") let observer = ValueConcurrentObserver( @@ -746,6 +801,12 @@ extension DatabasePool: DatabaseWriter { try writer.sync(updates) } + public func writeWithoutTransaction( + _ updates: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await writer.execute(updates) + } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { guard let readerPool else { @@ -756,7 +817,29 @@ extension DatabasePool: DatabaseWriter { } } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + public func barrierWriteWithoutTransaction( + _ updates: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + asyncBarrierWriteWithoutTransaction { dbResult in + do { + try dbAccess.checkCancellation() + let db = try dbResult.get() + let result = try dbAccess.inDatabase(db) { + try updates(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } + } + + public func asyncBarrierWriteWithoutTransaction( + _ updates: @escaping @Sendable (Result) -> Void + ) { guard let readerPool else { updates(.failure(DatabaseError.connectionIsClosed())) return @@ -788,9 +871,10 @@ extension DatabasePool: DatabaseWriter { /// /// - precondition: This method is not reentrant. /// - parameters: - /// - kind: The transaction type (default nil). If nil, the transaction - /// type is the ``Configuration/defaultTransactionKind`` of the - /// the ``configuration``. + /// - kind: The transaction type. + /// + /// If nil, the transaction kind is DEFERRED when the database + /// connection is read-only, and IMMEDIATE otherwise. /// - updates: A function that updates the database. /// - throws: The error thrown by `updates`, or by the wrapping transaction. public func writeInTransaction( @@ -809,7 +893,9 @@ extension DatabasePool: DatabaseWriter { try writer.reentrantSync(updates) } - public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + public func asyncWriteWithoutTransaction( + _ updates: @escaping @Sendable (Database) -> Void + ) { writer.async(updates) } } @@ -867,11 +953,10 @@ extension DatabasePool { path: path, configuration: DatabasePool.readerConfiguration(writer.configuration), defaultLabel: "GRDB.DatabasePool", - purpose: "snapshot.\($databaseSnapshotCount.increment())") + purpose: "snapshot.\(databaseSnapshotCountMutex.increment())") } - // swiftlint:disable:next line_length -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) /// Creates a database snapshot that allows concurrent accesses to an /// unchanging database content, as it exists at the moment the snapshot /// is created. diff --git a/GRDB/Core/DatabasePublishers.swift b/GRDB/Core/DatabasePublishers.swift index 8f8054953..c7e7a603f 100644 --- a/GRDB/Core/DatabasePublishers.swift +++ b/GRDB/Core/DatabasePublishers.swift @@ -1,5 +1,4 @@ #if canImport(Combine) /// A namespace for database Combine publishers. -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public enum DatabasePublishers { } #endif diff --git a/GRDB/Core/DatabaseQueue.swift b/GRDB/Core/DatabaseQueue.swift index ae763f694..37b62fde5 100644 --- a/GRDB/Core/DatabaseQueue.swift +++ b/GRDB/Core/DatabaseQueue.swift @@ -233,7 +233,19 @@ extension DatabaseQueue: DatabaseReader { } } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func read( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await writer.execute { db in + try db.isolated(readOnly: true) { + try value(db) + } + } + } + + public func asyncRead( + _ value: @escaping @Sendable (Result) -> Void + ) { writer.async { db in defer { // Ignore error because we can not notify it. @@ -254,11 +266,20 @@ extension DatabaseQueue: DatabaseReader { } } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func unsafeRead(_ value: (Database) throws -> T) rethrows -> T { try writer.sync(value) } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func unsafeRead( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await writer.execute(value) + } + + public func asyncUnsafeRead( + _ value: @escaping @Sendable (Result) -> Void + ) { writer.async { value(.success($0)) } } @@ -266,20 +287,9 @@ extension DatabaseQueue: DatabaseReader { try writer.reentrantSync(value) } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { - // DatabaseQueue can't perform parallel reads. - // Perform a blocking read instead. - return DatabaseFuture(Result { - // Check that we're on the writer queue, as documented - try writer.execute { db in - try db.isolated(readOnly: true) { - try value(db) - } - } - }) - } - - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + public func spawnConcurrentRead( + _ value: @escaping @Sendable (Result) -> Void + ) { // Check that we're on the writer queue... writer.execute { db in // ... and that no transaction is opened. @@ -309,9 +319,8 @@ extension DatabaseQueue: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) - -> AnyDatabaseCancellable - { + onChange: @escaping @Sendable (Reducer.Value) -> Void + ) -> AnyDatabaseCancellable { if configuration.readonly { // The easy case: the database does not change return _addReadOnly( @@ -352,9 +361,10 @@ extension DatabaseQueue: DatabaseWriter { /// ``` /// /// - parameters: - /// - kind: The transaction type (default nil). If nil, the transaction - /// type is the ``Configuration/defaultTransactionKind`` of the - /// the ``configuration``. + /// - kind: The transaction type. + /// + /// If nil, the transaction kind is DEFERRED when the database + /// connection is read-only, and IMMEDIATE otherwise. /// - updates: A function that updates the database. /// - throws: The error thrown by `updates`, or by the wrapping transaction. public func inTransaction( @@ -374,12 +384,26 @@ extension DatabaseQueue: DatabaseWriter { try writer.sync(updates) } + public func writeWithoutTransaction( + _ updates: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await writer.execute(updates) + } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { try writer.sync(updates) } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + public func barrierWriteWithoutTransaction( + _ updates: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await writer.execute(updates) + } + + public func asyncBarrierWriteWithoutTransaction( + _ updates: @escaping @Sendable (Result) -> Void + ) { writer.async { updates(.success($0)) } } @@ -425,7 +449,9 @@ extension DatabaseQueue: DatabaseWriter { try writer.reentrantSync(updates) } - public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + public func asyncWriteWithoutTransaction( + _ updates: @escaping @Sendable (Database) -> Void + ) { writer.async(updates) } } diff --git a/GRDB/Core/DatabaseReader.swift b/GRDB/Core/DatabaseReader.swift index 5fac0df44..2c9d1cfdd 100644 --- a/GRDB/Core/DatabaseReader.swift +++ b/GRDB/Core/DatabaseReader.swift @@ -22,14 +22,14 @@ import Dispatch /// ### Reading from the Database /// /// - ``read(_:)-3806d`` -/// - ``read(_:)-4w6gy`` +/// - ``read(_:)-4d1da`` /// - ``readPublisher(receiveOn:value:)`` /// - ``asyncRead(_:)`` /// /// ### Unsafe Methods /// /// - ``unsafeRead(_:)-5i7tf`` -/// - ``unsafeRead(_:)-11mk0`` +/// - ``unsafeRead(_:)-5gsav`` /// - ``unsafeReentrantRead(_:)`` /// - ``asyncUnsafeRead(_:)`` /// @@ -188,6 +188,36 @@ public protocol DatabaseReader: AnyObject, Sendable { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func read(_ value: (Database) throws -> T) throws -> T + /// Executes read-only database operations, and returns their result after + /// they have finished executing. + /// + /// For example: + /// + /// ```swift + /// let count = try await reader.read { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations are isolated in a transaction: they do not see + /// changes performed by eventual concurrent writes (even writes performed + /// by other processes). + /// + /// The database connection is read-only: attempts to write throw a + /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// - parameter value: A closure which accesses the database. + /// - throws: Any ``DatabaseError`` that happens while establishing the + /// database access, or the error thrown by `value`, or + /// `CancellationError` if the task is cancelled. + func read( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T + /// Schedules read-only database operations for execution, and /// returns immediately. /// @@ -214,7 +244,9 @@ public protocol DatabaseReader: AnyObject, Sendable { /// - parameter value: A closure which accesses the database. Its argument /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. - func asyncRead(_ value: @escaping (Result) -> Void) + func asyncRead( + _ value: @escaping @Sendable (Result) -> Void + ) /// Executes database operations, and returns their result after they have /// finished executing. @@ -254,6 +286,42 @@ public protocol DatabaseReader: AnyObject, Sendable { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func unsafeRead(_ value: (Database) throws -> T) throws -> T + /// Executes database operations, and returns their result after they have + /// finished executing. + /// + /// This method is "unsafe" because the database reader does nothing more + /// than providing a database connection. When you use this method, you + /// become responsible for the thread-safety of your application, and + /// responsible for database accesses performed by other processes. See + /// for + /// more information. + /// + /// For example: + /// + /// ```swift + /// let count = try await reader.unsafeRead { db in + /// try Player.fetchCount(db) + /// } + /// ``` + /// + /// The ``Database`` argument to `value` is valid only during the execution + /// of the closure. Do not store or return the database connection for + /// later use. + /// + /// - warning: Database operations may not be wrapped in a transaction. They + /// may see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `value` + /// closure may not return the same value. + /// - warning: Attempts to write in the database may succeed. + /// + /// - parameter value: A closure which accesses the database. + /// - throws: Any ``DatabaseError`` that happens while establishing the + /// database access, or the error thrown by `value`, or + /// `CancellationError` if the task is cancelled. + func unsafeRead( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T + /// Schedules database operations for execution, and returns immediately. /// /// This method is "unsafe" because the database reader does nothing more @@ -285,7 +353,9 @@ public protocol DatabaseReader: AnyObject, Sendable { /// - parameter value: A closure which accesses the database. Its argument /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. - func asyncUnsafeRead(_ value: @escaping (Result) -> Void) + func asyncUnsafeRead( + _ value: @escaping @Sendable (Result) -> Void + ) /// Executes database operations, and returns their result after they have /// finished executing. @@ -343,8 +413,8 @@ public protocol DatabaseReader: AnyObject, Sendable { func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) - -> AnyDatabaseCancellable + onChange: @escaping @Sendable (Reducer.Value) -> Void + ) -> AnyDatabaseCancellable } extension DatabaseReader { @@ -398,7 +468,7 @@ extension DatabaseReader { /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the /// error thrown by `progress`. public func backup( - to writer: some DatabaseWriter, + to writer: any DatabaseWriter, pagesPerStep: CInt = -1, progress: ((DatabaseBackupProgress) throws -> Void)? = nil) throws @@ -428,96 +498,6 @@ extension DatabaseReader { } } -extension DatabaseReader { - // MARK: - Asynchronous Database Access - - /// Executes read-only database operations, and returns their result after - /// they have finished executing. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// For example: - /// - /// ```swift - /// let count = try await reader.read { db in - /// try Player.fetchCount(db) - /// } - /// ``` - /// - /// Database operations are isolated in a transaction: they do not see - /// changes performed by eventual concurrent writes (even writes performed - /// by other processes). - /// - /// The database connection is read-only: attempts to write throw a - /// ``DatabaseError`` with resultCode `SQLITE_READONLY`. - /// - /// The ``Database`` argument to `value` is valid only during the execution - /// of the closure. Do not store or return the database connection for - /// later use. - /// - /// - parameter value: A closure which accesses the database. - /// - throws: The error thrown by `value`, or any ``DatabaseError`` that - /// would happen while establishing the database access. - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func read(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in - asyncRead { result in - do { - try continuation.resume(returning: value(result.get())) - } catch { - continuation.resume(throwing: error) - } - } - } - } - - /// Executes database operations, and returns their result after they have - /// finished executing. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// This method is "unsafe" because the database reader does nothing more - /// than providing a database connection. When you use this method, you - /// become responsible for the thread-safety of your application, and - /// responsible for database accesses performed by other processes. See - /// for - /// more information. - /// - /// For example: - /// - /// ```swift - /// let count = try await reader.unsafeRead { db in - /// try Player.fetchCount(db) - /// } - /// ``` - /// - /// The ``Database`` argument to `value` is valid only during the execution - /// of the closure. Do not store or return the database connection for - /// later use. - /// - /// - warning: Database operations may not be wrapped in a transaction. They - /// may see changes performed by concurrent writes or writes performed by - /// other processes: two identical requests performed by the `value` - /// closure may not return the same value. - /// - warning: Attempts to write in the database may succeed. - /// - /// - parameter value: A closure which accesses the database. - /// - throws: The error thrown by `value`, or any ``DatabaseError`` that - /// would happen while establishing the database access. - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func unsafeRead(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in - asyncUnsafeRead { result in - do { - try continuation.resume(returning: value(result.get())) - } catch { - continuation.resume(throwing: error) - } - } - } - } -} - #if canImport(Combine) extension DatabaseReader { // MARK: - Publishing Database Values @@ -549,17 +529,13 @@ extension DatabaseReader { /// /// - parameter scheduler: A Combine Scheduler. /// - parameter value: A closure which accesses the database. - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func readPublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - value: @escaping (Database) throws -> Output) - -> DatabasePublishers.Read - { - Deferred { - Future { fulfill in - self.asyncRead { dbResult in - fulfill(dbResult.flatMap { db in Result { try value(db) } }) - } + value: @escaping @Sendable (Database) throws -> Output + ) -> DatabasePublishers.Read { + OnDemandFuture { fulfill in + self.asyncRead { dbResult in + fulfill(dbResult.flatMap { db in Result { try value(db) } }) } } .receiveValues(on: scheduler) @@ -567,7 +543,6 @@ extension DatabaseReader { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension DatabasePublishers { /// A publisher that reads from the database. /// @@ -586,7 +561,6 @@ extension DatabasePublishers { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Publisher where Failure == Error { fileprivate func eraseToReadPublisher() -> DatabasePublishers.Read { .init(upstream: eraseToAnyPublisher()) @@ -602,9 +576,8 @@ extension DatabaseReader { func _addReadOnly( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) - -> AnyDatabaseCancellable - { + onChange: @escaping @Sendable (Reducer.Value) -> Void + ) -> AnyDatabaseCancellable { if scheduler.immediateInitialValue() { do { // Perform a reentrant read, in case the observation would be @@ -620,16 +593,16 @@ extension DatabaseReader { } return AnyDatabaseCancellable(cancel: { /* nothing to cancel */ }) } else { - var isCancelled = false + let cancellable = AnyDatabaseCancellable() asyncRead { dbResult in - guard !isCancelled else { return } + if cancellable.isCancelled { return } let result = dbResult.flatMap { db in Result { try observation.fetchInitialValue(db) } } scheduler.schedule { - guard !isCancelled else { return } + if cancellable.isCancelled { return } do { try onChange(result.get()) } catch { @@ -637,7 +610,7 @@ extension DatabaseReader { } } } - return AnyDatabaseCancellable(cancel: { isCancelled = true }) + return cancellable } } } @@ -651,7 +624,7 @@ public final class AnyDatabaseReader { /// Creates a new database reader that wraps and forwards operations /// to `base`. - public init(_ base: some DatabaseReader) { + public init(_ base: any DatabaseReader) { self.base = base } } @@ -678,7 +651,15 @@ extension AnyDatabaseReader: DatabaseReader { try base.read(value) } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func read( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await base.read(value) + } + + public func asyncRead( + _ value: @escaping @Sendable (Result) -> Void + ) { base.asyncRead(value) } @@ -687,7 +668,15 @@ extension AnyDatabaseReader: DatabaseReader { try base.unsafeRead(value) } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func unsafeRead( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await base.unsafeRead(value) + } + + public func asyncUnsafeRead( + _ value: @escaping @Sendable (Result) -> Void + ) { base.asyncUnsafeRead(value) } @@ -698,9 +687,8 @@ extension AnyDatabaseReader: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) - -> AnyDatabaseCancellable - { + onChange: @escaping @Sendable (Reducer.Value) -> Void + ) -> AnyDatabaseCancellable { base._add( observation: observation, scheduling: scheduler, @@ -753,12 +741,15 @@ extension DatabaseSnapshotReader { } // There is no such thing as an unsafe access to a snapshot. + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func unsafeRead(_ value: (Database) throws -> T) throws -> T { try read(value) } // There is no such thing as an unsafe access to a snapshot. - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func asyncUnsafeRead( + _ value: @escaping @Sendable (Result) -> Void + ) { asyncRead(value) } } diff --git a/GRDB/Core/DatabaseRegion.swift b/GRDB/Core/DatabaseRegion.swift index fddeb77d3..271b53f60 100644 --- a/GRDB/Core/DatabaseRegion.swift +++ b/GRDB/Core/DatabaseRegion.swift @@ -416,7 +416,7 @@ private struct TableRegion: Equatable { /// ### Supporting Types /// /// - ``AnyDatabaseRegionConvertible`` -public protocol DatabaseRegionConvertible { +public protocol DatabaseRegionConvertible: Sendable { /// Returns a database region. /// /// - parameter db: A database connection. @@ -437,14 +437,14 @@ extension DatabaseRegion: DatabaseRegionConvertible { /// A type-erased DatabaseRegionConvertible public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible { - let _region: (Database) throws -> DatabaseRegion + let _region: @Sendable (Database) throws -> DatabaseRegion - public init(_ region: @escaping (Database) throws -> DatabaseRegion) { + public init(_ region: @escaping @Sendable (Database) throws -> DatabaseRegion) { _region = region } public init(_ region: some DatabaseRegionConvertible) { - _region = region.databaseRegion + _region = { try region.databaseRegion($0) } } public func databaseRegion(_ db: Database) throws -> DatabaseRegion { @@ -461,7 +461,7 @@ extension DatabaseRegion { } } - static func union(_ regions: [any DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion { + static func union(_ regions: [any DatabaseRegionConvertible]) -> @Sendable (Database) throws -> DatabaseRegion { return { db in try regions.reduce(into: DatabaseRegion()) { union, region in try union.formUnion(region.databaseRegion(db)) diff --git a/GRDB/Core/DatabaseRegionObservation.swift b/GRDB/Core/DatabaseRegionObservation.swift index 4f1e1473c..ec6319721 100644 --- a/GRDB/Core/DatabaseRegionObservation.swift +++ b/GRDB/Core/DatabaseRegionObservation.swift @@ -3,10 +3,10 @@ import Combine #endif import Foundation -public struct DatabaseRegionObservation { +public struct DatabaseRegionObservation: Sendable { /// A closure that is evaluated when the observation starts, and returns /// the observed database region. - var observedRegion: (Database) throws -> DatabaseRegion + var observedRegion: @Sendable (Database) throws -> DatabaseRegion } extension DatabaseRegionObservation { @@ -43,10 +43,10 @@ extension DatabaseRegionObservation { extension DatabaseRegionObservation { /// The state of a started DatabaseRegionObservation - private enum ObservationState { + private enum ObservationState: Sendable { case cancelled case pending - case started(DatabaseRegionObserver) + case started(StrongReference) } /// Starts observing the database. @@ -83,22 +83,23 @@ 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 public func start( - in writer: some DatabaseWriter, - onError: @escaping (Error) -> Void, - onChange: @escaping (Database) -> Void) + in writer: any DatabaseWriter, + onError: @escaping @Sendable (Error) -> Void, + onChange: @escaping @Sendable (Database) -> Void) -> AnyDatabaseCancellable { - @LockedBox var state = ObservationState.pending + let stateMutex = Mutex(ObservationState.pending) // Use unsafeReentrantWrite so that observation can start from any // dispatch queue. writer.unsafeReentrantWrite { db in do { let region = try observedRegion(db).observableRegion(db) - $state.update { + stateMutex.withLock { state in let observer = DatabaseRegionObserver(region: region, onChange: { - if case .cancelled = state { + if case .cancelled = stateMutex.load() { return } onChange($0) @@ -111,7 +112,7 @@ extension DatabaseRegionObservation { // the observer. db.add(transactionObserver: observer, extent: .observerLifetime) - $0 = .started(observer) + state = .started(StrongReference(observer)) } } catch { onError(error) @@ -122,13 +123,12 @@ extension DatabaseRegionObservation { // Deallocates the transaction observer. This makes sure that the // `onChange` callback will never be called again, because the // observation was started with the `.observerLifetime` extent. - state = .cancelled + stateMutex.store(.cancelled) } } } #if canImport(Combine) -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension DatabaseRegionObservation { // MARK: - Publishing Impactful Transactions @@ -140,8 +140,7 @@ extension DatabaseRegionObservation { /// /// Do not reschedule the publisher with `receive(on:options:)` or any /// `Publisher` method that schedules publisher elements. - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion { + public func publisher(in writer: any DatabaseWriter) -> DatabasePublishers.DatabaseRegion { DatabasePublishers.DatabaseRegion(self, in: writer) } } @@ -149,10 +148,10 @@ extension DatabaseRegionObservation { private class DatabaseRegionObserver: TransactionObserver { let region: DatabaseRegion - let onChange: (Database) -> Void + let onChange: @Sendable (Database) -> Void var isChanged = false - init(region: DatabaseRegion, onChange: @escaping (Database) -> Void) { + init(region: DatabaseRegion, onChange: @escaping @Sendable (Database) -> Void) { self.region = region self.onChange = onChange } @@ -186,7 +185,6 @@ private class DatabaseRegionObserver: TransactionObserver { } #if canImport(Combine) -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension DatabasePublishers { /// A publisher that tracks transactions that modify a database region. /// @@ -198,7 +196,7 @@ extension DatabasePublishers { let writer: any DatabaseWriter let observation: DatabaseRegionObservation - init(_ observation: DatabaseRegionObservation, in writer: some DatabaseWriter) { + init(_ observation: DatabaseRegionObservation, in writer: any DatabaseWriter) { self.writer = writer self.observation = observation } @@ -212,9 +210,14 @@ extension DatabasePublishers { } } - private class DatabaseRegionSubscription: Subscription - where Downstream.Failure == Error, Downstream.Input == Database + private class DatabaseRegionSubscription: + Subscription, @unchecked Sendable + where Downstream: Subscriber, + Downstream.Failure == Error, + Downstream.Input == Database { + // @unchecked Sendable because `cancellable` and `state` are + // protected by `lock`. private struct WaitingForDemand { let downstream: Downstream let writer: any DatabaseWriter @@ -245,7 +248,7 @@ extension DatabasePublishers { private var lock = NSRecursiveLock() // Allow re-entrancy init( - writer: some DatabaseWriter, + writer: any DatabaseWriter, observation: DatabaseRegionObservation, downstream: Downstream) { diff --git a/GRDB/Core/DatabaseSnapshot.swift b/GRDB/Core/DatabaseSnapshot.swift index 1381c1871..7609a3433 100644 --- a/GRDB/Core/DatabaseSnapshot.swift +++ b/GRDB/Core/DatabaseSnapshot.swift @@ -126,10 +126,6 @@ public final class DatabaseSnapshot { // DatabaseSnapshot is read-only. configuration.readonly = true - // DatabaseSnapshot uses deferred transactions by default. - // Other transaction kinds are forbidden by SQLite in read-only connections. - configuration.defaultTransactionKind = .deferred - // DatabaseSnapshot keeps a long-lived transaction. configuration.allowsUnsafeTransactions = true @@ -150,19 +146,41 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { // MARK: - Reading from Database + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func read(_ block: (Database) throws -> T) rethrows -> T { try reader.sync(block) } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func read( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await reader.execute(value) + } + + public func asyncRead( + _ value: @escaping @Sendable (Result) -> Void + ) { reader.async { value(.success($0)) } } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func unsafeRead(_ value: (Database) throws -> T) rethrows -> T { try reader.sync(value) } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + // There is no such thing as an unsafe access to a snapshot. + // We can't provide this as a default implementation in + // `DatabaseSnapshotReader`, because of + // . + public func unsafeRead( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await read(value) + } + + public func asyncUnsafeRead( + _ value: @escaping @Sendable (Result) -> Void + ) { reader.async { value(.success($0)) } } @@ -175,9 +193,8 @@ extension DatabaseSnapshot: DatabaseSnapshotReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) - -> AnyDatabaseCancellable - { + onChange: @escaping @Sendable (Reducer.Value) -> Void + ) -> AnyDatabaseCancellable { _addReadOnly( observation: observation, scheduling: scheduler, diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index c32b0b1a2..20398c556 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -1,5 +1,13 @@ -// swiftlint:disable:next line_length -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + /// A database connection that allows concurrent accesses to an unchanging /// database content, as it existed at the moment the snapshot was created. /// @@ -122,6 +130,7 @@ public final class DatabaseSnapshotPool { /// `db` is used. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public init(_ db: Database, configuration: Configuration? = nil) throws { + let path = db.path var configuration = Self.configure(configuration ?? db.configuration) // Acquire and hold WAL snapshot @@ -130,7 +139,7 @@ public final class DatabaseSnapshotPool { } var holderConfig = Configuration() holderConfig.allowsUnsafeTransactions = true - snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig) + snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig) try snapshotHolder.inDatabase { db in try db.beginTransaction(.deferred) try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1") @@ -150,20 +159,18 @@ public final class DatabaseSnapshotPool { } self.configuration = configuration - self.path = db.path + self.path = path self.walSnapshot = walSnapshot - var readerCount = 0 readerPool = Pool( maximumCount: configuration.maximumReaderCount, qos: configuration.readQoS, - makeElement: { - readerCount += 1 // protected by Pool (TODO: document this protection behavior) + makeElement: { [configuration] index in return try SerializedDatabase( - path: db.path, + path: path, configuration: configuration, defaultLabel: "GRDB.DatabaseSnapshotPool", - purpose: "snapshot.\(readerCount)") + purpose: "snapshot.\(index)") }) } @@ -211,17 +218,15 @@ public final class DatabaseSnapshotPool { self.path = path self.walSnapshot = walSnapshot - var readerCount = 0 readerPool = Pool( maximumCount: configuration.maximumReaderCount, qos: configuration.readQoS, - makeElement: { - readerCount += 1 // protected by Pool (TODO: document this protection behavior) + makeElement: { [configuration] index in return try SerializedDatabase( path: path, configuration: configuration, defaultLabel: "GRDB.DatabaseSnapshotPool", - purpose: "snapshot.\(readerCount)") + purpose: "snapshot.\(index)") }) } @@ -234,10 +239,6 @@ public final class DatabaseSnapshotPool { // DatabaseSnapshotPool is read-only. configuration.readonly = true - // DatabaseSnapshotPool uses deferred transactions by default. - // Other transaction kinds are forbidden by SQLite in read-only connections. - configuration.defaultTransactionKind = .deferred - // DatabaseSnapshotPool keeps a long-lived transaction. configuration.allowsUnsafeTransactions = true @@ -292,7 +293,42 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func read( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + guard let readerPool else { + throw DatabaseError.connectionIsClosed() + } + + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + readerPool.asyncGet { result in + do { + let (reader, releaseReader) = try result.get() + // Second async jump because that's how `Pool.async` has to be used. + reader.async { db in + defer { + releaseReader(self.poolCompletion(db)) + } + do { + let result = try dbAccess.inDatabase(db) { + try value(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } catch { + continuation.resume(throwing: error) + } + } + } + } + + public func asyncRead( + _ value: @escaping @Sendable (Result) -> Void + ) { guard let readerPool else { value(.failure(DatabaseError.connectionIsClosed())) return @@ -312,12 +348,22 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { } } + // There is no such thing as an unsafe access to a snapshot. + // We can't provide this as a default implementation in + // `DatabaseSnapshotReader`, because of + // . + public func unsafeRead( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await read(value) + } + public func unsafeReentrantRead(_ value: (Database) throws -> T) throws -> T { if let reader = currentReader { return try reader.reentrantSync { db in let result = try value(db) if snapshotIsLost(db) { - throw DatabaseError(resultCode: .SQLITE_ABORT, message: "Snapshot is lost.") + throw DatabaseError.snapshotIsLost() } return result } @@ -330,9 +376,8 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) - -> AnyDatabaseCancellable where Reducer: ValueReducer - { + onChange: @escaping @Sendable (Reducer.Value) -> Void + ) -> AnyDatabaseCancellable where Reducer: ValueReducer { _addReadOnly(observation: observation, scheduling: scheduler, onChange: onChange) } diff --git a/GRDB/Core/DatabaseValue.swift b/GRDB/Core/DatabaseValue.swift index 574ea9791..1c8e721f9 100644 --- a/GRDB/Core/DatabaseValue.swift +++ b/GRDB/Core/DatabaseValue.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// A value stored in a database table. diff --git a/GRDB/Core/DatabaseValueConvertible.swift b/GRDB/Core/DatabaseValueConvertible.swift index df9b1b693..941e59375 100644 --- a/GRDB/Core/DatabaseValueConvertible.swift +++ b/GRDB/Core/DatabaseValueConvertible.swift @@ -541,13 +541,20 @@ extension DatabaseValueConvertible { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .select(Column("score")) - /// .filter(Column("lastName") == lastName) + /// .select(\.score) + /// .filter { $0.lastName == lastName } /// /// // SQL request /// let request: SQLRequest = """ @@ -571,7 +578,7 @@ extension DatabaseValueConvertible { /// /// - parameters: /// - db: A database connection. - /// - request: A FetchRequest. + /// - request: A fetch request. /// - returns: A ``DatabaseValueCursor`` over fetched values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> DatabaseValueCursor { @@ -584,13 +591,20 @@ extension DatabaseValueConvertible { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .select(Column("score")) - /// .filter(Column("lastName") == lastName) + /// .select(\.score) + /// .filter { $0.lastName == lastName } /// /// // SQL request /// let request: SQLRequest = """ @@ -605,7 +619,7 @@ extension DatabaseValueConvertible { /// /// - parameters: /// - db: A database connection. - /// - request: A FetchRequest. + /// - request: A fetch request. /// - returns: An array. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { @@ -623,13 +637,20 @@ extension DatabaseValueConvertible { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .select(Column("score")) - /// .filter(Column("lastName") == lastName) + /// .select(\.score) + /// .filter { $0.lastName == lastName } /// /// // SQL request /// let request: SQLRequest = """ @@ -642,7 +663,7 @@ extension DatabaseValueConvertible { /// /// - parameters: /// - db: A database connection. - /// - request: A FetchRequest. + /// - request: A fetch request. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { @@ -657,13 +678,20 @@ extension DatabaseValueConvertible where Self: Hashable { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .select(Column("score")) - /// .filter(Column("lastName") == lastName) + /// .select(\.score) + /// .filter { $0.lastName == lastName } /// /// // SQL request /// let request: SQLRequest = """ @@ -678,7 +706,7 @@ extension DatabaseValueConvertible where Self: Hashable { /// /// - parameters: /// - db: A database connection. - /// - request: A FetchRequest. + /// - request: A fetch request. /// - returns: A set. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { @@ -696,13 +724,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .filter(Column("lastName") == lastName) - /// .select(Column("score"), as: Int.self) + /// .filter { $0.lastName == lastName } + /// .select(\.score, as: Int.self) /// /// // SQL request /// let request: SQLRequest = """ @@ -736,13 +771,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .filter(Column("lastName") == lastName) - /// .select(Column("score"), as: Int.self) + /// .filter { $0.lastName == lastName } + /// .select(\.score, as: Int.self) /// /// // SQL request /// let request: SQLRequest = """ @@ -772,13 +814,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .filter(Column("lastName") == lastName) - /// .select(Column("score"), as: Int.self) + /// .filter { $0.lastName == lastName } + /// .select(\.score, as: Int.self) /// /// // SQL request /// let request: SQLRequest = """ @@ -808,8 +857,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable { /// /// // Query interface request /// let request = Player - /// .filter(Column("lastName") == lastName) - /// .select(Column("score"), as: Int.self) + /// .filter { $0.lastName == lastName } + /// .select(\.score, as: Int.self) /// /// // SQL request /// let request: SQLRequest = """ diff --git a/GRDB/Core/DatabaseWriter.swift b/GRDB/Core/DatabaseWriter.swift index b4de8f6fd..cbc2041d4 100644 --- a/GRDB/Core/DatabaseWriter.swift +++ b/GRDB/Core/DatabaseWriter.swift @@ -22,25 +22,23 @@ import Dispatch /// ### Writing into the Database /// /// - ``write(_:)-76inz`` -/// - ``write(_:)-88g7e`` +/// - ``write(_:)-3db50`` /// - ``writePublisher(receiveOn:updates:)`` /// - ``writePublisher(receiveOn:updates:thenRead:)`` /// - ``writeWithoutTransaction(_:)-4qh1w`` -/// - ``writeWithoutTransaction(_:)-tckw`` +/// - ``writeWithoutTransaction(_:)-67mri`` /// - ``asyncWrite(_:completion:)`` /// - ``asyncWriteWithoutTransaction(_:)`` /// /// ### Exclusive Access to the Database /// /// - ``barrierWriteWithoutTransaction(_:)-280j1`` -/// - ``barrierWriteWithoutTransaction(_:)-7u4xw`` +/// - ``barrierWriteWithoutTransaction(_:)-48d63`` /// - ``asyncBarrierWriteWithoutTransaction(_:)`` /// /// ### Reading from the Latest Committed Database State /// -/// - ``concurrentRead(_:)`` /// - ``spawnConcurrentRead(_:)`` -/// - ``DatabaseFuture`` /// /// ### Unsafe Methods /// @@ -102,6 +100,39 @@ public protocol DatabaseWriter: DatabaseReader { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func writeWithoutTransaction(_ updates: (Database) throws -> T) rethrows -> T + /// Executes database operations, and returns their result after they have + /// finished executing. + /// + /// For example: + /// + /// ```swift + /// let newPlayerCount = try await writer.writeWithoutTransaction { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. + /// + /// - parameter updates: A closure which accesses the database. + /// - throws: Any ``DatabaseError`` that happens while establishing the + /// database access, or the error thrown by `updates`, or + /// `CancellationError` if the task is cancelled. + func writeWithoutTransaction( + _ updates: @escaping @Sendable (Database) throws -> T + ) async throws -> T + /// Executes database operations, and returns their result after they have /// finished executing. /// @@ -142,6 +173,49 @@ public protocol DatabaseWriter: DatabaseReader { @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T + /// Executes database operations, and returns their result after they have + /// finished executing. + /// + /// Database operations are not executed until all currently executing + /// database accesses performed by the database writer finish executing + /// (both reads and writes). At that point, database operations are + /// executed. Once they finish, the database writer can proceed with other + /// database accesses. + /// + /// For example: + /// + /// ```swift + /// let newPlayerCount = try await writer.barrierWriteWithoutTransaction { db in + /// try Player(name: "Arthur").insert(db) + /// return try Player.fetchCount(db) + /// } + /// ``` + /// + /// Database operations run in the writer dispatch queue, serialized + /// with all database updates performed by this `DatabaseWriter`. + /// + /// The ``Database`` argument to `updates` is valid only during the + /// execution of the closure. Do not store or return the database connection + /// for later use. + /// + /// It is a programmer error to call this method from another database + /// access method. Doing so raises a "Database methods are not reentrant" + /// fatal error at runtime. + /// + /// - warning: Database operations are not wrapped in a transaction. They + /// can see changes performed by concurrent writes or writes performed by + /// other processes: two identical requests performed by the `updates` + /// closure may not return the same value. Concurrent database accesses + /// can see partial updates performed by the `updates` closure. + /// + /// - parameter updates: A closure which accesses the database. + /// - throws: Any ``DatabaseError`` that happens while establishing the + /// database access, or the error thrown by `updates`, or + /// `CancellationError` if the task is cancelled. + func barrierWriteWithoutTransaction( + _ updates: @escaping @Sendable (Database) throws -> T + ) async throws -> T + /// Schedules database operations for execution, and returns immediately. /// /// Database operations are not executed until all currently executing @@ -181,7 +255,9 @@ public protocol DatabaseWriter: DatabaseReader { /// - parameter updates: A closure which accesses the database. Its argument /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the barrier access to the database. - func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) + func asyncBarrierWriteWithoutTransaction( + _ updates: @escaping @Sendable (Result) -> Void + ) /// Schedules database operations for execution, and returns immediately. /// @@ -213,7 +289,9 @@ public protocol DatabaseWriter: DatabaseReader { /// for more information. /// /// - parameter updates: A closure which accesses the database. - func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) + func asyncWriteWithoutTransaction( + _ updates: @escaping @Sendable (Database) -> Void + ) /// Executes database operations, and returns their result after they have /// finished executing. @@ -251,54 +329,9 @@ public protocol DatabaseWriter: DatabaseReader { // MARK: - Reading from Database - /// Schedules read-only database operations for execution, and returns a - /// future value. - /// - /// This method must be called from the writer dispatch queue, outside of - /// any transaction. You'll get a fatal error otherwise. - /// - /// Database operations performed by the `value` closure are isolated in a - /// transaction: they do not see changes performed by eventual concurrent - /// writes (even writes performed by other processes). - /// - /// They see the database in the state left by the last updates performed - /// by the database writer. - /// - /// To access the fetched results, you call the ``DatabaseFuture/wait()`` - /// method of the returned future, on any dispatch queue. - /// - /// In the example below, the number of players is fetched concurrently with - /// the player insertion. Yet the future is guaranteed to return zero: - /// - /// ```swift - /// try writer.writeWithoutTransaction { db in - /// // Delete all players - /// try Player.deleteAll() - /// - /// // Count players concurrently - /// let future = writer.concurrentRead { db in - /// return try Player.fetchCount() - /// } - /// - /// // Insert a player - /// try Player(...).insert(db) - /// - /// // Guaranteed to be zero - /// let count = try future.wait() - /// } - /// ``` - /// - /// - note: Usage of this method is discouraged, because waiting on the - /// returned ``DatabaseFuture`` blocks a thread. You may prefer - /// ``spawnConcurrentRead(_:)`` instead. - /// - parameter value: A closure which accesses the database. - func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture - // Exposed for RxGRDB and GRBCombine. Naming is not stabilized. /// Schedules read-only database operations for execution. /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// /// This method must be called from the writer dispatch queue, outside of /// any transaction. You'll get a fatal error otherwise. /// @@ -340,7 +373,9 @@ public protocol DatabaseWriter: DatabaseReader { /// - parameter value: A closure which accesses the database. Its argument /// is a `Result` that provides the database connection, or the failure /// that would prevent establishing the read access to the database. - func spawnConcurrentRead(_ value: @escaping (Result) -> Void) + func spawnConcurrentRead( + _ value: @escaping @Sendable (Result) -> Void + ) } extension DatabaseWriter { @@ -426,9 +461,9 @@ extension DatabaseWriter { /// - parameter updates: A closure which accesses the database. /// - parameter completion: A closure called with the transaction result. public func asyncWrite( - _ updates: @escaping (Database) throws -> T, - completion: @escaping (Database, Result) -> Void) - { + _ updates: @escaping @Sendable (Database) throws -> T, + completion: @escaping @Sendable (Database, Result) -> Void + ) { asyncWriteWithoutTransaction { db in do { var result: T? @@ -541,7 +576,7 @@ extension DatabaseWriter { /// /// - Parameter filePath: file path for new database @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails - @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) + @available(iOS 14, macOS 10.16, tvOS 14, *) public func vacuum(into filePath: String) throws { try writeWithoutTransaction { try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath]) @@ -557,9 +592,8 @@ extension DatabaseWriter { func _addWriteOnly( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) - -> AnyDatabaseCancellable - { + onChange: @escaping @Sendable (Reducer.Value) -> Void + ) -> AnyDatabaseCancellable { assert(!configuration.readonly, "Use _addReadOnly(observation:) instead") let observer = ValueWriteOnlyObserver( writer: self, @@ -579,8 +613,6 @@ extension DatabaseWriter { /// Executes database operations, and returns their result after they have /// finished executing. /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// /// For example: /// /// ```swift @@ -604,115 +636,23 @@ extension DatabaseWriter { /// for later use. /// /// - parameter updates: A closure which accesses the database. - /// - throws: The error thrown by `updates`, or any ``DatabaseError`` that - /// would happen while establishing the database access or committing - /// the transaction. - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func write(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in - asyncWrite(updates, completion: { _, result in - continuation.resume(with: result) - }) - } - } - - /// Executes database operations, and returns their result after they have - /// finished executing. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// For example: - /// - /// ```swift - /// let newPlayerCount = try await writer.writeWithoutTransaction { db in - /// try Player(name: "Arthur").insert(db) - /// return try Player.fetchCount(db) - /// } - /// ``` - /// - /// Database operations run in the writer dispatch queue, serialized - /// with all database updates performed by this `DatabaseWriter`. - /// - /// The ``Database`` argument to `updates` is valid only during the - /// execution of the closure. Do not store or return the database connection - /// for later use. - /// - /// - warning: Database operations are not wrapped in a transaction. They - /// can see changes performed by concurrent writes or writes performed by - /// other processes: two identical requests performed by the `updates` - /// closure may not return the same value. Concurrent database accesses - /// can see partial updates performed by the `updates` closure. - /// - /// - parameter updates: A closure which accesses the database. - /// - throws: The error thrown by `updates`. - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func writeWithoutTransaction(_ updates: @Sendable @escaping (Database) throws -> T) async throws -> T { - try await withUnsafeThrowingContinuation { continuation in - asyncWriteWithoutTransaction { db in - do { - try continuation.resume(returning: updates(db)) - } catch { - continuation.resume(throwing: error) - } - } - } - } - - /// Executes database operations, and returns their result after they have - /// finished executing. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// Database operations are not executed until all currently executing - /// database accesses performed by the database writer finish executing - /// (both reads and writes). At that point, database operations are - /// executed. Once they finish, the database writer can proceed with other - /// database accesses. - /// - /// For example: - /// - /// ```swift - /// let newPlayerCount = try await writer.barrierWriteWithoutTransaction { db in - /// try Player(name: "Arthur").insert(db) - /// return try Player.fetchCount(db) - /// } - /// ``` - /// - /// Database operations run in the writer dispatch queue, serialized - /// with all database updates performed by this `DatabaseWriter`. - /// - /// The ``Database`` argument to `updates` is valid only during the - /// execution of the closure. Do not store or return the database connection - /// for later use. - /// - /// It is a programmer error to call this method from another database - /// access method. Doing so raises a "Database methods are not reentrant" - /// fatal error at runtime. - /// - /// - warning: Database operations are not wrapped in a transaction. They - /// can see changes performed by concurrent writes or writes performed by - /// other processes: two identical requests performed by the `updates` - /// closure may not return the same value. Concurrent database accesses - /// can see partial updates performed by the `updates` closure. - /// - /// - parameter updates: A closure which accesses the database. - /// - throws: The error thrown by `updates`. - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func barrierWriteWithoutTransaction( - _ updates: @Sendable @escaping (Database) throws -> T) - async throws -> T - { - try await withUnsafeThrowingContinuation { continuation in - asyncBarrierWriteWithoutTransaction { dbResult in - continuation.resume(with: dbResult.flatMap { db in Result { try updates(db) } }) + /// - throws: Any ``DatabaseError`` that happens while establishing the + /// database access, or the error thrown by `updates`, or + /// `CancellationError` if the task is cancelled. + public func write( + _ updates: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await writeWithoutTransaction { db in + var result: T? + try db.inTransaction { + result = try updates(db) + return .commit } + return result! } } /// Erase the database: delete all content, drop all tables, etc. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func erase() async throws { try await writeWithoutTransaction { try $0.erase() } } @@ -720,10 +660,7 @@ extension DatabaseWriter { /// Rebuilds the database file, repacking it into a minimal amount of /// disk space. /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// /// Related SQLite documentation: - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func vacuum() async throws { try await writeWithoutTransaction { try $0.execute(sql: "VACUUM") } } @@ -732,15 +669,12 @@ extension DatabaseWriter { /// Creates a new database file at the specified path with a minimum /// amount of disk space. /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// /// Databases encrypted with SQLCipher are copied with the same password /// and configuration as the original database. /// /// Related SQLite documentation: /// /// - Parameter filePath: file path for new database - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func vacuum(into filePath: String) async throws { try await writeWithoutTransaction { try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath]) @@ -750,12 +684,9 @@ extension DatabaseWriter { /// Creates a new database file at the specified path with a minimum /// amount of disk space. /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// /// Related SQLite documentation: /// /// - Parameter filePath: file path for new database - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func vacuum(into filePath: String) async throws { try await writeWithoutTransaction { try $0.execute(sql: "VACUUM INTO ?", arguments: [filePath]) @@ -800,12 +731,10 @@ extension DatabaseWriter { /// /// - parameter scheduler: A Combine Scheduler. /// - parameter updates: A closure which accesses the database. - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func writePublisher( receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, - updates: @escaping (Database) throws -> Output) - -> DatabasePublishers.Write - { + updates: @escaping @Sendable (Database) throws -> Output + ) -> DatabasePublishers.Write { OnDemandFuture { fulfill in self.asyncWrite(updates, completion: { _, result in fulfill(result) @@ -865,14 +794,11 @@ extension DatabaseWriter { /// - parameter scheduler: A Combine Scheduler. /// - parameter updates: A closure which writes in the database. /// - parameter value: A closure which reads from the database. - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - public func writePublisher( - receiveOn scheduler: S = DispatchQueue.main, - updates: @escaping (Database) throws -> T, - thenRead value: @escaping (Database, T) throws -> Output) - -> DatabasePublishers.Write - where S: Scheduler - { + public func writePublisher( + receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main, + updates: @escaping @Sendable (Database) throws -> T, + thenRead value: @escaping @Sendable (Database, T) throws -> Output + ) -> DatabasePublishers.Write { OnDemandFuture { fulfill in self.asyncWriteWithoutTransaction { db in var updatesValue: T? @@ -885,7 +811,7 @@ extension DatabaseWriter { fulfill(.failure(error)) return } - self.spawnConcurrentRead { dbResult in + self.spawnConcurrentRead { [updatesValue] dbResult in fulfill(dbResult.flatMap { db in Result { try value(db, updatesValue!) } }) } } @@ -897,7 +823,6 @@ extension DatabaseWriter { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension DatabasePublishers { /// A publisher that writes into the database. /// @@ -916,7 +841,6 @@ extension DatabasePublishers { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Publisher where Failure == Error { fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write { .init(upstream: self.eraseToAnyPublisher()) @@ -924,49 +848,6 @@ extension Publisher where Failure == Error { } #endif -/// A future database value. -/// -/// You get instances of `DatabaseFuture` from the `DatabaseWriter` -/// ``DatabaseWriter/concurrentRead(_:)`` method. For example: -/// -/// ```swift -/// let futureCount: Future = try writer.writeWithoutTransaction { db in -/// try Player(...).insert() -/// -/// // Count players concurrently -/// return writer.concurrentRead { db in -/// return try Player.fetchCount() -/// } -/// } -/// -/// let count: Int = try futureCount.wait() -/// ``` -public class DatabaseFuture { - private var consumed = false - private let _wait: () throws -> Value - - init(_ wait: @escaping () throws -> Value) { - _wait = wait - } - - init(_ result: Result) { - _wait = result.get - } - - /// Blocks the current thread until the value is available, and returns it. - /// - /// It is a programmer error to call this method several times. - /// - /// - throws: Any error that prevented the value from becoming available. - public func wait() throws -> Value { - // Not thread-safe and quick and dirty. - // Goal is that users learn not to call this method twice. - GRDBPrecondition(consumed == false, "DatabaseFuture.wait() must be called only once") - consumed = true - return try _wait() - } -} - /// A type-erased database writer. /// /// An instance of `AnyDatabaseWriter` forwards its operations to an underlying @@ -976,7 +857,7 @@ public final class AnyDatabaseWriter { /// Creates a new database reader that wraps and forwards operations /// to `base`. - public init(_ base: some DatabaseWriter) { + public init(_ base: any DatabaseWriter) { self.base = base } } @@ -1003,7 +884,15 @@ extension AnyDatabaseWriter: DatabaseReader { try base.read(value) } - public func asyncRead(_ value: @escaping (Result) -> Void) { + public func read( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await base.read(value) + } + + public func asyncRead( + _ value: @escaping @Sendable (Result) -> Void + ) { base.asyncRead(value) } @@ -1012,7 +901,15 @@ extension AnyDatabaseWriter: DatabaseReader { try base.unsafeRead(value) } - public func asyncUnsafeRead(_ value: @escaping (Result) -> Void) { + public func unsafeRead( + _ value: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await base.unsafeRead(value) + } + + public func asyncUnsafeRead( + _ value: @escaping @Sendable (Result) -> Void + ) { base.asyncUnsafeRead(value) } @@ -1023,9 +920,8 @@ extension AnyDatabaseWriter: DatabaseReader { public func _add( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, - onChange: @escaping (Reducer.Value) -> Void) - -> AnyDatabaseCancellable - { + onChange: @escaping @Sendable (Reducer.Value) -> Void + ) -> AnyDatabaseCancellable { base._add( observation: observation, scheduling: scheduler, @@ -1039,16 +935,32 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.writeWithoutTransaction(updates) } + public func writeWithoutTransaction( + _ updates: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await base.writeWithoutTransaction(updates) + } + @_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails public func barrierWriteWithoutTransaction(_ updates: (Database) throws -> T) throws -> T { try base.barrierWriteWithoutTransaction(updates) } - public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result) -> Void) { + public func barrierWriteWithoutTransaction( + _ updates: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + try await base.barrierWriteWithoutTransaction(updates) + } + + public func asyncBarrierWriteWithoutTransaction( + _ updates: @escaping @Sendable (Result) -> Void + ) { base.asyncBarrierWriteWithoutTransaction(updates) } - public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) { + public func asyncWriteWithoutTransaction( + _ updates: @escaping @Sendable (Database) -> Void + ) { base.asyncWriteWithoutTransaction(updates) } @@ -1056,11 +968,9 @@ extension AnyDatabaseWriter: DatabaseWriter { try base.unsafeReentrantWrite(updates) } - public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { - base.concurrentRead(value) - } - - public func spawnConcurrentRead(_ value: @escaping (Result) -> Void) { + public func spawnConcurrentRead( + _ value: @escaping @Sendable (Result) -> Void + ) { base.spawnConcurrentRead(value) } } diff --git a/GRDB/Core/FetchRequest.swift b/GRDB/Core/FetchRequest.swift index 43115cab7..c3e24d8ba 100644 --- a/GRDB/Core/FetchRequest.swift +++ b/GRDB/Core/FetchRequest.swift @@ -171,7 +171,9 @@ extension FetchRequest { /// /// - parameter adapter: A closure that accepts a database connection and /// returns a row adapter. - public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest { + public func adapted( + _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter + ) -> AdaptedFetchRequest { AdaptedFetchRequest(self, adapter) } } @@ -181,11 +183,11 @@ extension FetchRequest { /// See ``FetchRequest/adapted(_:)``. public struct AdaptedFetchRequest { let base: Base - let adapter: (Database) throws -> any RowAdapter + let adapter: @Sendable (Database) throws -> any RowAdapter /// Creates an adapted request from a base request and a closure that builds /// a row adapter from a database connection. - init(_ base: Base, _ adapter: @escaping (Database) throws -> any RowAdapter) { + init(_ base: Base, _ adapter: @escaping @Sendable (Database) throws -> any RowAdapter) { self.base = base self.adapter = adapter } @@ -274,7 +276,7 @@ extension AnyFetchRequest: FetchRequest { } // Class-based type erasure, so that we preserve full type information. -private class FetchRequestEraser: FetchRequest { +private class FetchRequestEraser: FetchRequest, @unchecked Sendable { typealias RowDecoder = Void var sqlSubquery: SQLSubquery { @@ -290,7 +292,7 @@ private class FetchRequestEraser: FetchRequest { } } -private final class ConcreteFetchRequestEraser: FetchRequestEraser { +private final class ConcreteFetchRequestEraser: FetchRequestEraser, @unchecked Sendable { let request: Request init(request: Request) { diff --git a/GRDB/Core/Row.swift b/GRDB/Core/Row.swift index e11f35d1f..f61cb35b8 100644 --- a/GRDB/Core/Row.swift +++ b/GRDB/Core/Row.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// A database row. @@ -51,6 +60,8 @@ import Foundation /// - ``subscript(_:)-3tp8o`` /// - ``subscript(_:)-4k8od`` /// - ``subscript(_:)-9rbo7`` +/// - ``coalesce(_:)-359k7`` +/// - ``coalesce(_:)-6nbah`` /// - ``withUnsafeData(named:_:)`` /// - ``dataNoCopy(named:)`` /// @@ -662,6 +673,53 @@ extension Row { public func dataNoCopy(_ column: some ColumnExpression) -> Data? { dataNoCopy(named: column.name) } + + /// Returns the first non-null value, if any. Identical to SQL `COALESCE` function. + /// + /// For example: + /// + /// ```swift + /// let name: String? = row.coalesce(["nickname", "name"]) + /// ``` + /// + /// Prefer `coalesce` to nil-coalescing row values, which does not + /// return the expected value: + /// + /// ```swift + /// // INCORRECT + /// let name: String? = row["nickname"] ?? row["name"] + /// ``` + public func coalesce( + _ columns: some Collection + ) -> T? { + for column in columns { + if let value = self[column] as T? { + return value + } + } + return nil + } + + /// Returns the first non-null value, if any. Identical to SQL `COALESCE` function. + /// + /// For example: + /// + /// ```swift + /// let name: String? = row.coalesce([Column("nickname"), Column("name")]) + /// ``` + /// + /// Prefer `coalesce` to nil-coalescing row values, which does not + /// return the expected value: + /// + /// ```swift + /// // INCORRECT + /// let name: String? = row[Column("nickname")] ?? row[Column("name")] + /// ``` + public func coalesce( + _ columns: some Collection + ) -> T? { + return coalesce(columns.lazy.map { $0.name }) + } } extension Row { @@ -1424,8 +1482,7 @@ extension Row { /// elements are undefined. /// /// - parameters: - /// - db: A database connection. - /// - sql: An SQL string. + /// - statement: The statement to iterate. /// - arguments: Optional statement arguments. /// - adapter: Optional RowAdapter /// - returns: A ``RowCursor`` over fetched rows. @@ -1678,11 +1735,17 @@ extension Row { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request - /// let request = Player.filter(Column("lastName") == lastName) + /// let request = Player.filter { $0.lastName == lastName } /// /// // SQL request /// let request: SQLRequest = """ @@ -1713,7 +1776,7 @@ extension Row { /// /// - parameters: /// - db: A database connection. - /// - request: A FetchRequest. + /// - request: A fetch request. /// - returns: A ``RowCursor`` over fetched rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> RowCursor { @@ -1727,11 +1790,17 @@ extension Row { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request - /// let request = Player.filter(Column("lastName") == lastName) + /// let request = Player.filter { $0.lastName == lastName } /// /// // SQL request /// let request: SQLRequest = """ @@ -1744,7 +1813,7 @@ extension Row { /// /// - parameters: /// - db: A database connection. - /// - request: A FetchRequest. + /// - request: A fetch request. /// - returns: An array of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Row] { @@ -1759,11 +1828,17 @@ extension Row { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request - /// let request = Player.filter(Column("lastName") == lastName) + /// let request = Player.filter { $0.lastName == lastName } /// /// // SQL request /// let request: SQLRequest = """ @@ -1776,7 +1851,7 @@ extension Row { /// /// - parameters: /// - db: A database connection. - /// - request: A FetchRequest. + /// - request: A fetch request. /// - returns: A set of rows. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { @@ -1795,11 +1870,17 @@ extension Row { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request - /// let request = Player.filter(Column("lastName") == lastName) + /// let request = Player.filter { $0.lastName == lastName } /// /// // SQL request /// let request: SQLRequest = """ @@ -1812,7 +1893,7 @@ extension Row { /// /// - parameters: /// - db: A database connection. - /// - request: A FetchRequest. + /// - request: A fetch request. /// - returns: An optional row. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Row? { @@ -2191,7 +2272,7 @@ extension Row { /// /// See ``Row/scopesTree`` for more information. /// - /// - parameter key: An association key. + /// - parameter name: The scope name. public subscript(_ name: String) -> Row? { var fifo = Array(scopes) while !fifo.isEmpty { @@ -2387,9 +2468,7 @@ extension RowImpl { struct ArrayRowImpl: RowImpl { let columns: [(String, DatabaseValue)] - init(columns: Columns) - where Columns: Collection, Columns.Element == (String, DatabaseValue) - { + init(columns: some Collection<(String, DatabaseValue)>) { self.columns = Array(columns) } diff --git a/GRDB/Core/RowAdapter.swift b/GRDB/Core/RowAdapter.swift index a077e5815..2c4b760f1 100644 --- a/GRDB/Core/RowAdapter.swift +++ b/GRDB/Core/RowAdapter.swift @@ -183,9 +183,7 @@ public struct _LayoutedColumnMapping { /// /// // [foo:"foo" bar: "bar"] /// try Row.fetchOne(db, sql: "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter()) - init(layoutColumns: S) - where S: Sequence, S.Element == (Int, String) - { + init(layoutColumns: some Collection<(Int, String)>) { self._layoutColumns = Array(layoutColumns) self.lowercaseColumnIndexes = Dictionary( layoutColumns @@ -318,7 +316,7 @@ extension Statement: _RowLayout { /// - ``RenameColumnAdapter`` /// - ``ScopeAdapter`` /// - ``SuffixRowAdapter`` -public protocol RowAdapter { +public protocol RowAdapter: Sendable { /// You never call this method directly. It is called for you whenever an /// adapter has to be applied. /// @@ -656,11 +654,11 @@ struct ChainedAdapter: RowAdapter { /// print(Array(adaptedRow.columnNames)) /// ``` public struct RenameColumnAdapter: RowAdapter { - let transform: (String) -> String + let transform: @Sendable (String) -> String /// Creates a `RenameColumnAdapter` adapter that renames columns according to the /// provided transform function. - public init(_ transform: @escaping (String) -> String) { + public init(_ transform: @escaping @Sendable (String) -> String) { self.transform = transform } diff --git a/GRDB/Core/RowDecodingError.swift b/GRDB/Core/RowDecodingError.swift index e2ca849d4..ed82c1f89 100644 --- a/GRDB/Core/RowDecodingError.swift +++ b/GRDB/Core/RowDecodingError.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + /// A key that is used to decode a value in a row @usableFromInline enum RowKey: Hashable, Sendable { diff --git a/GRDB/Core/SQL.swift b/GRDB/Core/SQL.swift index 4246cf202..056ad8abf 100644 --- a/GRDB/Core/SQL.swift +++ b/GRDB/Core/SQL.swift @@ -39,7 +39,7 @@ /// /// - ``append(literal:)`` /// - ``append(sql:arguments:)`` -public struct SQL { +public struct SQL: Sendable { /// `SQL.Element` is a component of an `SQL` literal. /// /// Elements can be qualified with table aliases, and this is how `SQL` @@ -118,7 +118,7 @@ public struct SQL { } } - fileprivate func qualified(with alias: TableAlias) -> Element { + fileprivate func qualified(with alias: TableAliasBase) -> Element { switch self { case .sql: // A raw SQL string can't be qualified with a table alias, @@ -192,7 +192,7 @@ public struct SQL { try elements.map { try $0.sql(context) }.joined() } - func qualified(with alias: TableAlias) -> SQL { + func qualified(with alias: TableAliasBase) -> SQL { SQL(elements: elements.map { $0.qualified(with: alias) }) } } diff --git a/GRDB/Core/SchedulingWatchdog.swift b/GRDB/Core/SchedulingWatchdog.swift index 83cb6d17a..dfbdfdace 100644 --- a/GRDB/Core/SchedulingWatchdog.swift +++ b/GRDB/Core/SchedulingWatchdog.swift @@ -1,3 +1,6 @@ +#if !canImport(Darwin) +@preconcurrency +#endif import Dispatch /// SchedulingWatchdog makes sure that databases connections are used on correct @@ -21,9 +24,17 @@ import Dispatch /// /// - preconditionValidQueue() crashes whenever a database is used in an invalid /// dispatch queue. -final class SchedulingWatchdog { +final class SchedulingWatchdog: @unchecked Sendable { + // @unchecked Sendable because mutable `allowedDatabases` is only + // accessed from the serial dispatch queue the instance is attached to. + private static let watchDogKey = DispatchSpecificKey() + + /// The databases allowed in the current dispatch queue. + /// + /// MUST be accessed from the serial dispatch queue the instance is attached to. private(set) var allowedDatabases: [Database] + var databaseObservationBroker: DatabaseObservationBroker? private init(allowedDatabase database: Database) { @@ -36,10 +47,14 @@ final class SchedulingWatchdog { queue.setSpecific(key: watchDogKey, value: watchdog) } - func inheritingAllowedDatabases(from other: SchedulingWatchdog, execute body: () throws -> T) rethrows -> T { - let backup = allowedDatabases - allowedDatabases.append(contentsOf: other.allowedDatabases) - defer { allowedDatabases = backup } + /// Must be called from a DispatchQueue with an attached SchedulingWatchdog. + static func inheritingAllowedDatabases( + _ allowedDatabases: [Database], execute body: () throws -> T + ) rethrows -> T { + let watchdog = current! + let backup = watchdog.allowedDatabases + watchdog.allowedDatabases.append(contentsOf: allowedDatabases) + defer { watchdog.allowedDatabases = backup } return try body() } @@ -58,11 +73,11 @@ final class SchedulingWatchdog { current?.allows(db) ?? false } - static var current: SchedulingWatchdog? { - DispatchQueue.getSpecific(key: watchDogKey) - } - func allows(_ db: Database) -> Bool { allowedDatabases.contains { $0 === db } } + + static var current: SchedulingWatchdog? { + DispatchQueue.getSpecific(key: watchDogKey) + } } diff --git a/GRDB/Core/SerializedDatabase.swift b/GRDB/Core/SerializedDatabase.swift index f1dfe0572..b794fa63e 100644 --- a/GRDB/Core/SerializedDatabase.swift +++ b/GRDB/Core/SerializedDatabase.swift @@ -133,7 +133,7 @@ final class SerializedDatabase { // Case 3 return try queue.sync { - try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) { + try SchedulingWatchdog.inheritingAllowedDatabases(watchdog.allowedDatabases) { defer { preconditionNoUnsafeTransactionLeft(db) } return try block(db) } @@ -209,7 +209,7 @@ final class SerializedDatabase { // Case 3 return try queue.sync { - try SchedulingWatchdog.current!.inheritingAllowedDatabases(from: watchdog) { + try SchedulingWatchdog.inheritingAllowedDatabases(watchdog.allowedDatabases) { // Since we are reentrant, a transaction may already be opened. // In this case, don't check for unsafe transaction at the end. if db.isInsideTransaction { @@ -223,7 +223,7 @@ final class SerializedDatabase { } /// Schedules database operations for execution, and returns immediately. - func async(_ block: @escaping (Database) -> Void) { + func async(_ block: @escaping @Sendable (Database) -> Void) { queue.async { block(self.db) self.preconditionNoUnsafeTransactionLeft(self.db) @@ -243,6 +243,25 @@ final class SerializedDatabase { return try block(db) } + /// Asynchrously executes the block. + func execute( + _ block: @escaping @Sendable (Database) throws -> T + ) async throws -> T { + let dbAccess = CancellableDatabaseAccess() + return try await dbAccess.withCancellableContinuation { continuation in + self.async { db in + do { + let result = try dbAccess.inDatabase(db) { + try block(db) + } + continuation.resume(returning: result) + } catch { + continuation.resume(throwing: error) + } + } + } + } + func interrupt() { // Intentionally not scheduled in our serial queue db.interrupt() @@ -286,3 +305,108 @@ final class SerializedDatabase { // It happens the job of SerializedDatabase is precisely to provide thread-safe // access to `Database`. extension SerializedDatabase: @unchecked Sendable { } + +// MARK: - Task Cancellation Support + +enum DatabaseAccessCancellationState: @unchecked Sendable { + // @unchecked Sendable because database is only accessed from its + // dispatch queue. + case notConnected + case connected(Database) + case cancelled + case expired +} + +typealias CancellableDatabaseAccess = Mutex + +/// Supports Task cancellation in async database accesses. +/// +/// Usage: +/// +/// ```swift +/// let dbAccess = CancellableDatabaseAccess() +/// return try dbAccess.withCancellableContinuation { continuation in +/// asyncDatabaseAccess { db in +/// do { +/// let result = try dbAccess.inDatabase(db) { +/// // Perform database operations +/// } +/// continuation.resume(returning: result) +/// } catch { +/// continuation.resume(throwing: error) +/// } +/// } +/// } +/// ``` +extension CancellableDatabaseAccess: DatabaseCancellable { + convenience init() { + self.init(.notConnected) + } + + func cancel() { + withLock { state in + switch state { + case let .connected(db): + db.cancel() + state = .cancelled + case .notConnected: + state = .cancelled + case .cancelled, .expired: + break + } + } + } + + func withCancellableContinuation( + _ fn: (UnsafeContinuation) -> Void + ) async throws -> Value { + try await withTaskCancellationHandler { + try checkCancellation() + return try await withUnsafeThrowingContinuation { continuation in + fn(continuation) + } + } onCancel: { + cancel() + } + } + + func checkCancellation() throws { + try withLock { state in + if case .cancelled = state { + throw CancellationError() + } + } + } + + /// Wraps a full database access with cancellation support. When this + /// method returns, the database is NOT cancelled. + func inDatabase(_ db: Database, execute work: () throws -> Value) throws -> Value { + try withLock { state in + switch state { + case .connected, .expired: + fatalError("Can't use a CancellableDatabaseAccess twice") + case .notConnected: + state = .connected(db) + case .cancelled: + throw CancellationError() + } + } + + return try throwingFirstError { + try work() + } finally: { + let cancelled = withLock { state in + if case .cancelled = state { + db.uncancel() + return true + } else { + state = .expired + return false + } + } + if cancelled { + throw CancellationError() + } + } + } +} diff --git a/GRDB/Core/Statement.swift b/GRDB/Core/Statement.swift index e1a90a108..be07f9eaf 100644 --- a/GRDB/Core/Statement.swift +++ b/GRDB/Core/Statement.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// A raw SQLite statement, suitable for the SQLite C API. @@ -26,7 +35,7 @@ extension String { } public final class Statement { - enum TransactionEffect { + enum TransactionEffect: Equatable { case beginTransaction case commitTransaction case rollbackTransaction @@ -83,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. /// @@ -130,21 +142,9 @@ public final class Statement { authorizer.reset() var sqliteStatement: SQLiteStatement? = nil - let code: CInt - // sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20 -#if GRDBCUSTOMSQLITE || GRDBCIPHER - code = sqlite3_prepare_v3( + let code = sqlite3_prepare_v3( database.sqliteConnection, statementStart, -1, prepFlags, &sqliteStatement, statementEnd) -#else - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+ - code = sqlite3_prepare_v3( - database.sqliteConnection, statementStart, -1, prepFlags, - &sqliteStatement, statementEnd) - } else { - code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd) - } -#endif guard code == SQLITE_OK else { throw DatabaseError( @@ -163,6 +163,7 @@ public final class Statement { self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache self.transactionEffect = authorizer.transactionEffect self.authorizerEventKinds = authorizer.databaseEventKinds + self.isQueryOnlyPragma = authorizer.isQueryOnlyPragma } deinit { @@ -710,7 +711,7 @@ extension Statement { /// [`sqlite3_reset`](https://www.sqlite.org/c3ref/reset.html) when the cursor /// is created, and when it is deallocated. Don't share the same prepared /// statement between two cursors! -public protocol DatabaseCursor: Cursor { +public protocol DatabaseCursor: Cursor { /// Must be initialized to false. var _isDone: Bool { get set } @@ -856,14 +857,12 @@ func checkBindingSuccess(code: CInt, sqliteStatement: SQLiteStatement) throws { /// - parameter index: The index of the first binding. /// - parameter body: The closure to execute when arguments are bound. @usableFromInline -func withBindings( - _ bindings: C, +func withBindings( + _ bindings: some Collection, to sqliteStatement: SQLiteStatement, from index: CInt = 1, - do body: () throws -> T) -throws -> T -where C: Collection, C.Element == DatabaseValue -{ + do body: () throws -> T +) throws -> T { guard let binding = bindings.first else { return try body() } @@ -929,7 +928,8 @@ where C: Collection, C.Element == DatabaseValue /// ## Concatenating Arguments /// /// Several arguments can be concatenated and mixed with the -/// ``append(contentsOf:)`` method and the `+`, `&+`, `+=` operators: +/// ``StatementArguments/append(contentsOf:)`` method and the `+`, `&+`, +/// `+=` operators: /// /// ```swift /// var arguments: StatementArguments = ["Arthur"] @@ -949,8 +949,8 @@ where C: Collection, C.Element == DatabaseValue /// arguments += ["name": "Barbara"] /// ``` /// -/// On the other side, `&+` and ``append(contentsOf:)`` allow overriding -/// named arguments: +/// On the other side, `&+` and ``StatementArguments/append(contentsOf:)`` +/// allow overriding named arguments: /// /// ```swift /// var arguments: StatementArguments = ["name": "Arthur"] @@ -1009,10 +1009,8 @@ public struct StatementArguments: Hashable { /// let values: [(any DatabaseValueConvertible)?] = ["foo", 1, nil] /// db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values)) /// ``` - public init(_ sequence: S) - where S: Sequence, S.Element == (any DatabaseValueConvertible)? - { - values = sequence.map { $0?.databaseValue ?? .null } + public init(_ values: some Sequence<(any DatabaseValueConvertible)?>) { + self.values = values.map { $0?.databaseValue ?? .null } namedValues = .init() } @@ -1024,10 +1022,8 @@ public struct StatementArguments: Hashable { /// let values: [String] = ["foo", "bar"] /// db.execute(sql: "INSERT ... (?,?)", arguments: StatementArguments(values)) /// ``` - public init(_ sequence: S) - where S: Sequence, S.Element: DatabaseValueConvertible - { - values = sequence.map(\.databaseValue) + public init(_ values: some Sequence) { + self.values = values.map(\.databaseValue) namedValues = .init() } @@ -1068,11 +1064,11 @@ public struct StatementArguments: Hashable { /// Creates a `StatementArguments` of named arguments from a sequence of /// (key, value) pairs. - public init(_ sequence: S) - where S: Sequence, S.Element == (String, (any DatabaseValueConvertible)?) - { - namedValues = .init(minimumCapacity: sequence.underestimatedCount) - for (key, value) in sequence { + public init( + _ keysAndValues: some Sequence<(String, (any DatabaseValueConvertible)?)> + ) { + namedValues = .init(minimumCapacity: keysAndValues.underestimatedCount) + for (key, value) in keysAndValues { namedValues[key] = value?.databaseValue ?? .null } values = .init() diff --git a/GRDB/Core/StatementAuthorizer.swift b/GRDB/Core/StatementAuthorizer.swift index e20883049..fb27043a5 100644 --- a/GRDB/Core/StatementAuthorizer.swift +++ b/GRDB/Core/StatementAuthorizer.swift @@ -1,5 +1,20 @@ -#if os(Linux) +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + +#if canImport(string_h) +import string_h +#elseif os(Linux) import Glibc +#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS) +import Darwin +#elseif os(Windows) +import ucrt #endif /// `StatementAuthorizer` provides information about compiled database @@ -26,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) { @@ -52,6 +70,7 @@ final class StatementAuthorizer { databaseEventKinds = [] invalidatesDatabaseSchemaCache = false transactionEffect = nil + isQueryOnlyPragma = false isDropStatement = false } @@ -177,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 } diff --git a/GRDB/Core/StatementColumnConvertible.swift b/GRDB/Core/StatementColumnConvertible.swift index cb081ec63..dc9ec1b9b 100644 --- a/GRDB/Core/StatementColumnConvertible.swift +++ b/GRDB/Core/StatementColumnConvertible.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + /// A type that can decode itself from the low-level C interface to /// SQLite results. /// @@ -108,7 +117,6 @@ public protocol StatementColumnConvertible { /// - parameters: /// - sqliteStatement: A pointer to an SQLite statement. /// - index: The column index. - /// - returns: A decoded value, or, if decoding is impossible, nil. init?(sqliteStatement: SQLiteStatement, index: CInt) } @@ -555,13 +563,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .select(Column("score")) - /// .filter(Column("lastName") == lastName) + /// .select(\.score) + /// .filter { $0.lastName == lastName } /// /// // SQL request /// let request: SQLRequest = """ @@ -585,7 +600,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// /// - parameters: /// - db: A database connection. - /// - request: A FetchRequest. + /// - request: A fetch request. /// - returns: A ``FastDatabaseValueCursor`` over fetched values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: some FetchRequest) @@ -600,13 +615,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .select(Column("score")) - /// .filter(Column("lastName") == lastName) + /// .select(\.score) + /// .filter { $0.lastName == lastName } /// /// // SQL request /// let request: SQLRequest = """ @@ -621,7 +643,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// /// - parameters: /// - db: A database connection. - /// - request: A FetchRequest. + /// - request: A fetch request. /// - returns: An array of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { @@ -639,13 +661,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .select(Column("score")) - /// .filter(Column("lastName") == lastName) + /// .select(\.score) + /// .filter { $0.lastName == lastName } /// /// // SQL request /// let request: SQLRequest = """ @@ -658,7 +687,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible { /// /// - parameters: /// - db: A database connection. - /// - request: A FetchRequest. + /// - request: A fetch request. /// - returns: An optional value. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { @@ -673,13 +702,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .select(Column("score")) - /// .filter(Column("lastName") == lastName) + /// .select(\.score) + /// .filter { $0.lastName == lastName } /// /// // SQL request /// let request: SQLRequest = """ @@ -694,7 +730,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash /// /// - parameters: /// - db: A database connection. - /// - request: A FetchRequest. + /// - request: A fetch request. /// - returns: A set of values. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { @@ -712,13 +748,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .filter(Column("lastName") == lastName) - /// .select(Column("score"), as: Int.self) + /// .filter { $0.lastName == lastName } + /// .select(\.score, as: Int.self) /// /// // SQL request /// let request: SQLRequest = """ @@ -752,13 +795,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .filter(Column("lastName") == lastName) - /// .select(Column("score"), as: Int.self) + /// .filter { $0.lastName == lastName } + /// .select(\.score, as: Int.self) /// /// // SQL request /// let request: SQLRequest = """ @@ -788,13 +838,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .filter(Column("lastName") == lastName) - /// .select(Column("score"), as: Int.self) + /// .filter { $0.lastName == lastName } + /// .select(\.score, as: Int.self) /// /// // SQL request /// let request: SQLRequest = """ @@ -819,13 +876,20 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let lastName = Column("lastName") + /// } + /// } + /// /// try dbQueue.read { db in /// let lastName = "O'Reilly" /// /// // Query interface request /// let request = Player - /// .filter(Column("lastName") == lastName) - /// .select(Column("score"), as: Int.self) + /// .filter { $0.lastName == lastName } + /// .select(\.score, as: Int.self) /// /// // SQL request /// let request: SQLRequest = """ diff --git a/GRDB/Core/Support/Foundation/Data.swift b/GRDB/Core/Support/Foundation/Data.swift index 6827b71d9..55d6bdb20 100644 --- a/GRDB/Core/Support/Foundation/Data.swift +++ b/GRDB/Core/Support/Foundation/Data.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// Data is convertible to and from DatabaseValue. diff --git a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift index d4ebba478..fb861feb8 100644 --- a/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift +++ b/GRDB/Core/Support/Foundation/DatabaseDateComponents.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// A database value that holds date components. diff --git a/GRDB/Core/Support/Foundation/Date.swift b/GRDB/Core/Support/Foundation/Date.swift index cc056bea4..6676c065a 100644 --- a/GRDB/Core/Support/Foundation/Date.swift +++ b/GRDB/Core/Support/Foundation/Date.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation #if !os(Linux) diff --git a/GRDB/Core/Support/Foundation/Decimal.swift b/GRDB/Core/Support/Foundation/Decimal.swift index 44fe2eaeb..e200c6c59 100644 --- a/GRDB/Core/Support/Foundation/Decimal.swift +++ b/GRDB/Core/Support/Foundation/Decimal.swift @@ -1,4 +1,13 @@ #if !os(Linux) +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// Decimal adopts DatabaseValueConvertible diff --git a/GRDB/Core/Support/Foundation/NSNumber.swift b/GRDB/Core/Support/Foundation/NSNumber.swift index 9867e8f43..1c5778c19 100644 --- a/GRDB/Core/Support/Foundation/NSNumber.swift +++ b/GRDB/Core/Support/Foundation/NSNumber.swift @@ -1,4 +1,4 @@ -#if !os(Linux) +#if !os(Linux) && !os(Windows) import Foundation private let integerRoundingBehavior = NSDecimalNumberHandler( diff --git a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift index 4f234749d..74db8e5fd 100644 --- a/GRDB/Core/Support/Foundation/SQLiteDateParser.swift +++ b/GRDB/Core/Support/Foundation/SQLiteDateParser.swift @@ -4,7 +4,6 @@ import Foundation @usableFromInline struct SQLiteDateParser { - // swiftlint:disable:next unneeded_synthesized_initializer @usableFromInline init() { } diff --git a/GRDB/Core/Support/Foundation/URL.swift b/GRDB/Core/Support/Foundation/URL.swift index cf4b96d12..6db66ec3b 100644 --- a/GRDB/Core/Support/Foundation/URL.swift +++ b/GRDB/Core/Support/Foundation/URL.swift @@ -1,6 +1,6 @@ import Foundation -#if !os(Linux) +#if !os(Linux) && !os(Windows) /// NSURL stores its absoluteString in the database. extension NSURL: DatabaseValueConvertible { diff --git a/GRDB/Core/Support/Foundation/UUID.swift b/GRDB/Core/Support/Foundation/UUID.swift index 8aa88d090..7595b53ef 100644 --- a/GRDB/Core/Support/Foundation/UUID.swift +++ b/GRDB/Core/Support/Foundation/UUID.swift @@ -1,6 +1,15 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation -#if !os(Linux) +#if !os(Linux) && !os(Windows) /// NSUUID adopts DatabaseValueConvertible extension NSUUID: DatabaseValueConvertible { /// Returns a BLOB database value containing the uuid bytes. @@ -8,7 +17,7 @@ extension NSUUID: DatabaseValueConvertible { var uuidBytes = ContiguousArray(repeating: UInt8(0), count: 16) return uuidBytes.withUnsafeMutableBufferPointer { buffer in getBytes(buffer.baseAddress!) - return NSData(bytes: buffer.baseAddress, length: 16).databaseValue + return Data(bytes: buffer.baseAddress!, count: 16).databaseValue } } diff --git a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift index 7735a8fb6..2076df72d 100644 --- a/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift +++ b/GRDB/Core/Support/StandardLibrary/DatabaseValueConvertible+Encodable.swift @@ -129,7 +129,7 @@ private class DatabaseValueEncoder: Encoder { // eventually perform JSON decoding. // TODO: possible optimization: avoid this conversion to string, // and store raw data bytes as an SQLite string - let jsonString = String(data: jsonData, encoding: .utf8)! + let jsonString = String(decoding: jsonData, as: UTF8.self) try jsonString.encode(to: self) } } diff --git a/GRDB/Core/Support/StandardLibrary/Optional.swift b/GRDB/Core/Support/StandardLibrary/Optional.swift index 4c9e3a3b9..0902097d9 100644 --- a/GRDB/Core/Support/StandardLibrary/Optional.swift +++ b/GRDB/Core/Support/StandardLibrary/Optional.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + extension Optional: StatementBinding where Wrapped: StatementBinding { public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt { switch self { diff --git a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift index 021beb492..d72cf3d19 100644 --- a/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift +++ b/GRDB/Core/Support/StandardLibrary/StandardLibrary.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + // MARK: - Value Types /// Bool adopts DatabaseValueConvertible and StatementColumnConvertible. @@ -641,8 +650,7 @@ extension DatabaseFunction { /// ``SQLSpecificExpressible/capitalized``: /// /// ```swift - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.capitalized) + /// let request = Player.select { $0.name.capitalized } /// let names = try String.fetchAll(dbQueue, request) // [String] /// ``` public static let capitalize = @@ -663,8 +671,7 @@ extension DatabaseFunction { /// ``SQLSpecificExpressible/lowercased``: /// /// ```swift - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.lowercased) + /// let request = Player.select { $0.name.lowercased } /// let names = try String.fetchAll(dbQueue, request) // [String] /// ``` public static let lowercase = @@ -685,8 +692,7 @@ extension DatabaseFunction { /// ``SQLSpecificExpressible/uppercased``: /// /// ```swift - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.uppercased) + /// let request = Player.select { $0.name.uppercased } /// let names = try String.fetchAll(dbQueue, request) // [String] /// ``` public static let uppercase = @@ -707,8 +713,7 @@ extension DatabaseFunction { /// ``SQLSpecificExpressible/localizedCapitalized``: /// /// ```swift - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.localizedCapitalized) + /// let request = Player.select { $0.name.localizedCapitalized } /// let names = try String.fetchAll(dbQueue, request) // [String] /// ``` public static let localizedCapitalize = @@ -730,8 +735,7 @@ extension DatabaseFunction { /// ``SQLSpecificExpressible/localizedLowercased``: /// /// ```swift - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.localizedLowercase) + /// let request = Player.select { $0.name.localizedLowercase } /// let names = try String.fetchAll(dbQueue, request) // [String] /// ``` public static let localizedLowercase = @@ -752,8 +756,7 @@ extension DatabaseFunction { /// ``SQLSpecificExpressible/localizedUppercased``: /// /// ```swift - /// let nameColumn = Column("name") - /// let request = Player.select(nameColumn.localizedUppercase) + /// let request = Player.select { $0.name.localizedUppercase } /// let names = try String.fetchAll(dbQueue, request) // [String] /// ``` public static let localizedUppercase = diff --git a/GRDB/Core/TransactionClock.swift b/GRDB/Core/TransactionClock.swift index d878cd450..b467ce724 100644 --- a/GRDB/Core/TransactionClock.swift +++ b/GRDB/Core/TransactionClock.swift @@ -10,7 +10,7 @@ import Foundation /// /// - ``DefaultTransactionClock`` /// - ``CustomTransactionClock`` -public protocol TransactionClock { +public protocol TransactionClock: Sendable { /// Returns the date of the current transaction. /// /// This function is called whenever a transaction starts - precisely @@ -36,7 +36,7 @@ extension TransactionClock where Self == CustomTransactionClock { /// /// It is also called when the ``Database/transactionDate`` property is /// called, and the database connection is not in a transaction. - public static func custom(_ now: @escaping (Database) throws -> Date) -> Self { + public static func custom(_ now: @escaping @Sendable (Database) throws -> Date) -> Self { CustomTransactionClock(now) } } @@ -53,9 +53,9 @@ public struct DefaultTransactionClock: TransactionClock { /// A custom transaction clock. public struct CustomTransactionClock: TransactionClock { - let _now: (Database) throws -> Date + let _now: @Sendable (Database) throws -> Date - public init(_ now: @escaping (Database) throws -> Date) { + public init(_ now: @escaping @Sendable (Database) throws -> Date) { self._now = now } diff --git a/GRDB/Core/TransactionObserver.swift b/GRDB/Core/TransactionObserver.swift index c0d0d991a..cd536035c 100644 --- a/GRDB/Core/TransactionObserver.swift +++ b/GRDB/Core/TransactionObserver.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + extension Database { // MARK: - Database Observation @@ -101,14 +110,17 @@ extension Database { /// - parameter onCommit: A closure executed on transaction commit. /// - parameter onRollback: A closure executed on transaction rollback. public func afterNextTransaction( - onCommit: @escaping (Database) -> Void, - onRollback: @escaping (Database) -> Void = { _ in }) + onCommit: @escaping @Sendable (Database) -> Void, + onRollback: @escaping @Sendable (Database) -> Void = { _ in }) { class TransactionHandler: TransactionObserver { - let onCommit: (Database) -> Void - let onRollback: (Database) -> Void + let onCommit: @Sendable (Database) -> Void + let onRollback: @Sendable (Database) -> Void - init(onCommit: @escaping (Database) -> Void, onRollback: @escaping (Database) -> Void) { + init( + onCommit: @escaping @Sendable (Database) -> Void, + onRollback: @escaping @Sendable (Database) -> Void + ) { self.onCommit = onCommit self.onRollback = onRollback } @@ -537,8 +549,12 @@ class DatabaseObservationBroker { savepointStack.clear() if !database.isReadOnly { - for observation in transactionObservations { - observation.databaseDidCommit(database) + // Observers must be able to access the database, even if the + // task that has performed the commit is cancelled. + database.ignoringCancellation { + for observation in transactionObservations { + observation.databaseDidCommit(database) + } } } @@ -601,8 +617,13 @@ class DatabaseObservationBroker { if notifyTransactionObservers { assert(!database.isReadOnly, "Read-only transactions are not notified") - for observation in transactionObservations { - observation.databaseDidRollback(database) + + // Observers must be able to access the database, even if the + // task that has performed the commit is cancelled. + database.ignoringCancellation { + for observation in transactionObservations { + observation.databaseDidRollback(database) + } } } databaseDidEndTransaction() diff --git a/GRDB/Core/WALSnapshot.swift b/GRDB/Core/WALSnapshot.swift index 4d50c67e0..a8c0168a7 100644 --- a/GRDB/Core/WALSnapshot.swift +++ b/GRDB/Core/WALSnapshot.swift @@ -1,5 +1,13 @@ -// swiftlint:disable:next line_length -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + /// An instance of WALSnapshot records the state of a WAL mode database for some /// specific point in history. /// @@ -15,8 +23,8 @@ /// With custom SQLite builds, it only works if `SQLITE_ENABLE_SNAPSHOT` /// is defined. /// -/// With system SQLite, it can only work when the SDK exposes the C apis and -/// their availability, which means XCode 14 (identified with Swift 5.7). +/// With system SQLite, it works because the SDK exposes the C apis and +/// since XCode 14. /// /// Yes, this is an awfully complex logic. /// diff --git a/GRDB/Core/WALSnapshotTransaction.swift b/GRDB/Core/WALSnapshotTransaction.swift index 5f56f1d2f..eb6597fe1 100644 --- a/GRDB/Core/WALSnapshotTransaction.swift +++ b/GRDB/Core/WALSnapshotTransaction.swift @@ -1,12 +1,30 @@ -// swiftlint:disable:next line_length -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) /// A long-live read-only WAL transaction. /// /// `WALSnapshotTransaction` **takes ownership** of its reader /// `SerializedDatabase` (TODO: make it a move-only type eventually). -class WALSnapshotTransaction { - private let reader: SerializedDatabase - private let release: (_ isInsideTransaction: Bool) -> Void +final class WALSnapshotTransaction: @unchecked Sendable { + // @unchecked because `databaseAccess` is protected by a mutex. + + private struct DatabaseAccess { + let reader: SerializedDatabase + let release: @Sendable (_ isInsideTransaction: Bool) -> Void + + // MUST be called only once + func commitAndRelease() { + // WALSnapshotTransaction may be deinitialized in the dispatch + // queue of its reader: allow reentrancy. + let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in + try? db.commit() + return db.isInsideTransaction + } + release(isInsideTransaction) + } + } + + // TODO: consider using the serialized DispatchQueue of reader instead of a lock. + /// nil when closed + private let databaseAccessMutex: Mutex /// The state of the database at the beginning of the transaction. let walSnapshot: WALSnapshot @@ -37,10 +55,11 @@ class WALSnapshotTransaction { /// is no longer used. init( onReader reader: SerializedDatabase, - release: @escaping (_ isInsideTransaction: Bool) -> Void) + release: @escaping @Sendable (_ isInsideTransaction: Bool) -> Void) throws { assert(reader.configuration.readonly) + let databaseAccess = DatabaseAccess(reader: reader, release: release) do { // Open a long-lived transaction, and enter snapshot isolation @@ -51,44 +70,56 @@ class WALSnapshotTransaction { try db.clearSchemaCacheIfNeeded() return try WALSnapshot(db) } - self.reader = reader - self.release = release + self.databaseAccessMutex = Mutex(databaseAccess) } catch { // self is not initialized, so deinit will not run. - Self.commitAndRelease(reader: reader, release: release) + databaseAccess.commitAndRelease() throw error } } deinit { - Self.commitAndRelease(reader: reader, release: release) + close() } /// Executes database operations in the snapshot transaction, and /// returns their result after they have finished executing. - func read(_ value: (Database) throws -> T) rethrows -> T { - // We should check the validity of the snapshot, as DatabaseSnapshotPool does. - try reader.sync(value) + func read(_ value: (Database) throws -> T) throws -> T { + try databaseAccessMutex.withLock { databaseAccess in + guard let databaseAccess else { + throw DatabaseError.snapshotIsLost() + } + + // We should check the validity of the snapshot, as DatabaseSnapshotPool does. + return try databaseAccess.reader.sync(value) + } } /// Schedules database operations for execution, and /// returns immediately. - func asyncRead(_ value: @escaping (Database) -> Void) { - // We should check the validity of the snapshot, as DatabaseSnapshotPool does. - reader.async(value) + func asyncRead(_ value: @escaping @Sendable (Result) -> Void) { + databaseAccessMutex.withLock { databaseAccess in + guard let databaseAccess else { + value(.failure(DatabaseError.snapshotIsLost())) + return + } + + databaseAccess.reader.async { db in + // We should check the validity of the snapshot, as DatabaseSnapshotPool does. + // At least check if self was closed: + if self.databaseAccessMutex.load() == nil { + value(.failure(DatabaseError.snapshotIsLost())) + } + value(.success(db)) + } + } } - private static func commitAndRelease( - reader: SerializedDatabase, - release: (_ isInsideTransaction: Bool) -> Void) - { - // WALSnapshotTransaction may be deinitialized in the dispatch - // queue of its reader: allow reentrancy. - let isInsideTransaction = reader.reentrantSync(allowingLongLivedTransaction: false) { db in - try? db.commit() - return db.isInsideTransaction + func close() { + databaseAccessMutex.withLock { databaseAccess in + databaseAccess?.commitAndRelease() + databaseAccess = nil } - release(isInsideTransaction) } } #endif diff --git a/GRDB/Documentation.docc/Concurrency.md b/GRDB/Documentation.docc/Concurrency.md index 4c5f7e908..439ce4fa5 100644 --- a/GRDB/Documentation.docc/Concurrency.md +++ b/GRDB/Documentation.docc/Concurrency.md @@ -1,6 +1,6 @@ # Concurrency -GRDB helps your app deal with SQLite concurrency. +GRDB helps your app deal with Swift and SQLite concurrency. ## Overview @@ -84,9 +84,7 @@ try dbQueue.write { db in 🔀 **An async access does not block the current thread.** Instead, it notifies you when the database operations are completed. There are four ways to access the database asynchronously: -- **Swift concurrency** (async/await) - - [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) +- **Swift concurrency** (async/await) ```swift let playerCount = try await dbQueue.read { db in @@ -99,9 +97,13 @@ try dbQueue.write { db in } ``` - See ``DatabaseReader/read(_:)-4w6gy`` and ``DatabaseWriter/write(_:)-88g7e``. + See ``DatabaseReader/read(_:)-4d1da`` and ``DatabaseWriter/write(_:)-3db50``. Note the identical method names: `read`, `write`. The async version is only available in async Swift functions. + + The async database access methods honor task cancellation. Once an async Task is cancelled, reads and writes throw `CancellationError`, and any transaction is rollbacked. + + See for more information about GRDB and Swift 6. - **Combine publishers** @@ -277,31 +279,7 @@ let newPlayerCount = try dbPool.write { db in } ``` -➡️ The synchronous solution is the ``DatabaseWriter/concurrentRead(_:)`` method. It must be called from within a write access, outside of any transaction. It returns a ``DatabaseFuture`` which you consume any time later, with the ``DatabaseFuture/wait()`` method: - -```swift -let future: DatabaseFuture = try dbPool.writeWithoutTransaction { db in - // Increment the number of players - try db.inTransaction { - try Player(...).insert(db) - return .commit - } - - // <- Not in a transaction here - return dbPool.concurrentRead { db - try Player.fetchCount(db) - } -} - -do { - // Handle the new player count - guaranteed greater than zero - let newPlayerCount = try future.wait() -} catch { - // Handle error -} -``` - -🔀 The asynchronous version of `concurrentRead` is ``DatabasePool/asyncConcurrentRead(_:)``: +🔀 The solution is ``DatabasePool/asyncConcurrentRead(_:)``. It must be called from within a write access, outside of any transaction: ```swift try dbPool.writeWithoutTransaction { db in @@ -324,11 +302,10 @@ try dbPool.writeWithoutTransaction { db in } ``` -Both ``DatabaseWriter/concurrentRead(_:)`` and ``DatabasePool/asyncConcurrentRead(_:)`` block until they can guarantee their closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes this closure. +The ``DatabasePool/asyncConcurrentRead(_:)`` method blocks until it can guarantee its closure argument an isolated access to the database, in the exact state left by the last transaction. It then asynchronously executes the closure. In the illustration below, the striped band shows the delay needed for the reading thread to acquire isolation. Until then, no other thread can write: - ![DatabasePool Concurrent Read](DatabasePoolConcurrentRead.png) Types that conform to ``TransactionObserver`` can also use those methods in their ``TransactionObserver/databaseDidCommit(_:)`` method, in order to process database changes without blocking other threads that want to write into the database. @@ -341,8 +318,9 @@ Types that conform to ``TransactionObserver`` can also use those methods in thei - ``DatabaseReader`` - ``DatabaseSnapshotReader`` -### Advanced Concurrency +### Going Further +- - diff --git a/GRDB/Documentation.docc/DatabaseSchema.md b/GRDB/Documentation.docc/DatabaseSchema.md index abfd53021..dde873346 100644 --- a/GRDB/Documentation.docc/DatabaseSchema.md +++ b/GRDB/Documentation.docc/DatabaseSchema.md @@ -6,7 +6,7 @@ Define or query the database schema. **GRDB supports all database schemas, and has no requirement.** Any existing SQLite database can be opened, and you are free to structure your new databases as you wish. -You perform modifications to the database schema with methods such as ``Database/create(table:options:body:)``, listed at the end of this page. For example: +You perform modifications to the database schema with methods such as ``Database/create(table:options:body:)``, listed in . For example: ```swift try db.create(table: "player") { t in @@ -16,408 +16,19 @@ try db.create(table: "player") { t in } ``` -When you plan to evolve the schema as new versions of your application ship, wrap all schema changes in . - -Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example). - -When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See for the detailed procedure. - -## Database Schema Recommendations - -Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below. - -When those conventions are not applied, or not applicable, you will have to perform extra configurations. - -For recommendations specific to JSON columns, see . - -### Table names should be English, singular, and camelCased - -Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`: - -```swift -// RECOMMENDED -try db.create(table: "player") { t in - // table columns and constraints -} - -// REQUIRES EXTRA CONFIGURATION -try db.create(table: "players") { t in - // table columns and constraints -} -``` - -☝️ **If table names follow a different naming convention**, record types (see ) will need explicit table names: - -```swift -extension Player: TableRecord { - // Required because table name is not 'player' - static let databaseTableName = "players" -} - -extension PostalAddress: TableRecord { - // Required because table name is not 'postalAddress' - static let databaseTableName = "postal_address" -} - -extension Award: TableRecord { - // Required because table name is not 'award' - static let databaseTableName = "Auszeichnung" -} -``` - -[Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) will need explicit keys as well: - -```swift -extension Player: TableRecord { - // Explicit association key because the table name is not 'postalAddress' - static let postalAddress = belongsTo(PostalAddress.self, key: "postalAddress") - - // Explicit association key because the table name is not 'award' - static let awards = hasMany(Award.self, key: "awards") -} -``` - -As in the above example, make sure to-one associations use singular keys, and to-many associations use plural keys. - -### Column names should be camelCased - -Again, make them look like Swift identifiers: `fullName`, `score`, `creationDate`: - -```swift -// RECOMMENDED -try db.create(table: "player") { t in - t.autoIncrementedPrimaryKey("id") - t.column("fullName", .text).notNull() - t.column("score", .integer).notNull() - t.column("creationDate", .datetime).notNull() -} - -// REQUIRES EXTRA CONFIGURATION -try db.create(table: "player") { t in - t.autoIncrementedPrimaryKey("id") - t.column("full_name", .text).notNull() - t.column("score", .integer).notNull() - t.column("creation_date", .datetime).notNull() -} -``` - -☝️ **If the column names follow a different naming convention**, `Codable` record types will need an explicit `CodingKeys` enum: - -```swift -struct Player: Decodable, FetchableRecord { - var id: Int64 - var fullName: String - var score: Int - var creationDate: Date - - // Required CodingKeys customization because - // columns are not named like Swift properties - enum CodingKeys: String, CodingKey { - case id, fullName = "full_name", score, creationDate = "creation_date" - } -} -``` - -### Tables should have explicit primary keys - -A primary key uniquely identifies a row in a table. It is defined on one or several columns: - -```swift -// RECOMMENDED -try db.create(table: "player") { t in - // Auto-incremented primary key - t.autoIncrementedPrimaryKey("id") - t.column("name", .text).notNull() -} - -try db.create(table: "team") { t in - // Single-column primary key - t.primaryKey("id", .text) - t.column("name", .text).notNull() -} - -try db.create(table: "membership") { t in - // Composite primary key - t.primaryKey { - t.belongsTo("player") - t.belongsTo("team") - } - t.column("role", .text).notNull() -} -``` - -Primary keys support record fetching methods such as ``FetchableRecord/fetchOne(_:id:)``, and persistence methods such as ``MutablePersistableRecord/update(_:onConflict:)`` or ``MutablePersistableRecord/delete(_:)``. - -See when you need to define a table that contains a single row. - -☝️ **If the database table does not define any explicit primary key**, identifying specific rows in this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html) in the matching record types: - -```swift -// A table without any explicit primary key -try db.create(table: "player") { t in - t.column("name", .text).notNull() - t.column("score", .integer).notNull() -} - -// The record type for the 'player' table' -struct Player: Codable { - // Uniquely identifies a player. - var rowid: Int64? - var name: String - var score: Int -} - -extension Player: FetchableRecord, MutablePersistableRecord { - // Required because the primary key - // is the hidden rowid column. - static let databaseSelection: [any SQLSelectable] = [ - AllColumns(), - Column.rowID] - - // Update id upon successful insertion - mutating func didInsert(_ inserted: InsertionSuccess) { - rowid = inserted.rowID - } -} - -try dbQueue.read { db in - // SELECT *, rowid FROM player WHERE rowid = 1 - if let player = try Player.fetchOne(db, id: 1) { - // DELETE FROM player WHERE rowid = 1 - let deleted = try player.delete(db) - print(deleted) // true - } -} -``` - -### Single-column primary keys should be named 'id' - -This helps record types play well with the standard `Identifiable` protocol. - -```swift -// RECOMMENDED -try db.create(table: "player") { t in - t.primaryKey("id", .text) - t.column("name", .text).notNull() -} - -// REQUIRES EXTRA CONFIGURATION -try db.create(table: "player") { t in - t.primaryKey("uuid", .text) - t.column("name", .text).notNull() -} -``` -☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need a custom `CodingKeys` enum, or an extra property: - -```swift -// Custom coding keys -struct Player: Codable, Identifiable { - var id: String - var name: String - - // Required CodingKeys customization because - // columns are not named like Swift properties - enum CodingKeys: String, CodingKey { - case id = "uuid", name - } -} - -// Extra property -struct Player: Identifiable { - var uuid: String - var name: String - - // Required because the primary key column is not 'id' - var id: String { uuid } -} -``` - -### Unique keys should be supported by unique indexes - -Unique indexes makes sure SQLite prevents the insertion of conflicting rows: - -```swift -// RECOMMENDED -try db.create(table: "player") { t in - t.autoIncrementedPrimaryKey("id") - t.belongsTo("team").notNull() - t.column("position", .integer).notNull() - // Players must have distinct names - t.column("name", .text).unique() -} - -// One single player at any given position in a team -try db.create( - indexOn: "player", - columns: ["teamId", "position"], - options: .unique) -``` - -> Tip: SQLite does not support deferred unique indexes, and this creates undesired churn when you need to temporarily break them. This may happen, for example, when you want to reorder player positions in our above example. -> -> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, take care that only actual indexes can be dropped. Unique constraints created inside the table body can not: -> -> ```swift -> // Unique constraint on player(name) can not be dropped. -> try db.create(table: "player") { t in -> t.column("name", .text).unique() -> } -> -> // Unique index on team(name) can be dropped. -> try db.create(table: "team") { t in -> t.column("name", .text) -> } -> try db.create(indexOn: "team", columns: ["name"], options: .unique) -> ``` -> -> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See for the detailed procedure. - -☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error: - -```swift -try dbQueue.write { db in - // Fatal error: table player has no unique index on columns ... - let player = try Player.fetchOne(db, key: ["teamId": 42, "position": 1]) - try Player.deleteOne(db, key: ["name": "Arthur"]) - - // Use instead: - let player = try Player - .filter(Column("teamId") == 42 && Column("position") == 1) - .fetchOne(db) - - try Player - .filter(Column("name") == "Arthur") - .deleteAll(db) -} -``` - -### Relations between tables should be supported by foreign keys - -[Foreign Keys](https://www.sqlite.org/foreignkeys.html) have SQLite enforce valid relationships between tables: - -```swift -try db.create(table: "team") { t in - t.autoIncrementedPrimaryKey("id") - t.column("color", .text).notNull() -} - -// RECOMMENDED -try db.create(table: "player") { t in - t.autoIncrementedPrimaryKey("id") - t.column("name", .text).notNull() - // A player must refer to an existing team - t.belongsTo("team").notNull() -} - -// REQUIRES EXTRA CONFIGURATION -try db.create(table: "player") { t in - t.autoIncrementedPrimaryKey("id") - t.column("name", .text).notNull() - // No foreign key - t.column("teamId", .integer).notNull() -} -``` - -See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` for more information about the creation of foreign keys. - -GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema: - -```swift -extension Player: TableRecord { - static let team = belongsTo(Team.self) -} - -extension Team: TableRecord { - static let players = hasMany(Player.self) -} -``` - -See [Associations and the Database Schema](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#associations-and-the-database-schema) for more precise recommendations. - -☝️ **If a foreign key is not declared in the schema**, you will need to explicitly configure related associations: - -```swift -extension Player: TableRecord { - // Required configuration because the database does - // not declare any foreign key from players to their team. - static let teamForeignKey = ForeignKey(["teamId"]) - static let team = belongsTo(Team.self, - using: teamForeignKey) -} - -extension Team: TableRecord { - // Required configuration because the database does - // not declare any foreign key from players to their team. - static let players = hasMany(Player.self, - using: Player.teamForeignKey) -} -``` +Most applications modify the database schema as new versions ship: it is recommended to wrap all schema changes in . ## Topics -### Database Tables +### Define the database schema -- ``Database/alter(table:body:)`` -- ``Database/create(table:options:body:)`` -- ``Database/create(virtualTable:ifNotExists:using:)`` -- ``Database/create(virtualTable:ifNotExists:using:_:)`` -- ``Database/drop(table:)`` -- ``Database/dropFTS4SynchronizationTriggers(forTable:)`` -- ``Database/dropFTS5SynchronizationTriggers(forTable:)`` -- ``Database/rename(table:to:)`` -- ``Database/ColumnType`` -- ``Database/ConflictResolution`` -- ``Database/ForeignKeyAction`` -- ``TableAlteration`` -- ``TableDefinition`` -- ``TableOptions`` -- ``VirtualTableModule`` +- +- -### Database Views +### Introspect the database schema -- ``Database/create(view:options:columns:as:)`` -- ``Database/create(view:options:columns:asLiteral:)`` -- ``Database/drop(view:)`` -- ``ViewOptions`` +- -### Database Indexes +### Check the database schema -- ``Database/create(indexOn:columns:options:condition:)`` -- ``Database/create(index:on:columns:options:condition:)`` -- ``Database/create(index:on:expressions:options:condition:)`` -- ``Database/drop(indexOn:columns:)`` -- ``Database/drop(index:)`` -- ``IndexOptions`` - -### Querying the Database Schema - -- ``Database/columns(in:in:)`` -- ``Database/foreignKeys(on:in:)`` -- ``Database/indexes(on:in:)`` -- ``Database/isGRDBInternalTable(_:)`` -- ``Database/isSQLiteInternalTable(_:)`` -- ``Database/primaryKey(_:in:)`` -- ``Database/schemaVersion()`` -- ``Database/table(_:hasUniqueKey:)`` -- ``Database/tableExists(_:in:)`` -- ``Database/triggerExists(_:in:)`` -- ``Database/viewExists(_:in:)`` -- ``ColumnInfo`` -- ``ForeignKeyInfo`` -- ``IndexInfo`` -- ``PrimaryKeyInfo`` - -### Integrity Checks - -- ``Database/checkForeignKeys()`` -- ``Database/checkForeignKeys(in:in:)`` -- ``Database/foreignKeyViolations()`` -- ``Database/foreignKeyViolations(in:in:)`` -- ``ForeignKeyViolation`` - -### Sunsetted Methods - -Those are legacy interfaces that are preserved for backwards compatibility. Their use is not recommended. - -- ``Database/create(index:on:columns:unique:ifNotExists:condition:)`` -- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)`` +- diff --git a/GRDB/Documentation.docc/DatabaseSchemaIntegrityChecks.md b/GRDB/Documentation.docc/DatabaseSchemaIntegrityChecks.md new file mode 100644 index 000000000..afa549e39 --- /dev/null +++ b/GRDB/Documentation.docc/DatabaseSchemaIntegrityChecks.md @@ -0,0 +1,13 @@ +# Integrity Checks + +Perform integrity checks of the database content + +## Topics + +### Integrity Checks + +- ``Database/checkForeignKeys()`` +- ``Database/checkForeignKeys(in:in:)`` +- ``Database/foreignKeyViolations()`` +- ``Database/foreignKeyViolations(in:in:)`` +- ``ForeignKeyViolation`` diff --git a/GRDB/Documentation.docc/DatabaseSchemaIntrospection.md b/GRDB/Documentation.docc/DatabaseSchemaIntrospection.md new file mode 100644 index 000000000..ee114e8c1 --- /dev/null +++ b/GRDB/Documentation.docc/DatabaseSchemaIntrospection.md @@ -0,0 +1,35 @@ +# Database Schema Introspection + +Get information about schema objects such as tables, columns, indexes, foreign keys, etc. + +## Topics + +### Querying the Schema Version + +- ``Database/schemaVersion()`` + +### Existence Checks + +- ``Database/tableExists(_:in:)`` +- ``Database/triggerExists(_:in:)`` +- ``Database/viewExists(_:in:)`` + +### Table Structure + +- ``Database/columns(in:in:)`` +- ``Database/foreignKeys(on:in:)`` +- ``Database/indexes(on:in:)`` +- ``Database/primaryKey(_:in:)`` +- ``Database/table(_:hasUniqueKey:)`` + +### Reserved Tables + +- ``Database/isGRDBInternalTable(_:)`` +- ``Database/isSQLiteInternalTable(_:)`` + +### Supporting Types + +- ``ColumnInfo`` +- ``ForeignKeyInfo`` +- ``IndexInfo`` +- ``PrimaryKeyInfo`` diff --git a/GRDB/Documentation.docc/DatabaseSchemaModifications.md b/GRDB/Documentation.docc/DatabaseSchemaModifications.md new file mode 100644 index 000000000..202677e0d --- /dev/null +++ b/GRDB/Documentation.docc/DatabaseSchemaModifications.md @@ -0,0 +1,293 @@ +# Modifying the Database Schema + +How to modify the database schema + +## Overview + +For modifying the database schema, prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example). + +When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See for the detailed procedure. + +## Create Tables + +The ``Database/create(table:options:body:)`` method covers nearly all SQLite table creation features. For virtual tables, see [Full-Text Search](https://github.com/groue/GRDB.swift/blob/master/Documentation/FullTextSearch.md), or use raw SQL. + +```swift +// CREATE TABLE place ( +// id INTEGER PRIMARY KEY AUTOINCREMENT, +// title TEXT, +// favorite BOOLEAN NOT NULL DEFAULT 0, +// latitude DOUBLE NOT NULL, +// longitude DOUBLE NOT NULL +// ) +try db.create(table: "place") { t in + t.autoIncrementedPrimaryKey("id") + t.column("title", .text) + t.column("favorite", .boolean).notNull().defaults(to: false) + t.column("longitude", .double).notNull() + t.column("latitude", .double).notNull() +} +``` + +**Configure table creation** + +```swift +// CREATE TABLE player ( ... ) +try db.create(table: "player") { t in ... } + +// CREATE TEMPORARY TABLE player IF NOT EXISTS ( +try db.create(table: "player", options: [.temporary, .ifNotExists]) { t in ... } +``` + +Reference: ``TableOptions`` + +**Add regular columns** with their name and eventual type (`text`, `integer`, `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime`, `any`, and `json`) - see [SQLite data types](https://www.sqlite.org/datatype3.html) and : + +```swift +// CREATE TABLE player ( +// score, +// name TEXT, +// creationDate DATETIME, +// address TEXT, +try db.create(table: "player") { t in + t.column("score") + t.column("name", .text) + t.column("creationDate", .datetime) + t.column("address", .json) +``` + +Reference: ``TableDefinition/column(_:_:)`` + +Define **not null** columns, and set **default values**: + +```swift + // email TEXT NOT NULL, + t.column("email", .text).notNull() + + // name TEXT NOT NULL DEFAULT 'Anonymous', + t.column("name", .text).notNull().defaults(to: "Anonymous") +``` + +Reference: ``ColumnDefinition`` + +**Define primary, unique, or foreign keys**. When defining a foreign key, the referenced column is the primary key of the referenced table (unless you specify otherwise): + +```swift + // id INTEGER PRIMARY KEY AUTOINCREMENT, + t.autoIncrementedPrimaryKey("id") + + // uuid TEXT PRIMARY KEY NOT NULL, + t.primaryKey("uuid", .text) + + // teamName TEXT NOT NULL, + // position INTEGER NOT NULL, + // PRIMARY KEY (teamName, position), + t.primaryKey { + t.column("teamName", .text) + t.column("position", .integer) + } + + // email TEXT UNIQUE, + t.column("email", .text).unique() + + // teamId TEXT REFERENCES team(id) ON DELETE CASCADE, + // countryCode TEXT REFERENCES country(code) NOT NULL, + t.belongsTo("team", onDelete: .cascade) + t.belongsTo("country").notNull() +``` + +Reference: ``TableDefinition``, ``ColumnDefinition/unique(onConflict:)`` + +**Create an index** on a column + +```swift + t.column("score", .integer).indexed() +``` + +Reference: ``ColumnDefinition`` + +For extra index options, see below. + +**Perform integrity checks** on individual columns, and SQLite will only let conforming rows in. In the example below, the `$0` closure variable is a column which lets you build any SQL expression. + +```swift + // name TEXT CHECK (LENGTH(name) > 0) + // score INTEGER CHECK (score > 0) + t.column("name", .text).check { length($0) > 0 } + t.column("score", .integer).check(sql: "score > 0") +``` + +Reference: ``ColumnDefinition`` + +Columns can also be defined with a raw sql String, or an [SQL literal](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md#sql-literal) in which you can safely embed raw values without any risk of syntax errors or SQL injection: + +```swift + t.column(sql: "name TEXT") + + let defaultName: String = ... + t.column(literal: "name TEXT DEFAULT \(defaultName)") +``` + +Reference: ``TableDefinition`` + +Other **table constraints** can involve several columns: + +```swift + // PRIMARY KEY (a, b), + t.primaryKey(["a", "b"]) + + // UNIQUE (a, b) ON CONFLICT REPLACE, + t.uniqueKey(["a", "b"], onConflict: .replace) + + // FOREIGN KEY (a, b) REFERENCES parents(c, d), + t.foreignKey(["a", "b"], references: "parents") + + // CHECK (a + b < 10), + t.check(Column("a") + Column("b") < 10) + + // CHECK (a + b < 10) + t.check(sql: "a + b < 10") + + // Raw SQL constraints + t.constraint(sql: "CHECK (a + b < 10)") + t.constraint(literal: "CHECK (a + b < \(10))") +``` + +Reference: ``TableDefinition`` + +**Generated columns**: + +```swift + t.column("totalScore", .integer).generatedAs(sql: "score + bonus") + t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus")) +} +``` + +Reference: ``ColumnDefinition`` + +## Modify Tables + +SQLite lets you modify existing tables: + +```swift +// ALTER TABLE referer RENAME TO referrer +try db.rename(table: "referer", to: "referrer") + +// ALTER TABLE player ADD COLUMN hasBonus BOOLEAN +// ALTER TABLE player RENAME COLUMN url TO homeURL +// ALTER TABLE player DROP COLUMN score +try db.alter(table: "player") { t in + t.add(column: "hasBonus", .boolean) + t.rename(column: "url", to: "homeURL") + t.drop(column: "score") +} +``` + +Reference: ``TableAlteration`` + +> Note: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See for more information. + +## Drop Tables + +Drop tables with the ``Database/drop(table:)`` method: + +```swift +try db.drop(table: "obsolete") +``` + +## Create Indexes + +Create an index on a column: + +```swift +try db.create(table: "player") { t in + t.column("email", .text).unique() + t.column("score", .integer).indexed() +} +``` + +Create indexes on an existing table: + +```swift +// CREATE INDEX index_player_on_email ON player(email) +try db.create(indexOn: "player", columns: ["email"]) + +// CREATE UNIQUE INDEX index_player_on_email ON player(email) +try db.create(indexOn: "player", columns: ["email"], options: .unique) +``` + +Create indexes with a specific collation: + +```swift +// CREATE INDEX index_player_on_email ON player(email COLLATE NOCASE) +try db.create( + index: "index_player_on_email", + on: "player", + expressions: [Column("email").collating(.nocase)]) +``` + +Create indexes on expressions: + +```swift +// CREATE INDEX index_player_on_total_score ON player(score+bonus) +try db.create( + index: "index_player_on_total_score", + on: "player", + expressions: [Column("score") + Column("bonus")]) + +// CREATE INDEX index_player_on_country ON player(address ->> 'country') +try db.create( + index: "index_player_on_country", + on: "player", + expressions: [ + JSONColumn("address")["country"], + ]) +``` + +Unique constraints and unique indexes are somewhat different: don't miss the tip in below. + +## Topics + +### Database Tables + +- ``Database/alter(table:body:)`` +- ``Database/create(table:options:body:)`` +- ``Database/create(virtualTable:options:using:)`` +- ``Database/create(virtualTable:options:using:_:)`` +- ``Database/drop(table:)`` +- ``Database/dropFTS4SynchronizationTriggers(forTable:)`` +- ``Database/dropFTS5SynchronizationTriggers(forTable:)`` +- ``Database/rename(table:to:)`` +- ``Database/ColumnType`` +- ``Database/ConflictResolution`` +- ``Database/ForeignKeyAction`` +- ``TableAlteration`` +- ``TableDefinition`` +- ``TableOptions`` +- ``VirtualTableModule`` +- ``VirtualTableOptions`` + +### Database Views + +- ``Database/create(view:options:columns:as:)`` +- ``Database/create(view:options:columns:asLiteral:)`` +- ``Database/drop(view:)`` +- ``ViewOptions`` + +### Database Indexes + +- ``Database/create(indexOn:columns:options:condition:)`` +- ``Database/create(index:on:columns:options:condition:)`` +- ``Database/create(index:on:expressions:options:condition:)`` +- ``Database/drop(indexOn:columns:)`` +- ``Database/drop(index:)`` +- ``IndexOptions`` + +### Sunsetted Methods + +Those are legacy interfaces that are preserved for backwards compatibility. Their use is not recommended. + +- ``Database/create(index:on:columns:unique:ifNotExists:condition:)`` +- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)`` +- ``Database/create(virtualTable:ifNotExists:using:)`` +- ``Database/create(virtualTable:ifNotExists:using:_:)`` diff --git a/GRDB/Documentation.docc/DatabaseSchemaRecommendations.md b/GRDB/Documentation.docc/DatabaseSchemaRecommendations.md new file mode 100644 index 000000000..7aabe6429 --- /dev/null +++ b/GRDB/Documentation.docc/DatabaseSchemaRecommendations.md @@ -0,0 +1,334 @@ +# Database Schema Recommendations + +Recommendations for an ideal integration of the database schema with GRDB + +## Overview + +Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below. + +When those conventions are not applied, or not applicable, you will have to perform extra configurations. + +For recommendations specific to JSON columns, see . + +## Table names should be English, singular, and camelCased + +Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`: + +```swift +// RECOMMENDED +try db.create(table: "player") { t in + // table columns and constraints +} + +// REQUIRES EXTRA CONFIGURATION +try db.create(table: "players") { t in + // table columns and constraints +} +``` + +☝️ **If table names follow a different naming convention**, record types (see ) will need explicit table names: + +```swift +extension Player: TableRecord { + // Required because table name is not 'player' + static let databaseTableName = "players" +} + +extension PostalAddress: TableRecord { + // Required because table name is not 'postalAddress' + static let databaseTableName = "postal_address" +} + +extension Award: TableRecord { + // Required because table name is not 'award' + static let databaseTableName = "Auszeichnung" +} +``` + +[Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) will need explicit keys as well: + +```swift +extension Player: TableRecord { + // Explicit association key because the table name is not 'postalAddress' + static let postalAddress = belongsTo(PostalAddress.self, key: "postalAddress") + + // Explicit association key because the table name is not 'award' + static let awards = hasMany(Award.self, key: "awards") +} +``` + +As in the above example, make sure to-one associations use singular keys, and to-many associations use plural keys. + +## Column names should be camelCased + +Again, make them look like Swift identifiers: `fullName`, `score`, `creationDate`: + +```swift +// RECOMMENDED +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("fullName", .text).notNull() + t.column("score", .integer).notNull() + t.column("creationDate", .datetime).notNull() +} + +// REQUIRES EXTRA CONFIGURATION +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("full_name", .text).notNull() + t.column("score", .integer).notNull() + t.column("creation_date", .datetime).notNull() +} +``` + +☝️ **If the column names follow a different naming convention**, `Codable` record types will need an explicit `CodingKeys` enum: + +```swift +struct Player: Decodable, FetchableRecord { + var id: Int64 + var fullName: String + var score: Int + var creationDate: Date + + // Required CodingKeys customization because + // columns are not named like Swift properties + enum CodingKeys: String, CodingKey { + case id, fullName = "full_name", score, creationDate = "creation_date" + } +} +``` + +## Tables should have explicit primary keys + +A primary key uniquely identifies a row in a table. It is defined on one or several columns: + +```swift +// RECOMMENDED +try db.create(table: "player") { t in + // Auto-incremented primary key + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() +} + +try db.create(table: "team") { t in + // Single-column primary key + t.primaryKey("id", .text) + t.column("name", .text).notNull() +} + +try db.create(table: "membership") { t in + // Composite primary key + t.primaryKey { + t.belongsTo("player") + t.belongsTo("team") + } + t.column("role", .text).notNull() +} +``` + +Primary keys support record fetching methods such as ``FetchableRecord/fetchOne(_:id:)``, and persistence methods such as ``MutablePersistableRecord/update(_:onConflict:)`` or ``MutablePersistableRecord/delete(_:)``. + +See when you need to define a table that contains a single row. + +☝️ **If the database table does not define any explicit primary key**, identifying specific rows in this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html) in the matching record types: + +```swift +// A table without any explicit primary key +try db.create(table: "player") { t in + t.column("name", .text).notNull() + t.column("score", .integer).notNull() +} + +// The record type for the 'player' table' +struct Player: Codable { + // Uniquely identifies a player. + var rowid: Int64? + var name: String + var score: Int +} + +extension Player: FetchableRecord, MutablePersistableRecord { + // Required because the primary key + // is the hidden rowid column. + static var databaseSelection: [any SQLSelectable] { + [.allColumns, .rowID] + } + + // Update id upon successful insertion + mutating func didInsert(_ inserted: InsertionSuccess) { + rowid = inserted.rowID + } +} + +try dbQueue.read { db in + // SELECT *, rowid FROM player WHERE rowid = 1 + if let player = try Player.fetchOne(db, id: 1) { + // DELETE FROM player WHERE rowid = 1 + let deleted = try player.delete(db) + print(deleted) // true + } +} +``` + +## Single-column primary keys should be named 'id' + +This helps record types play well with the standard `Identifiable` protocol. + +```swift +// RECOMMENDED +try db.create(table: "player") { t in + t.primaryKey("id", .text) + t.column("name", .text).notNull() +} + +// REQUIRES EXTRA CONFIGURATION +try db.create(table: "player") { t in + t.primaryKey("uuid", .text) + t.column("name", .text).notNull() +} +``` +☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need a custom `CodingKeys` enum, or an extra property: + +```swift +// Custom coding keys +struct Player: Codable, Identifiable { + var id: String + var name: String + + // Required CodingKeys customization because + // columns are not named like Swift properties + enum CodingKeys: String, CodingKey { + case id = "uuid", name + } +} + +// Extra property +struct Player: Identifiable { + var uuid: String + var name: String + + // Required because the primary key column is not 'id' + var id: String { uuid } +} +``` + +## Unique keys should be supported by unique indexes + +Unique indexes makes sure SQLite prevents the insertion of conflicting rows: + +```swift +// RECOMMENDED +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.belongsTo("team").notNull() + t.column("position", .integer).notNull() + // Players must have distinct names + t.column("name", .text).unique() +} + +// One single player at any given position in a team +try db.create( + indexOn: "player", + columns: ["teamId", "position"], + options: .unique) +``` + +> Tip: SQLite does not support deferred unique indexes, and this creates undesired churn when you need to temporarily break them. This may happen, for example, when you want to reorder player positions in our above example. +> +> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, take care that only actual indexes can be dropped. Unique constraints created inside the table body can not: +> +> ```swift +> // Unique constraint on player(name) can not be dropped. +> try db.create(table: "player") { t in +> t.column("name", .text).unique() +> } +> +> // Unique index on team(name) can be dropped. +> try db.create(table: "team") { t in +> t.column("name", .text) +> } +> try db.create(indexOn: "team", columns: ["name"], options: .unique) +> ``` +> +> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See for the detailed procedure. + +☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error: + +```swift +try dbQueue.write { db in + // Fatal error: table player has no unique index on columns ... + let player = try Player.fetchOne(db, key: ["teamId": 42, "position": 1]) + try Player.deleteOne(db, key: ["name": "Arthur"]) + + // Use instead: + let player = try Player + .filter { $0.teamId == 42 && $0.position == 1 } + .fetchOne(db) + + try Player + .filter { $0.name == "Arthur" } + .deleteAll(db) +} +``` + +## Relations between tables should be supported by foreign keys + +[Foreign Keys](https://www.sqlite.org/foreignkeys.html) have SQLite enforce valid relationships between tables: + +```swift +try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + t.column("color", .text).notNull() +} + +// RECOMMENDED +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() + // A player must refer to an existing team + t.belongsTo("team").notNull() +} + +// REQUIRES EXTRA CONFIGURATION +try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text).notNull() + // No foreign key + t.column("teamId", .integer).notNull() +} +``` + +See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` for more information about the creation of foreign keys. + +GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema: + +```swift +extension Player: TableRecord { + static let team = belongsTo(Team.self) +} + +extension Team: TableRecord { + static let players = hasMany(Player.self) +} +``` + +See [Associations and the Database Schema](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#associations-and-the-database-schema) for more precise recommendations. + +☝️ **If a foreign key is not declared in the schema**, you will need to explicitly configure related associations: + +```swift +extension Player: TableRecord { + // Required configuration because the database does + // not declare any foreign key from players to their team. + static let teamForeignKey = ForeignKey(["teamId"]) + static let team = belongsTo(Team.self, + using: teamForeignKey) +} + +extension Team: TableRecord { + // Required configuration because the database does + // not declare any foreign key from players to their team. + static let players = hasMany(Player.self, + using: Player.teamForeignKey) +} +``` diff --git a/GRDB/Documentation.docc/DatabaseSharing.md b/GRDB/Documentation.docc/DatabaseSharing.md index 50b9569f4..29dd6b9b6 100644 --- a/GRDB/Documentation.docc/DatabaseSharing.md +++ b/GRDB/Documentation.docc/DatabaseSharing.md @@ -152,12 +152,11 @@ If several processes want to write in the database, configure the database pool ```swift var configuration = Configuration() -configuration.defaultTransactionKind = .immediate configuration.busyMode = .timeout(/* a TimeInterval */) let dbPool = try DatabasePool(path: ..., configuration: configuration) ``` -Both the `defaultTransactionKind` and `busyMode` are important for preventing `SQLITE_BUSY`. The `immediate` transaction kind prevents write transactions from overlapping, and the busy timeout has write transactions wait, instead of throwing `SQLITE_BUSY`, whenever another process is writing. +The busy timeout has write transactions wait, instead of throwing `SQLITE_BUSY`, whenever another process is writing. GRDB automatically opens all write transactions with the IMMEDIATE kind, preventing write transactions from overlapping. With such a setup, you will still get `SQLITE_BUSY` errors if the database remains locked by another process for longer than the specified timeout. You can catch those errors: diff --git a/GRDB/Documentation.docc/Extension/Configuration.md b/GRDB/Documentation.docc/Extension/Configuration.md index efb77b8a6..55f0d770d 100644 --- a/GRDB/Documentation.docc/Extension/Configuration.md +++ b/GRDB/Documentation.docc/Extension/Configuration.md @@ -90,7 +90,6 @@ do { ### Configuring GRDB Connections - ``allowsUnsafeTransactions`` -- ``defaultTransactionKind`` - ``label`` - ``maximumReaderCount`` - ``observesSuspensionNotifications`` diff --git a/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md b/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md index 9bfee067f..172cc169b 100644 --- a/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md +++ b/GRDB/Documentation.docc/Extension/DatabaseRegionObservation.md @@ -59,7 +59,7 @@ You can feed `DatabaseRegionObservation` with any type that conforms to the ``Da ```swift // Observe the score column of the 'player' table let observation = DatabaseRegionObservation( - tracking: Player.select(Column("score"))) + tracking: Player.select(\.score)) // Observe the 'score' column of the 'player' table let observation = DatabaseRegionObservation( diff --git a/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md b/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md index 97a52239a..e450d9fbd 100644 --- a/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md +++ b/GRDB/Documentation.docc/Extension/DatabaseValueConvertible.md @@ -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: diff --git a/GRDB/Documentation.docc/Extension/TransactionObserver.md b/GRDB/Documentation.docc/Extension/TransactionObserver.md index 9815e0852..72acd5e51 100644 --- a/GRDB/Documentation.docc/Extension/TransactionObserver.md +++ b/GRDB/Documentation.docc/Extension/TransactionObserver.md @@ -205,11 +205,8 @@ This extra API can be activated in two ways: 1. Use the GRDB.swift CocoaPod with a custom compilation option, as below. - It uses the system SQLite, which is compiled with `SQLITE_ENABLE_PREUPDATE_HOOK` support, but only on iOS 11.0+ (we don't know the minimum version of macOS, tvOS, watchOS): - ```ruby pod 'GRDB.swift' - platform :ios, '11.0' # or above post_install do |installer| installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target| diff --git a/GRDB/Documentation.docc/Extension/ValueObservation.md b/GRDB/Documentation.docc/Extension/ValueObservation.md index 2fbf4f9e1..a1d192e23 100644 --- a/GRDB/Documentation.docc/Extension/ValueObservation.md +++ b/GRDB/Documentation.docc/Extension/ValueObservation.md @@ -78,7 +78,7 @@ See below for the li By default, `ValueObservation` notifies a fresh value whenever any component of its fetched value is modified (any fetched column, row, etc.). This can be configured: see . -By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main dispatch queue, asynchronously. This can be configured: see . +By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main actor, asynchronously. This can be configured: see . By default, `ValueObservation` fetches a fresh value immediately after a change is committed in the database. In particular, modifying the database on the main thread triggers a fetch on the main thread as well. This behavior can be configured: see . @@ -98,40 +98,38 @@ The database observation stops when the cancellable returned by the `start` meth ## ValueObservation Scheduling -By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main dispatch queue, asynchronously: +By default, `ValueObservation` notifies the initial value, as well as eventual changes and errors, on the main actor, asynchronously: ```swift // The default scheduling let cancellable = observation.start(in: dbQueue) { error in - // Called asynchronously on the main dispatch queue + // This closure is MainActor-isolated. } onChange: { value in - // Called asynchronously on the main dispatch queue + // This closure is MainActor-isolated. print("Fresh value", value) } ``` You can change this behavior by adding a `scheduling` argument to the `start()` method. -For example, the ``ValueObservationScheduler/immediate`` scheduler notifies all values on the main dispatch queue, and notifies the first one immediately when the observation starts. +For example, the ``ValueObservationMainActorScheduler/immediate`` scheduler notifies all values on the main actor, and notifies the first one immediately when the observation starts. It is very useful in graphic applications, because you can configure views right away, without waiting for the initial value to be fetched eventually. You don't have to implement any empty or loading screen, or to prevent some undesired initial animation. Take care that the user interface is not responsive during the fetch of the first value, so only use the `immediate` scheduling for very fast database requests! -The `immediate` scheduling requires that the observation starts from the main dispatch queue (a fatal error is raised otherwise): - ```swift // Immediate scheduling notifies // the initial value right on subscription. let cancellable = observation .start(in: dbQueue, scheduling: .immediate) { error in - // Called on the main dispatch queue + // Called on the main actor } onChange: { value in - // Called on the main dispatch queue + // Called on the main actor print("Fresh value", value) } // <- Here "Fresh value" has already been printed. ``` -The other built-in scheduler ``ValueObservationScheduler/async(onQueue:)`` asynchronously schedules values and errors on the dispatch queue of your choice. Make sure you provide a serial queue, because a concurrent one such as `DispachQueue.global(qos: .default)` would mess with the ordering of fresh value notifications: +The ``ValueObservationScheduler/async(onQueue:)`` scheduler asynchronously schedules values and errors on the dispatch queue of your choice. Make sure you provide a serial dispatch queue, because a concurrent one such as `DispachQueue.global(qos: .default)` would mess with the ordering of fresh value notifications: ```swift // Async scheduling notifies all values @@ -146,9 +144,33 @@ let cancellable = observation } ``` +The ``ValueObservationScheduler/task`` scheduler asynchronously schedules values and errors on the cooperative thread pool. It is implicitly used when you turn a ValueObservation into an async sequence. You can specify it explicitly when you intend to consume a shared observation as an async sequence: + +```swift +do { + for try await players in observation.values(in: dbQueue) { + // Called on the cooperative thread pool + print("Fresh players", players) + } +} catch { + // Handle error +} + +let sharedObservation = observation.shared(in: dbQueue, scheduling: .task) +do { + for try await players in sharedObservation.values() { + // Called on the cooperative thread pool + print("Fresh players", players) + } +} catch { + // Handle error +} + +``` + As described above, the `scheduling` argument controls the execution of the change and error callbacks. You also have some control on the execution of the database fetch: -- With the `.immediate` scheduling, the initial fetch is always performed synchronously, on the main thread, when the observation starts, so that the initial value can be notified immediately. +- With the `.immediate` scheduling, the initial fetch is always performed synchronously, on the main actor, when the observation starts, so that the initial value can be notified immediately. - With the default `.async` scheduling, the initial fetch is always performed asynchronouly. It never blocks the main thread. @@ -192,7 +214,7 @@ Consider a scenario where you'd like to get a specific Player's row, but only wh let observation = ValueObservation.tracking( // Define the tracked database region // (the score column of the player with id 1) - region: Player.select(Column("score")).filter(id: 1), + region: Player.select(\.score).filter(id: 1), // Define what to fetch upon such change to the tracked region // (the player with id 1) fetch: { db in try Player.fetchOne(db, id: 1) } @@ -241,6 +263,10 @@ You can filter out undesired duplicate notifications with the ``removeDuplicates When needed, you can help GRDB optimize observations and reduce database contention: +> Important: **Keep your number of observations bounded.** +> +> In particular, do not observe independently all elements in a list. Instead, observe the whole list in a single observation. + > Tip: Stop observations when possible. > > For example, if a `UIViewController` needs to display database values, it can start the observation in `viewWillAppear`, and stop it in `viewWillDisappear`. @@ -289,11 +315,13 @@ When needed, you can help GRDB optimize observations and reduce database content ### Accessing Observed Values +- ``start(in:scheduling:onError:onChange:)-t62r`` +- ``start(in:scheduling:onError:onChange:)-4mqbs`` - ``publisher(in:scheduling:)`` -- ``start(in:scheduling:onError:onChange:)`` - ``values(in:scheduling:bufferingPolicy:)`` - ``DatabaseCancellable`` - ``ValueObservationScheduler`` +- ``ValueObservationMainActorScheduler`` ### Mapping Values @@ -313,6 +341,6 @@ When needed, you can help GRDB optimize observations and reduce database content - ``handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)`` - ``print(_:to:)`` -### Support +### Supporting Types - ``ValueReducer`` diff --git a/GRDB/Documentation.docc/JSON.md b/GRDB/Documentation.docc/JSON.md index 34fdba125..9b11e9873 100644 --- a/GRDB/Documentation.docc/JSON.md +++ b/GRDB/Documentation.docc/JSON.md @@ -27,8 +27,8 @@ try db.create(table: "player") { t in > Tip: When an application performs queries on values embedded inside JSON columns, indexes can help performance: > > ```swift -> // CREATE INDEX "player_on_country" -> // ON "player"("address" ->> 'country') +> // CREATE INDEX player_on_country +> // ON player(address ->> 'country') > try db.create( > index: "player_on_country", > on: "player", @@ -36,10 +36,16 @@ try db.create(table: "player") { t in > JSONColumn("address")["country"], > ]) > +> struct Player: FetchableRecord, TableRecord { +> enum Columns { +> static let address = JSONColumn("address") +> } +> } +> > // SELECT * FROM player -> // WHERE "address" ->> 'country' = 'DE' +> // WHERE address ->> 'country' = 'DE' > let germanPlayers = try Player -> .filter(JSONColumn("address")["country"] == "DE") +> .filter { $0.address["country"] == "DE" } > .fetchAll(db) > ``` @@ -92,10 +98,33 @@ struct Team: Codable { extension Team: FetchableRecord, PersistableRecord { // Support SQLite JSON functions and operators // by storing JSON data as database text: - static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text + static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy { + .text + } } ``` +> Tip: Conform your `Codable` property to `DatabaseValueConvertible` if you want to be able to filter on specific values of it: +> +> ```swift +> struct Address: Codable { ... } +> extension Address: DatabaseValueConvertible {} +> +> struct Player: FetchableRecord, TableRecord { +> enum Columns { +> static let address = JSONColumn("address") +> } +> } +> +> // SELECT * FROM player +> // WHERE address = '{"street": "...", "city": "...", "country": "..."}' +> let players = try Player +> .filter { $0.address == Address(...) } +> .fetchAll(db) +> ``` +> +> Take care that SQLite will compare strings, not JSON objects: white-space and key ordering matter. For this comparison to succeed, make sure that the database contains values that are formatted exactly like a serialized `Address`. + ## Manipulate JSON values at the database level [SQLite JSON functions and operators](https://www.sqlite.org/json1.html) are available starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+. @@ -129,7 +158,7 @@ The `->` and `->>` SQL operators are available on the ``SQLJSONExpressible`` pro ### Build new JSON values at the SQL level - ``Database/json(_:)`` -- ``Database/jsonArray(_:)-8xxe3`` +- ``Database/jsonArray(_:)-8p2p8`` - ``Database/jsonArray(_:)-469db`` - ``Database/jsonObject(_:)`` - ``Database/jsonQuote(_:)`` diff --git a/GRDB/Documentation.docc/Migrations.md b/GRDB/Documentation.docc/Migrations.md index ee7ed0f83..5c5f054f9 100644 --- a/GRDB/Documentation.docc/Migrations.md +++ b/GRDB/Documentation.docc/Migrations.md @@ -94,6 +94,26 @@ migrator.registerMigration("Create authors") { db in } ``` +#### How to Rename a Foreign Key + +When a migration **renames a foreign key**, make sure the migration runs with `.immediate` foreign key checks, in order to avoid database integrity problems: + +```swift +// IMPORTANT: rename foreign keys with immediate foreign key checks. +migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in + try db.rename(table: "team", to: "guild") + + try db.alter(table: "player") { t in + // Rename a foreign key + t.rename(column: "teamId", to: "guildId") + } +} +``` + +Note: migrations that run with `.immediate` foreign key checks can not be used to recreated database tables, as described below. When needed, define two migrations instead of one. + +#### How to Recreate a Database Table + When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table. For example: @@ -113,19 +133,39 @@ migrator.registerMigration("Add NOT NULL check on author.name") { db in The detailed sequence of operations for recreating a database table from a migration is: -1. When relevant, remember the format of all indexes, triggers, and views associated with table X. This information will be needed in steps 6 and 7 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`. +1. When relevant, remember the format of all indexes, triggers, and views associated with table `X`. This information will be needed in steps 6 below. One way to do this is to run the following statement and examine the output in the console: -2. Use `CREATE TABLE` to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course. + ```swift + try db.dumpSQL("SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'") + ``` -3. Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`. +2. Construct a new table `new_X` that is in the desired revised format of table `X`. Make sure that the name `new_X` does not collide with any existing table name, of course. -4. Drop the old table X: `DROP TABLE X`. + ```swift + try db.create(table: "new_X") { t in ... } + ``` -5. Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`. +3. Transfer content from `X` into `new_X` using a statement like: -6. When relevant, use `CREATE INDEX`, `CREATE TRIGGER`, and `CREATE VIEW` to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration. + ```swift + try db.execute(sql: "INSERT INTO new_X SELECT ... FROM X") + ``` -7. If any views refer to table X in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`. +4. Drop the old table `X`: + + ```swift + try db.drop(table: "X") + ``` + +5. Change the name of `new_X` to `X` using: + + ```swift + try db.rename(table: "new_X", to: "X") + ``` + +6. When relevant, reconstruct indexes, triggers, and views associated with table `X`. + +7. If any views refer to table `X` in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`. > Important: When recreating a table, be sure to follow the above procedure exactly, in the given order, or you might corrupt triggers, views, and foreign key constraints. > diff --git a/GRDB/Documentation.docc/QueryInterface.md b/GRDB/Documentation.docc/QueryInterface.md index f09b20f47..e16932441 100644 --- a/GRDB/Documentation.docc/QueryInterface.md +++ b/GRDB/Documentation.docc/QueryInterface.md @@ -8,9 +8,8 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R ## Topics -### Records +### Records Protocols -- ``Record`` - ``EncodableRecord`` - ``FetchableRecord`` - ``MutablePersistableRecord`` @@ -48,3 +47,7 @@ For an overview, see [Records](https://github.com/groue/GRDB.swift/blob/master/R - ``SQLSubqueryable`` - ``SQLOrderingTerm`` - ``SQLSelectable`` + +### Legacy Types + +- ``Record`` diff --git a/GRDB/Documentation.docc/RecordRecommendedPractices.md b/GRDB/Documentation.docc/RecordRecommendedPractices.md index 405bb8735..98ad99585 100644 --- a/GRDB/Documentation.docc/RecordRecommendedPractices.md +++ b/GRDB/Documentation.docc/RecordRecommendedPractices.md @@ -39,7 +39,7 @@ migrator.registerMigration("createLibrary") { db in try migrator.migrate(dbQueue) ``` -1. Our database tables follow the : table names are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`. +1. Our database tables follow the : table names are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`. 2. Each author has a unique id. 3. An author must have a name. 4. The country of an author is not always known. @@ -214,7 +214,7 @@ extension Book.Kind: DatabaseValueConvertible { } // Fetch all novels let novels = try dbQueue.read { db in - try Book.filter(Column("kind") == Book.Kind.novel).fetchAll(db) + try Book.filter { $0.kind == Book.Kind.novel }.fetchAll(db) } ``` @@ -297,7 +297,7 @@ Once we have record types that are able to read and write in the database, we'd ### Columns -Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum: +Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration, with the name `Columns`, nested inside the record type. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum: ```swift // HOW TO define columns for a Codable record @@ -310,13 +310,15 @@ extension Author { } ``` -For other record types, declare a plain `String` enum that conforms to the ``ColumnExpression`` protocol: +For non-Codable record types, declare columns with their names: ```swift // HOW TO define columns for a non-Codable record extension Author { - enum Columns: String, ColumnExpression { - case id, name, countryCode + enum Columns { + static let id = Column("id") + static let name = Column("name") + static let countryCode = Column("countryCode") } } ``` @@ -328,12 +330,12 @@ try dbQueue.read { db in // Fetch all authors, ordered by name, // in a localized case-insensitive fashion let sortedAuthors: [Author] = try Author.all() - .order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare)) + .order { $0.name.collating(.localizedCaseInsensitiveCompare) } .fetchAll(db) // Count French authors let frenchAuthorCount: Int = try Author.all() - .filter(Author.Columns.countryCode == "FR") + .filter { $0.countryCode == "FR" } .fetchCount(db) } ``` @@ -349,13 +351,12 @@ Define those methods in extensions of the ``DerivableRequest`` protocol, as belo extension DerivableRequest { /// Order authors by name, in a localized case-insensitive fashion func orderByName() -> Self { - let name = Author.Columns.name - return order(name.collating(.localizedCaseInsensitiveCompare)) + order { $0.name.collating(.localizedCaseInsensitiveCompare) } } /// Filters authors from a country func filter(countryCode: String) -> Self { - filter(Author.Columns.countryCode == countryCode) + filter { $0.countryCode == countryCode } } } @@ -363,13 +364,12 @@ extension DerivableRequest { extension DerivableRequest { /// Order books by title, in a localized case-insensitive fashion func orderByTitle() -> Self { - let title = Book.Columns.title - return order(title.collating(.localizedCaseInsensitiveCompare)) + order { $0.title.collating(.localizedCaseInsensitiveCompare) } } /// Filters books by kind func filter(kind: Book.Kind) -> Self { - filter(Book.Columns.kind == kind) + filter { $0.kind == kind } } } ``` @@ -393,16 +393,16 @@ Extensions to the `DerivableRequest` protocol can not change the type of request ```swift extension QueryInterfaceRequest { - // Selects author ids - func selectId() -> QueryInterfaceRequest { - selectPrimaryKey(as: Int64.self) + // Selects authors' name + func selectName() -> QueryInterfaceRequest { + select(\.name) } } -// The ids of Japanese authors -let ids: Set = try Author.all() +// The names of Japanese authors +let names: Set = try Author.all() .filter(countryCode: "JP") - .selectId() + .selectName() .fetchSet(db) ``` diff --git a/GRDB/Documentation.docc/RecordTimestamps.md b/GRDB/Documentation.docc/RecordTimestamps.md index 44fb2e5e8..32689234d 100644 --- a/GRDB/Documentation.docc/RecordTimestamps.md +++ b/GRDB/Documentation.docc/RecordTimestamps.md @@ -332,7 +332,7 @@ The full implementation of `TimestampedRecord` follows: ```swift /// A record type that tracks its creation and modification dates. See -/// +/// protocol TimestampedRecord: MutablePersistableRecord { var creationDate: Date? { get set } var modificationDate: Date? { get set } diff --git a/GRDB/Documentation.docc/SwiftConcurrency.md b/GRDB/Documentation.docc/SwiftConcurrency.md new file mode 100644 index 000000000..4fcfc15fa --- /dev/null +++ b/GRDB/Documentation.docc/SwiftConcurrency.md @@ -0,0 +1,233 @@ +# Swift Concurrency and GRDB + +How to best integrate GRDB and Swift Concurrency + +## Overview + +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. + +Application previews and tests prefer to use an in-memory ``DatabaseQueue`` connection. + +Both connection types provide the same database access methods: + +```swift +// Read +let playerCount = try await writer.read { db in + try Player.fetchCount(db) +} + +// Write +let newPlayerCount = try await writer.write { db in + try Player(name: "Arthur").insert(db) + return try Player.fetchCount(db) +} + +// Observe database changes +let observation = ValueObservation.tracking { db in + try Player.fetchAll(db) +} +for try await players in observation.values(in: writer) { + print("Fresh players", players) +} +``` + +`DatabaseQueue` serializes all database accesses, when `DatabasePool` allows parallel reads and writes. The common ``DatabaseWriter`` protocol provides the [SQLite isolation guarantees](https://www.sqlite.org/isolation.html) that abstract away the differences between the two connection types, without sacrificing data integrity. See the guide for more information. + +All safety guarantees of Swift 6 are enforced during database accesses. They are controlled by the language mode and level of concurrency checkings used by your application, as described in [Migrating to Swift 6] on swift.org. + +The following sections describe, with more details, how GRDB interacts with Swift Concurrency. + +- +- +- +- + +### Shorthand Closure Notation + +In the Swift 5 language mode, the compiler emits a warning when a database access is written with the shorthand closure notation: + +```swift +// Standard closure: +let count = try await writer.read { db in + try Player.fetchCount(db) +} + +// Shorthand notation: +// ⚠️ Converting non-sendable function value to '@Sendable (Database) +// throws -> Int' may introduce data races. +let count = try await writer.read(Player.fetchCount) +``` + +**You can remove this warning** by enabling [SE-0418: Inferring `Sendable` for methods and key path literals](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md), as below: + +- **Using Xcode** + + Set `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` to `YES` in the build settings of your target. + +- **In a SwiftPM package manifest** + + Enable the `InferSendableFromCaptures` upcoming feature: + + ```swift + .target( + name: "MyTarget", + swiftSettings: [ + .enableUpcomingFeature("InferSendableFromCaptures") + ] + ) + ``` + +This language feature is not enabled by default, because it can potentially [affect source compatibility](https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/sourcecompatibility#Inferring-Sendable-for-methods-and-key-path-literals). + +### Non-Sendable Configuration of Record Types + +In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when a record type specifies which columns it fetches from the database, with the ``TableRecord/databaseSelection-7iphs`` static property: + +```swift +extension Player: FetchableRecord, PersistableRecord { + // ❌ Static property 'databaseSelection' is not concurrency-safe + // because non-'Sendable' type '[any SQLSelectable]' + // may have shared mutable state + static let databaseSelection: [any SQLSelectable] = [ + Columns.id, Columns.name, Columns.score + ] + + enum Columns { + static let id = Column("id") + static let name = Column("name") + static let score = Column("score") + } +} +``` + +**To fix this error**, replace the stored property with a computed property: + +```swift +extension Player: FetchableRecord, PersistableRecord { + static var databaseSelection: [any SQLSelectable] { + [Columns.id, Columns.name, Columns.score] + } +} +``` + +### Non-Sendable Record Types + +In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when the application reads, writes, or observes a non-[`Sendable`](https://developer.apple.com/documentation/swift/sendable) type. + +By default, Swift classes are not Sendable. They are not thread-safe. With GRDB, record classes will typically trigger compiler diagnostics: + +```swift +// A non-Sendable record type +final class Player: Codable, Identifiable { + var id: Int64 + var name: String + var score: Int +} + +extension Player: FetchableRecord, PersistableRecord { } + +// ❌ Type 'Player' does not conform to the 'Sendable' protocol +let player = try await writer.read { db in + try Player.fetchOne(db, id: 42) +} + +// ❌ Capture of 'player' with non-sendable type 'Player' in a `@Sendable` closure +let player: Player +try await writer.read { db in + try player.insert(db) +} + +// ❌ Type 'Player' does not conform to the 'Sendable' protocol +let observation = ValueObservation.tracking { db in + try Player.fetchAll(db) +} +``` + +#### The solution + +The solution is to have the record type conform to `Sendable`. + +Since classes are difficult to make `Sendable`, the easiest way to is to replace classes with structs composed of `Sendable` properties: + +```swift +// This struct is Sendable +struct Player: Codable, Identifiable { + var id: Int64 + var name: String + var score: Int +} + +extension Player: FetchableRecord, PersistableRecord { } +``` + +You do not need to perform this refactoring right away: you can compile your application in the Swift 5 language mode, with minimal concurrency checkings. Take your time, and only when your application is ready, enable strict concurrency checkings or the Swift 6 language mode. + +#### FAQ: My application defines record classes, because… + +- **Question: My record types are subclasses of the built-in GRDB `Record` class.** + + Consider refactoring them as structs. The ``Record`` class was present in GRDB 1.0, in 2017. It has served its purpose. It is not `Sendable`, and its use is actively discouraged since GRDB 7. + +- **Question: I need a hierarchy of record classes because I use inheritance.** + + It should be possible to refactor the class hiearchy with Swift protocols. See for a practical example. Protocols make it possible to define records as structs. + +- **Question: I use the `@Observable` macro for my record types, and this macro requires a class.** + + A possible solution is to define two types: an `@Observable` class that drives your SwiftUI views, and a plain record struct for database work. An indirect advantage is that you will be able to make them evolve independently. + +- **Question: I use classes instead of structs because I monitored my application and classes have a lower CPU/memory footprint.** + + Now that's tricky. Please do not think the `Sendable` requirement is a whim: see the following questions. + +#### FAQ: How to make classes Sendable? + +- **Question: Can I mark my record classes as `@unchecked Sendable`?** + + Take care that all humans and machines who will read your code will think that the class is thread-safe, so make sure it really is. See the following questions. + +- **Question: I can use locks to make my class safely Sendable.** + + You can indeed put a lock on the whole instance, or on each individual property, or on multiple subgroups of properties, as needed by your application. Remember that structs are simpler, because they do not need locks and the compiler does all the hard work for you. + +- **Question: Can I make my record classes immutable?** + + Yes. Classes that can not be modified, made of constant `let` properties, are Sendable. Those immutable classes will not make it easy to modify the database, though. + +### Choosing between Synchronous and Asynchronous Database Accesses + +GRDB connections provide two versions of `read` and `write`, one that is synchronous, and one that is asynchronous. It might not be clear how to choose one or the other. + +```swift +// Synchronous database access +try writer.write { ... } + +// Asynchronous database access +await try writer.write { ... } +``` + +Synchronous database accesses are handy. They avoid undesired delays, flashes of missing content in the user interface, or `async` functions. Many apps access the database synchronously, even from the main thread, because SQLite is very fast. Of course, it is still possible to run slow queries: in this case, asynchronous accesses should be preferred. They are guaranteed to never block the main thread. + +Performing synchronous accesses from Swift Concurrency tasks is not incorrect. + +Some people recommend to avoid performing long blocking jobs on the cooperative thread pool, so you might want to follow this advice, and prefer to always `await` for the database in Swift tasks. In many occasions, the compiler will help you. For example, in the sample code below, the compiler requires the `await` keyword: + +```swift +func fetchPlayers() async throws -> [Player] { + try await writer.read(Player.fetchAll) +} +``` + +But there are some scenarios where the compiler misses opportunities to use `await`, such as inside closures ([swiftlang/swift#74459](https://github.com/swiftlang/swift/issues/74459)): + +```swift +Task { + // The compiler does not spot the missing `await` + let players = try writer.read(Player.fetchAll) +} +``` + +[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps +[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide/ diff --git a/GRDB/Documentation.docc/Transactions.md b/GRDB/Documentation.docc/Transactions.md index 56dedce47..469ffd953 100644 --- a/GRDB/Documentation.docc/Transactions.md +++ b/GRDB/Documentation.docc/Transactions.md @@ -142,16 +142,21 @@ try dbQueue.writeWithoutTransaction { db } ``` -Transactions can't be left opened unless the ``Configuration/allowsUnsafeTransactions`` configuration flag is set: +Make sure all transactions opened from a database access are committed or rollbacked from that same database access, because it is a programmer error to leave an opened transaction: ```swift -// fatal error: A transaction has been left opened at the end of a database access +// fatal error: A transaction has been left +// opened at the end of a database access. try dbQueue.writeWithoutTransaction { db in try db.execute(sql: "BEGIN TRANSACTION") // <- no commit or rollback } ``` +In particular, since commits may throw an error, make sure you perform a rollback when a commit fails. + +This restriction can be left with the ``Configuration/allowsUnsafeTransactions`` configuration flag. + It is possible to ask if a transaction is currently opened: ```swift @@ -214,6 +219,8 @@ SQLite savepoints are more than nested transactions, though. For advanced uses, SQLite supports [three kinds of transactions](https://www.sqlite.org/lang_transaction.html): deferred (the default), immediate, and exclusive. +By default, GRDB opens DEFERRED transaction for reads, and IMMEDIATE transactions for writes. + The transaction kind can be chosen for individual transaction: ```swift @@ -222,20 +229,3 @@ let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite") // BEGIN EXCLUSIVE TRANSACTION ... try dbQueue.inTransaction(.exclusive) { db in ... } ``` - -It is also possible to configure the ``Configuration/defaultTransactionKind``: - -```swift -var config = Configuration() -config.defaultTransactionKind = .immediate - -let dbQueue = try DatabaseQueue( - path: "/path/to/database.sqlite", - configuration: config) - -// BEGIN IMMEDIATE TRANSACTION ... -try dbQueue.write { db in ... } - -// BEGIN IMMEDIATE TRANSACTION ... -try dbQueue.inTransaction { db in ... } -``` diff --git a/GRDB/Dump/Database+Dump.swift b/GRDB/Dump/Database+Dump.swift index d4abfb653..8876b8cb7 100644 --- a/GRDB/Dump/Database+Dump.swift +++ b/GRDB/Dump/Database+Dump.swift @@ -45,7 +45,7 @@ extension Database { /// ``` /// /// - Parameters: - /// - request : The executed request. + /// - request: The executed request. /// - format: The output format. /// - stream: A stream for text output, which directs output to the /// console by default. @@ -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 diff --git a/GRDB/Dump/DatabaseReader+dump.swift b/GRDB/Dump/DatabaseReader+dump.swift index 55e829c89..cbe3e922d 100644 --- a/GRDB/Dump/DatabaseReader+dump.swift +++ b/GRDB/Dump/DatabaseReader+dump.swift @@ -38,7 +38,7 @@ extension DatabaseReader { /// ``` /// /// - Parameters: - /// - request : The executed request. + /// - request: The executed request. /// - format: The output format. /// - stream: A stream for text output, which directs output to the /// console by default. diff --git a/GRDB/Dump/DumpFormats/DebugDumpFormat.swift b/GRDB/Dump/DumpFormats/DebugDumpFormat.swift index 02f2f1130..b3ae31248 100644 --- a/GRDB/Dump/DumpFormats/DebugDumpFormat.swift +++ b/GRDB/Dump/DumpFormats/DebugDumpFormat.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// A format that prints one line per database row, suitable diff --git a/GRDB/Dump/DumpFormats/JSONDumpFormat.swift b/GRDB/Dump/DumpFormats/JSONDumpFormat.swift index 7e3bc61d5..d5bc8cb10 100644 --- a/GRDB/Dump/DumpFormats/JSONDumpFormat.swift +++ b/GRDB/Dump/DumpFormats/JSONDumpFormat.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// A format that prints database rows as a JSON array. @@ -43,9 +52,7 @@ public struct JSONDumpFormat: Sendable { public static var defaultEncoder: JSONEncoder { // This encoder MUST NOT CHANGE, because some people rely on this format. let encoder = JSONEncoder() - if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) { - encoder.outputFormatting = .withoutEscapingSlashes - } + encoder.outputFormatting = .withoutEscapingSlashes encoder.nonConformingFloatEncodingStrategy = .convertToString( positiveInfinity: "inf", negativeInfinity: "-inf", @@ -159,10 +166,7 @@ extension JSONDumpFormat: DumpFormat { private func formattedValue(_ value: some Encodable) throws -> String { let data = try encoder.encode(value) - guard let string = String(data: data, encoding: .utf8) else { - throw EncodingError.invalidValue(data, .init(codingPath: [], debugDescription: "Invalid JSON data")) - } - return string + return String(decoding: data, as: UTF8.self) } } diff --git a/GRDB/Dump/DumpFormats/LineDumpFormat.swift b/GRDB/Dump/DumpFormats/LineDumpFormat.swift index a0c9f9a1f..a71b05ca6 100644 --- a/GRDB/Dump/DumpFormats/LineDumpFormat.swift +++ b/GRDB/Dump/DumpFormats/LineDumpFormat.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// A format that prints one line per database value. All blob values diff --git a/GRDB/Dump/DumpFormats/ListDumpFormat.swift b/GRDB/Dump/DumpFormats/ListDumpFormat.swift index c256af4c8..dc7bfdb6c 100644 --- a/GRDB/Dump/DumpFormats/ListDumpFormat.swift +++ b/GRDB/Dump/DumpFormats/ListDumpFormat.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// A format that prints one line per database row. All blob values diff --git a/GRDB/Dump/DumpFormats/QuoteDumpFormat.swift b/GRDB/Dump/DumpFormats/QuoteDumpFormat.swift index 3c6ae5c17..3818c7c17 100644 --- a/GRDB/Dump/DumpFormats/QuoteDumpFormat.swift +++ b/GRDB/Dump/DumpFormats/QuoteDumpFormat.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + /// A format that prints one line per database row, formatting values /// as SQL literals. /// diff --git a/GRDB/Export.swift b/GRDB/Export.swift deleted file mode 100644 index f5aaed572..000000000 --- a/GRDB/Export.swift +++ /dev/null @@ -1,8 +0,0 @@ -// Export the underlying SQLite library -#if SWIFT_PACKAGE -@_exported import CSQLite -#elseif GRDBCIPHER -@_exported import SQLCipher -#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER -@_exported import SQLite3 -#endif diff --git a/GRDB/FTS/FTS3.swift b/GRDB/FTS/FTS3.swift index 80e677ae1..1e02e2b9f 100644 --- a/GRDB/FTS/FTS3.swift +++ b/GRDB/FTS/FTS3.swift @@ -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) @@ -47,7 +47,7 @@ public struct FTS3 { #elseif !GRDBCIPHER /// Remove diacritics from Latin script characters. This option matches /// the `remove_diacritics=2` tokenizer argument. - @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.27+ + @available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.27+ case remove #endif } @@ -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 diff --git a/GRDB/FTS/FTS3TokenizerDescriptor.swift b/GRDB/FTS/FTS3TokenizerDescriptor.swift index 14b2a3e81..403e946ab 100644 --- a/GRDB/FTS/FTS3TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS3TokenizerDescriptor.swift @@ -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) diff --git a/GRDB/FTS/FTS4.swift b/GRDB/FTS/FTS4.swift index ef9a54f5e..2848cb8f2 100644 --- a/GRDB/FTS/FTS4.swift +++ b/GRDB/FTS/FTS4.swift @@ -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 diff --git a/GRDB/FTS/FTS5.swift b/GRDB/FTS/FTS5.swift index a18da5a3f..26ad268f7 100644 --- a/GRDB/FTS/FTS5.swift +++ b/GRDB/FTS/FTS5.swift @@ -1,10 +1,19 @@ #if SQLITE_ENABLE_FTS5 +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + 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) @@ -60,7 +69,7 @@ public struct FTS5 { /// Remove diacritics from Latin script characters. This /// option matches the raw "remove_diacritics=2" tokenizer argument, /// available from SQLite 3.27.0 - @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.27+ + @available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.27+ case remove #endif } @@ -76,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 @@ -108,46 +117,6 @@ public struct FTS5 { /// /// Related SQLite documentation: public static func api(_ db: Database) -> UnsafePointer { - // Access to FTS5 is one of the rare SQLite api which was broken in - // SQLite 3.20.0+, for security reasons: - // - // Starting SQLite 3.20.0+, we need to use the new sqlite3_bind_pointer api. - // The previous way to access FTS5 does not work any longer. - // - // So let's see which SQLite version we are linked against: - - #if GRDBCUSTOMSQLITE || GRDBCIPHER - // GRDB is linked against SQLCipher or a custom SQLite build: SQLite 3.20.0 or more. - return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer) - #else - // GRDB is linked against the system SQLite. - if #available(iOS 12, macOS 10.14, tvOS 12, watchOS 5, *) { // SQLite 3.20+ - return api_v2(db, sqlite3_prepare_v3, sqlite3_bind_pointer) - } else { - return api_v1(db) - } - #endif - } - - private static func api_v1(_ db: Database) -> UnsafePointer { - guard let data = try! Data.fetchOne(db, sql: "SELECT fts5()") else { - fatalError("FTS5 is not available") - } - return data.withUnsafeBytes { - $0.bindMemory(to: UnsafePointer.self).first! - } - } - - // Technique given by Jordan Rose: - // https://forums.swift.org/t/c-interoperability-combinations-of-library-and-os-versions/14029/4 - private static func api_v2( - _ db: Database, - // swiftlint:disable:next line_length - _ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer?, CInt, CUnsignedInt, UnsafeMutablePointer?, UnsafeMutablePointer?>?) -> CInt, - // swiftlint:disable:next line_length - _ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt) - -> UnsafePointer - { var statement: SQLiteStatement? = nil var api: UnsafePointer? = nil let type: StaticString = "fts5_api_ptr" @@ -174,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) } @@ -250,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: @@ -258,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 @@ -305,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 diff --git a/GRDB/FTS/FTS5CustomTokenizer.swift b/GRDB/FTS/FTS5CustomTokenizer.swift index a294c35b3..370f1256c 100644 --- a/GRDB/FTS/FTS5CustomTokenizer.swift +++ b/GRDB/FTS/FTS5CustomTokenizer.swift @@ -1,4 +1,13 @@ #if SQLITE_ENABLE_FTS5 +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + /// A type that implements a custom tokenizer for the ``FTS5`` full-text engine. /// /// See [FTS5 Tokenizers](https://github.com/groue/GRDB.swift/blob/master/Documentation/FTS5Tokenizers.md) diff --git a/GRDB/FTS/FTS5Pattern.swift b/GRDB/FTS/FTS5Pattern.swift index 045a409a1..79c91c322 100644 --- a/GRDB/FTS/FTS5Pattern.swift +++ b/GRDB/FTS/FTS5Pattern.swift @@ -7,8 +7,9 @@ /// /// ### Creating Raw FTS5 Patterns /// +/// - ``init(rawPattern:allowedColumns:)`` /// - ``Database/makeFTS5Pattern(rawPattern:forTable:)`` -/// +/// /// ### Creating FTS5 Patterns from User Input /// /// - ``init(matchingAllPrefixesIn:)`` @@ -123,7 +124,25 @@ public struct FTS5Pattern: Sendable { try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"") } - init(rawPattern: String, allowedColumns: [String] = []) throws { + /// Creates a pattern from a raw pattern string. + /// + /// The pattern syntax is documented at + /// + /// For example: + /// + /// ```swift + /// // OK + /// let pattern = try FTS5Pattern(rawPattern: "and") + /// + /// // Throws an error: malformed MATCH expression: [AND] + /// let pattern = try FTS5Pattern(rawPattern: "AND") + /// ``` + /// + /// If the pattern tests for specific columns, you must pass those + /// columns in the `allowedColumns` parameter. + /// + /// - throws: A ``DatabaseError`` if the pattern has an invalid syntax. + public init(rawPattern: String, allowedColumns: [String] = []) throws { // Correctness above all: use SQLite to validate the pattern. // // Invalid patterns have SQLite return an error on the first diff --git a/GRDB/FTS/FTS5Tokenizer.swift b/GRDB/FTS/FTS5Tokenizer.swift index 8609a5ad7..e4aecc36f 100644 --- a/GRDB/FTS/FTS5Tokenizer.swift +++ b/GRDB/FTS/FTS5Tokenizer.swift @@ -1,4 +1,13 @@ #if SQLITE_ENABLE_FTS5 +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// A low-level SQLite function that lets FTS5Tokenizer notify tokens. diff --git a/GRDB/FTS/FTS5TokenizerDescriptor.swift b/GRDB/FTS/FTS5TokenizerDescriptor.swift index 9750aa76f..6eb1db585 100644 --- a/GRDB/FTS/FTS5TokenizerDescriptor.swift +++ b/GRDB/FTS/FTS5TokenizerDescriptor.swift @@ -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()) } diff --git a/GRDB/FTS/FTS5WrapperTokenizer.swift b/GRDB/FTS/FTS5WrapperTokenizer.swift index 16ac1e1f9..5851866be 100644 --- a/GRDB/FTS/FTS5WrapperTokenizer.swift +++ b/GRDB/FTS/FTS5WrapperTokenizer.swift @@ -1,4 +1,13 @@ #if SQLITE_ENABLE_FTS5 +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation /// Flags that tell SQLite how to register a token. diff --git a/GRDB/Fixits.swift b/GRDB/Fixits.swift index ed82d514d..174a5ce7e 100644 --- a/GRDB/Fixits.swift +++ b/GRDB/Fixits.swift @@ -1,171 +1,20 @@ -// Fixits for changes introduced by GRDB 6.0.0 +// Fixits for changes introduced by GRDB 7.0.0 // swiftlint:disable all -extension AggregatingRequest { - @available(*, unavailable, renamed: "groupWhenConnected(_:)") - func group(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self { preconditionFailure() } - - @available(*, unavailable, renamed: "havingWhenConnected(_:)") - func having(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self { preconditionFailure() } -} - -extension Association { - @available(*, unavailable, message: "limit(_:offset:) was not working properly, and was removed.") - public func limit(_ limit: Int, offset: Int? = nil) -> Self { preconditionFailure() } -} - -extension Database { - @available(*, unavailable, renamed: "cachedStatement(sql:)") - public func cachedSelectStatement(sql: String) throws -> Statement { preconditionFailure() } - - @available(*, unavailable, renamed: "cachedStatement(literal:)") - public func cachedSelectStatement(literal sqlLiteral: SQL) throws -> Statement { preconditionFailure() } - - @available(*, unavailable, renamed: "cachedStatement(sql:)") - public func cachedUpdateStatement(sql: String) throws -> Statement { preconditionFailure() } - - @available(*, unavailable, renamed: "cachedStatement(sql:)") - public func cachedUpdateStatement(literal sqlLiteral: SQL) throws -> Statement { preconditionFailure() } - - @available(*, unavailable, message: "Use Database.isSQLiteInternalTable(_:) static method instead.") - public func isSQLiteInternalTable(_ tableName: String) -> Bool { preconditionFailure() } - - @available(*, unavailable, message: "Use Database.isGRDBInternalTable(_:) static method instead.") - public func isGRDBInternalTable(_ tableName: String) -> Bool { preconditionFailure() } - - @available(*, unavailable, renamed: "makeStatement(sql:)") - public func makeSelectStatement(sql: String) throws -> Statement { preconditionFailure() } - - @available(*, unavailable, renamed: "makeStatement(literal:)") - public func makeSelectStatement(literal sqlLiteral: SQL) throws -> Statement { preconditionFailure() } - - @available(*, unavailable, renamed: "makeStatement(sql:)") - public func makeUpdateStatement(sql: String) throws -> Statement { preconditionFailure() } - - @available(*, unavailable, renamed: "makeStatement(literal:)") - public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> Statement { preconditionFailure() } - - @available(*, unavailable, renamed: "afterNextTransaction(onCommit:)") - public func afterNextTransactionCommit(_ closure: @escaping (Database) -> Void) { preconditionFailure() } -} - -extension DatabaseCursor { - @available(*, unavailable, message: "statement has been removed. You may use other cursor properties instead.") - public var statement: Statement { preconditionFailure() } -} - -extension DatabaseMigrator { - @available(*, unavailable, message: "The completion function now accepts one Result argument") - public func asyncMigrate( - _ writer: any DatabaseWriter, - completion: @escaping (Database, Error?) -> Void) - { preconditionFailure() } -} - -extension DatabaseRegionObservation { - @available(*, unavailable, message: "The extent of the observation is now controlled by the cancellable returned by DatabaseRegionObservation.start().") - public var extent: Database.TransactionObservationExtent { +extension Configuration { + @available(*, unavailable, message: "The default transaction kind is now automatically managed.") + public var defaultTransactionKind: Database.TransactionKind { get { preconditionFailure() } set { preconditionFailure() } } } -extension DatabaseUUIDEncodingStrategy { - @available(*, unavailable, renamed: "uppercaseString") - public static var string: Self { preconditionFailure() } -} +@available(*, unavailable, message: "DatabaseFuture has been removed.") +public class DatabaseFuture { } -@available(*, unavailable, message: "FastNullableDatabaseValueCursor has been replaced with FastDatabaseValueCursor") -typealias FastNullableDatabaseValueCursor = FastDatabaseValueCursor - -extension FilteredRequest { - @available(*, unavailable, renamed: "filterWhenConnected(with:)") - func filter(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self { preconditionFailure() } -} - -extension MutablePersistableRecord { - @available(*, unavailable, message: "Use persistence callbacks instead.") - public mutating func performInsert(_ db: Database) throws { preconditionFailure() } - - @available(*, unavailable, message: "Use persistence callbacks instead.") - public func performUpdate(_ db: Database, columns: Set) throws { preconditionFailure() } - - @available(*, unavailable, message: "Use persistence callbacks instead.") - public mutating func performSave(_ db: Database) throws { preconditionFailure() } - - @available(*, unavailable, message: "Use persistence callbacks instead.") - public func performDelete(_ db: Database) throws -> Bool { preconditionFailure() } - - @available(*, unavailable, message: "performExists(_:) was removed without any replacement.") - public func performExists(_ db: Database) throws -> Bool { preconditionFailure() } - - @available(*, unavailable, renamed: "updateChanges(_:modify:)") - public mutating func updateChanges(_ db: Database, with change: (inout Self) throws -> Void) throws -> Bool { preconditionFailure() } -} - -@available(*, unavailable, message: "NullableDatabaseValueCursor has been replaced with DatabaseValueCursor") -typealias NullableDatabaseValueCursor = DatabaseValueCursor - -extension OrderedRequest { - @available(*, unavailable, renamed: "orderWhenConnected(_:)") - func order(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self { preconditionFailure() } -} - -extension PersistableRecord { - @available(*, unavailable, message: "Use persistence callbacks instead.") - public func performInsert(_ db: Database) throws { preconditionFailure() } - - @available(*, unavailable, message: "Use persistence callbacks instead.") - public func performSave(_ db: Database) throws { preconditionFailure() } -} - -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) -extension QueryInterfaceRequest where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { - @available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.") - public func selectID() -> QueryInterfaceRequest { preconditionFailure() } -} - -extension Record { - @available(*, unavailable, message: "Record.copy() was removed without any replacement.") - final func copy() -> Self { preconditionFailure() } -} - -@available(*, unavailable, renamed: "Statement") -public typealias SelectStatement = Statement - -extension SelectionRequest { - @available(*, unavailable, renamed: "annotatedWhenConnected(with:)") - func annotated(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self { preconditionFailure() } - - @available(*, unavailable, renamed: "selectWhenConnected(_:)") - func select(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self { preconditionFailure() } -} - -@available(*, unavailable, renamed: "SQLExpression.AssociativeBinaryOperator") -public typealias SQLAssociativeBinaryOperator = SQLExpression.AssociativeBinaryOperator - -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) -extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { - @available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.") - public func selectID() -> QueryInterfaceRequest { preconditionFailure() } -} - -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) -extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { - @available(*, unavailable, message: "selectID() has been removed. You may use selectPrimaryKey(as:) instead.") - public static func selectID() -> QueryInterfaceRequest { preconditionFailure() } -} - -@available(*, unavailable, renamed: "Statement") -public typealias UpdateStatement = Statement - -extension ValueObservation { - @available(*, unavailable, renamed: "tracking(_:)") - public static func trackingVaryingRegion( - _ fetch: @escaping (Database) throws -> Value) - -> Self - where Reducer == ValueReducers.Fetch - { preconditionFailure() } +extension DatabasePool { + @available(*, unavailable, message: "concurrentRead has been removed. Use `asyncConcurrentRead` instead.") + public func concurrentRead(_ value: @escaping (Database) throws -> T) -> DatabaseFuture { preconditionFailure() } } // swiftlint:enable all diff --git a/GRDB/JSON/JSONColumn.swift b/GRDB/JSON/JSONColumn.swift index 8f778d2b5..1e29d3335 100644 --- a/GRDB/JSON/JSONColumn.swift +++ b/GRDB/JSON/JSONColumn.swift @@ -28,7 +28,7 @@ /// enum Columns { /// static let id = Column(CodingKeys.id) /// static let name = Column(CodingKeys.name) -/// static let address = JSONColumn(CodingKeys.address) // JSONColumn! +/// static let address = JSONColumn(CodingKeys.address) // JSONColumn /// } /// } /// @@ -43,7 +43,7 @@ /// // Fetch all country codes /// // SELECT DISTINCT address ->> 'countryCode' FROM player /// let countryCodes: [String] = try Player -/// .select(Player.Columns.address["countryCode"], as: String.self) +/// .select({ $0.address["countryCode"] }, as: String.self) /// .distinct() /// .fetchAll(db) /// } @@ -59,8 +59,10 @@ /// > extension Player: FetchableRecord, PersistableRecord { /// > // That's another valid way to define columns. /// > // But we don't have any JSONColumn this time. -/// > enum Columns: String, ColumnExpression { -/// > case id, name, address +/// > enum Columns { +/// > static let id = Column("id") +/// > static let name = Column("name") +/// > static let address = Column("address") /// > } /// > } /// > @@ -68,7 +70,7 @@ /// > // Fetch all country codes /// > // SELECT DISTINCT address ->> 'countryCode' FROM player /// > let countryCodes: [String] = try Player -/// > .select(Player.Columns.address.asJSON["countryCode"], as: String.self) +/// > .select({ $0.address.asJSON["countryCode"] }, as: String.self) /// > .distinct() /// > .fetchAll(db) /// > } diff --git a/GRDB/JSON/SQLJSONExpressible.swift b/GRDB/JSON/SQLJSONExpressible.swift index 991a5dd7d..71c3708fc 100644 --- a/GRDB/JSON/SQLJSONExpressible.swift +++ b/GRDB/JSON/SQLJSONExpressible.swift @@ -8,7 +8,7 @@ /// the SQL level. /// /// - When used in a JSON-building function such as -/// ``Database/jsonArray(_:)-8xxe3`` or ``Database/jsonObject(_:)``, +/// ``Database/jsonArray(_:)-8p2p8`` or ``Database/jsonObject(_:)``, /// they are parsed and interpreted as JSON, not as plain strings. /// /// To build a JSON value, create a ``JSONColumn``, or call the @@ -66,7 +66,7 @@ /// ## Build JSON objects and arrays from JSON values /// /// When used in a JSON-building function such as -/// ``Database/jsonArray(_:)-8xxe3`` or ``Database/jsonObject(_:)-5iswr``, +/// ``Database/jsonArray(_:)-8p2p8`` or ``Database/jsonObject(_:)-5iswr``, /// JSON values are parsed and interpreted as JSON, not as plain strings. /// /// In the example below, we can see how the `JSONColumn` is interpreted as @@ -135,12 +135,16 @@ extension SQLSpecificExpressible { /// For example: /// /// ```swift - /// let info = Column("info").asJSON + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = Column("info") + /// } + /// } /// /// // SELECT info ->> 'firstName' FROM player /// // → 'Arthur' /// let firstName = try Player - /// .select(info["firstName"], as: String.self) + /// .select({ $0.info.asJSON["firstName"] }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -157,18 +161,22 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT info ->> 'firstName' FROM player /// // → 'Arthur' /// let firstName = try Player - /// .select(info["firstName"], as: String.self) + /// .select({ $0.info["firstName"] }, as: String.self) /// .fetchOne(db) /// /// // SELECT info ->> 'address' FROM player /// // → '{"street":"Rue de Belleville","city":"Paris"}' /// let address = try Player - /// .select(info["address"], as: String.self) + /// .select({ $0.info["address"] }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -185,18 +193,22 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player /// // → 'Arthur' /// let firstName = try Player - /// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self) + /// .select({ $0.info.jsonExtract(atPath: "$.firstName") }, as: String.self) /// .fetchOne(db) /// /// // SELECT JSON_EXTRACT(info, '$.address') FROM player /// // → '{"street":"Rue de Belleville","city":"Paris"}' /// let address = try Player - /// .select(info.jsonExtract(atPath: "$.address"), as: String.self) + /// .select({ $0.info.jsonExtract(atPath: "$.address") }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -212,21 +224,25 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player /// // → '["Arthur","Miller"]' /// let nameComponents = try Player - /// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self) + /// .select({ $0.info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]) }, as: String.self) /// .fetchOne(db) /// ``` /// /// Related SQL documentation: /// /// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). - public func jsonExtract(atPaths paths: C) -> SQLExpression - where C: Collection, C.Element: SQLExpressible - { + public func jsonExtract( + atPaths paths: some Collection + ) -> SQLExpression { Database.jsonExtract(self, atPaths: paths) } @@ -235,18 +251,22 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT info -> 'firstName' FROM player /// // → '"Arthur"' /// let name = try Player - /// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self) + /// .select({ $0.info.jsonRepresentation(atPath: "firstName") }, as: String.self) /// .fetchOne(db) /// /// // SELECT info -> 'address' FROM player /// // → '{"street":"Rue de Belleville","city":"Paris"}' /// let name = try Player - /// .select(info.jsonRepresentation(atPath: "address"), as: String.self) + /// .select({ $0.info.jsonRepresentation(atPath: "address") }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -265,18 +285,22 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT info ->> 'firstName' FROM player /// // → 'Arthur' /// let firstName = try Player - /// .select(info["firstName"], as: String.self) + /// .select({ $0.info["firstName"] }, as: String.self) /// .fetchOne(db) /// /// // SELECT info ->> 'address' FROM player /// // → '{"street":"Rue de Belleville","city":"Paris"}' /// let address = try Player - /// .select(info["address"], as: String.self) + /// .select({ $0.info["address"] }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -294,25 +318,29 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player /// // → 'Arthur' /// let firstName = try Player - /// .select(info.jsonExtract(atPath: "$.firstName"), as: String.self) + /// .select({ $0.info.jsonExtract(atPath: "$.firstName") }, as: String.self) /// .fetchOne(db) /// /// // SELECT JSON_EXTRACT(info, '$.address') FROM player /// // → '{"street":"Rue de Belleville","city":"Paris"}' /// let address = try Player - /// .select(info.jsonExtract(atPath: "$.address"), as: String.self) + /// .select({ $0.info.jsonExtract(atPath: "$.address") }, as: String.self) /// .fetchOne(db) /// ``` /// /// Related SQL documentation: /// /// - parameter path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public func jsonExtract(atPath path: some SQLExpressible) -> SQLExpression { Database.jsonExtract(self, atPath: path) } @@ -322,22 +350,26 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player /// // → '["Arthur","Miller"]' /// let nameComponents = try Player - /// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self) + /// .select({ $0.info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]) }, as: String.self) /// .fetchOne(db) /// ``` /// /// Related SQL documentation: /// /// - parameter paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS - public func jsonExtract(atPaths paths: C) -> SQLExpression - where C: Collection, C.Element: SQLExpressible - { + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + public func jsonExtract( + atPaths paths: some Collection + ) -> SQLExpression { Database.jsonExtract(self, atPaths: paths) } @@ -346,18 +378,22 @@ extension SQLJSONExpressible { /// For example: /// /// ```swift - /// let info = JSONColumn("info") + /// struct Player: TableRecord { + /// enum Columns { + /// static let info = JSONColumn("info") + /// } + /// } /// /// // SELECT info -> 'firstName' FROM player /// // → '"Arthur"' /// let name = try Player - /// .select(info.jsonRepresentation(atPath: "firstName"), as: String.self) + /// .select({ $0.info.jsonRepresentation(atPath: "firstName") }, as: String.self) /// .fetchOne(db) /// /// // SELECT info -> 'address' FROM player /// // → '{"street":"Rue de Belleville","city":"Paris"}' /// let name = try Player - /// .select(info.jsonRepresentation(atPath: "address"), as: String.self) + /// .select({ $0.info.jsonRepresentation(atPath: "address") }, as: String.self) /// .fetchOne(db) /// ``` /// @@ -385,7 +421,7 @@ extension SQLJSONExpressible { // /// ``` // /// // /// Related SQLite documentation: -// @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS +// @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS // public func jsonPatch( // with patch: some SQLExpressible) // -> ColumnAssignment @@ -408,7 +444,7 @@ extension SQLJSONExpressible { // /// // /// - Parameters: // /// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). -// @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS +// @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS // public func jsonRemove(atPath path: some SQLExpressible) -> ColumnAssignment { // .init(columnName: name, value: Database.jsonRemove(self, atPath: path)) // } @@ -428,11 +464,10 @@ extension SQLJSONExpressible { // /// // /// - Parameters: // /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). -// @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS -// public func jsonRemove(atPaths paths: C) -// -> ColumnAssignment -// where C: Collection, C.Element: SQLExpressible -// { +// @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS +// public func jsonRemove( +// atPaths paths: some Collection +// ) -> ColumnAssignment { // .init(columnName: name, value: Database.jsonRemove(self, atPaths: paths)) // } // diff --git a/GRDB/JSON/SQLJSONFunctions.swift b/GRDB/JSON/SQLJSONFunctions.swift index 85122f289..406b7f1d4 100644 --- a/GRDB/JSON/SQLJSONFunctions.swift +++ b/GRDB/JSON/SQLJSONFunctions.swift @@ -1,4 +1,6 @@ #if GRDBCUSTOMSQLITE || GRDBCIPHER +// MARK: - JSON + extension Database { /// Validates and minifies a JSON string, with the `JSON` SQL function. /// @@ -24,9 +26,9 @@ extension Database { /// ``` /// /// Related SQLite documentation: - public static func jsonArray(_ values: C) -> SQLExpression - where C: Collection, C.Element: SQLExpressible - { + public static func jsonArray( + _ values: some Collection + ) -> SQLExpression { .function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression)) } @@ -40,9 +42,9 @@ extension Database { /// ``` /// /// Related SQLite documentation: - public static func jsonArray(_ values: C) -> SQLExpression - where C: Collection, C.Element == any SQLExpressible - { + public static func jsonArray( + _ values: some Collection + ) -> SQLExpression { .function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression)) } @@ -130,10 +132,10 @@ extension Database { /// - Parameters: /// - value: A JSON value. /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). - public static func jsonExtract(_ value: some SQLExpressible, atPaths paths: C) - -> SQLExpression - where C: Collection, C.Element: SQLExpressible - { + public static func jsonExtract( + _ value: some SQLExpressible, + atPaths paths: some Collection + ) -> SQLExpression { .function("JSON_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression)) } @@ -152,13 +154,10 @@ extension Database { /// - 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 jsonInsert( + public static func jsonInsert( _ value: some SQLExpressible, - _ assignments: C) - -> SQLExpression - where C: Collection, - C.Element == (key: String, value: any SQLExpressible) - { + _ assignments: some Collection<(key: String, value: any SQLExpressible)> + ) -> SQLExpression { .function("JSON_INSERT", [value.sqlExpression] + assignments.flatMap { [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] }) @@ -179,13 +178,10 @@ extension Database { /// - 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 jsonReplace( + public static func jsonReplace( _ value: some SQLExpressible, - _ assignments: C) - -> SQLExpression - where C: Collection, - C.Element == (key: String, value: any SQLExpressible) - { + _ assignments: some Collection<(key: String, value: any SQLExpressible)> + ) -> SQLExpression { .function("JSON_REPLACE", [value.sqlExpression] + assignments.flatMap { [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] }) @@ -206,13 +202,10 @@ extension Database { /// - 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 jsonSet( + public static func jsonSet( _ value: some SQLExpressible, - _ assignments: C) - -> SQLExpression - where C: Collection, - C.Element == (key: String, value: any SQLExpressible) - { + _ assignments: some Collection<(key: String, value: any SQLExpressible)> + ) -> SQLExpression { .function("JSON_SET", [value.sqlExpression] + assignments.flatMap { [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] }) @@ -241,11 +234,9 @@ extension Database { /// ``` /// /// Related SQLite documentation: - public static func jsonObject(_ elements: C) - -> SQLExpression - where C: Collection, - C.Element == (key: String, value: any SQLExpressible) - { + public static func jsonObject( + _ elements: some Collection<(key: String, value: any SQLExpressible)> + ) -> SQLExpression { .function("JSON_OBJECT", elements.flatMap { [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] }) @@ -301,10 +292,10 @@ extension Database { /// - Parameters: /// - value: A JSON value. /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). - public static func jsonRemove(_ value: some SQLExpressible, atPaths paths: C) - -> SQLExpression - where C: Collection, C.Element: SQLExpressible - { + public static func jsonRemove( + _ value: some SQLExpressible, + atPaths paths: some Collection + ) -> SQLExpression { .function("JSON_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression)) } @@ -350,8 +341,19 @@ extension Database { /// ``` /// /// Related SQLite documentation: - 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 . + 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. @@ -376,14 +378,21 @@ extension Database { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// static let score = Column("score") + /// } + /// } + /// /// // SELECT JSON_GROUP_ARRAY(name) FROM player - /// Player.select(Database.jsonGroupArray(Column("name"))) + /// Player.select { Database.jsonGroupArray($0.name) } /// /// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player - /// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0)) + /// Player.select { Database.jsonGroupArray($0.name, filter: $0.score > 0) } /// /// // SELECT JSON_GROUP_ARRAY(name ORDER BY name) FROM player - /// Player.select(Database.jsonGroupArray(Column("name"), orderBy: Column("name"))) + /// Player.select { Database.jsonGroupArray($0.name, orderBy: $0.name) } /// ``` /// /// Related SQLite documentation: @@ -405,16 +414,27 @@ extension Database { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// static let score = Column("score") + /// } + /// } + /// /// // SELECT JSON_GROUP_OBJECT(name, score) FROM player - /// Player.select(Database.jsonGroupObject( - /// key: Column("name"), - /// value: Column("score"))) + /// Player.select { + /// Database.jsonGroupObject( + /// key: $0.name, + /// value: $0.score) + /// } /// /// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player - /// Player.select(Database.jsonGroupObject( - /// key: Column("name"), - /// value: Column("score"), - /// filter: Column("score") > 0)) + /// Player.select { + /// Database.jsonGroupObject( + /// key: $0.name, + /// value: $0.score, + /// filter: $0.score > 0) + /// } /// ``` /// /// Related SQLite documentation: @@ -430,7 +450,347 @@ 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: + 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: + public static func jsonbArray( + _ values: some Collection + ) -> 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: + public static func jsonbArray( + _ values: some Collection + ) -> 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: + /// + /// - 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: + /// + /// - 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 + ) -> 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: + /// + /// - 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: + /// + /// - 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: + /// + /// - 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: + 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: + 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: + /// + /// - 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: + /// + /// - 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 + ) -> SQLExpression { + .function("JSONB_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression)) + } + + /// The `JSONB_GROUP_ARRAY` SQL function. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// static let score = Column("score") + /// } + /// } + /// + /// // SELECT JSONB_GROUP_ARRAY(name) FROM player + /// Player.select { Database.jsonbGroupArray($0.name) } + /// + /// // SELECT JSONB_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player + /// Player.select { Database.jsonbGroupArray($0.name, filter: $0.score > 0) } + /// + /// // SELECT JSONB_GROUP_ARRAY(name ORDER BY name) FROM player + /// Player.select { Database.jsonbGroupArray($0.name, orderBy: $0.name) } + /// ``` + /// + /// Related SQLite documentation: + 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 + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// static let score = Column("score") + /// } + /// } + /// + /// // SELECT JSONB_GROUP_OBJECT(name, score) FROM player + /// Player.select { + /// Database.jsonbGroupObject( + /// key: $0.name, + /// value: $0.score) + /// } + /// + /// // SELECT JSONB_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player + /// Player.select { + /// Database.jsonbGroupObject( + /// key: $0.name, + /// value: $0.score, + /// filter: $0.score > 0) + /// } + /// ``` + /// + /// Related SQLite documentation: + 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. /// @@ -442,7 +802,7 @@ extension Database { /// ``` /// /// Related SQLite documentation: - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public static func json(_ value: some SQLExpressible) -> SQLExpression { .function("JSON", [value.sqlExpression]) } @@ -457,10 +817,10 @@ extension Database { /// ``` /// /// Related SQLite documentation: - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS - public static func jsonArray(_ values: C) -> SQLExpression - where C: Collection, C.Element: SQLExpressible - { + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + public static func jsonArray( + _ values: some Collection + ) -> SQLExpression { .function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression)) } @@ -474,10 +834,10 @@ extension Database { /// ``` /// /// Related SQLite documentation: - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS - public static func jsonArray(_ values: C) -> SQLExpression - where C: Collection, C.Element == any SQLExpressible - { + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + public static func jsonArray( + _ values: some Collection + ) -> SQLExpression { .function("JSON_ARRAY", values.map(\.sqlExpression.jsonBuilderExpression)) } @@ -492,7 +852,7 @@ extension Database { /// ``` /// /// Related SQLite documentation: - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public static func jsonArrayLength(_ value: some SQLExpressible) -> SQLExpression { .function("JSON_ARRAY_LENGTH", [value.sqlExpression]) } @@ -512,7 +872,7 @@ extension Database { /// - Parameters: /// - value: A JSON array. /// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public static func jsonArrayLength( _ value: some SQLExpressible, atPath path: some SQLExpressible) @@ -535,7 +895,7 @@ extension Database { /// - Parameters: /// - value: A JSON value. /// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public static func jsonExtract(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression { .function("JSON_EXTRACT", [value.sqlExpression, path.sqlExpression]) } @@ -554,11 +914,11 @@ extension Database { /// - Parameters: /// - value: A JSON value. /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS - public static func jsonExtract(_ value: some SQLExpressible, atPaths paths: C) - -> SQLExpression - where C: Collection, C.Element: SQLExpressible - { + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + public static func jsonExtract( + _ value: some SQLExpressible, + atPaths paths: some Collection + ) -> SQLExpression { .function("JSON_EXTRACT", [value.sqlExpression] + paths.map(\.sqlExpression)) } @@ -577,14 +937,11 @@ extension Database { /// - value: A JSON value. /// - assignments: A collection of key/value pairs, where keys are /// [JSON paths](https://www.sqlite.org/json1.html#path_arguments). - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS - public static func jsonInsert( + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + public static func jsonInsert( _ value: some SQLExpressible, - _ assignments: C) - -> SQLExpression - where C: Collection, - C.Element == (key: String, value: any SQLExpressible) - { + _ assignments: some Collection<(key: String, value: any SQLExpressible)> + ) -> SQLExpression { .function("JSON_INSERT", [value.sqlExpression] + assignments.flatMap { [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] }) @@ -605,14 +962,11 @@ extension Database { /// - value: A JSON value. /// - assignments: A collection of key/value pairs, where keys are /// [JSON paths](https://www.sqlite.org/json1.html#path_arguments). - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS - public static func jsonReplace( + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + public static func jsonReplace( _ value: some SQLExpressible, - _ assignments: C) - -> SQLExpression - where C: Collection, - C.Element == (key: String, value: any SQLExpressible) - { + _ assignments: some Collection<(key: String, value: any SQLExpressible)> + ) -> SQLExpression { .function("JSON_REPLACE", [value.sqlExpression] + assignments.flatMap { [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] }) @@ -633,14 +987,11 @@ extension Database { /// - value: A JSON value. /// - assignments: A collection of key/value pairs, where keys are /// [JSON paths](https://www.sqlite.org/json1.html#path_arguments). - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS - public static func jsonSet( + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + public static func jsonSet( _ value: some SQLExpressible, - _ assignments: C) - -> SQLExpression - where C: Collection, - C.Element == (key: String, value: any SQLExpressible) - { + _ assignments: some Collection<(key: String, value: any SQLExpressible)> + ) -> SQLExpression { .function("JSON_SET", [value.sqlExpression] + assignments.flatMap { [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] }) @@ -669,12 +1020,10 @@ extension Database { /// ``` /// /// Related SQLite documentation: - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS - public static func jsonObject(_ elements: C) - -> SQLExpression - where C: Collection, - C.Element == (key: String, value: any SQLExpressible) - { + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + public static func jsonObject( + _ elements: some Collection<(key: String, value: any SQLExpressible)> + ) -> SQLExpression { .function("JSON_OBJECT", elements.flatMap { [$0.key.sqlExpression, $0.value.sqlExpression.jsonBuilderExpression] }) @@ -690,7 +1039,7 @@ extension Database { /// ``` /// /// Related SQLite documentation: - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public static func jsonPatch( _ value: some SQLExpressible, with patch: some SQLExpressible) @@ -712,8 +1061,8 @@ extension Database { /// /// - Parameters: /// - value: A JSON value. - /// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + /// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public static func jsonRemove(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression { .function("JSON_REMOVE", [value.sqlExpression, path.sqlExpression]) } @@ -732,11 +1081,11 @@ extension Database { /// - Parameters: /// - value: A JSON value. /// - paths: A collection of [JSON paths](https://www.sqlite.org/json1.html#path_arguments). - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS - public static func jsonRemove(_ value: some SQLExpressible, atPaths paths: C) - -> SQLExpression - where C: Collection, C.Element: SQLExpressible - { + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + public static func jsonRemove( + _ value: some SQLExpressible, + atPaths paths: some Collection + ) -> SQLExpression { .function("JSON_REMOVE", [value.sqlExpression] + paths.map(\.sqlExpression)) } @@ -750,7 +1099,7 @@ extension Database { /// ``` /// /// Related SQLite documentation: - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public static func jsonType(_ value: some SQLExpressible) -> SQLExpression { .function("JSON_TYPE", [value.sqlExpression]) } @@ -768,8 +1117,8 @@ extension Database { /// /// - Parameters: /// - value: A JSON value. - /// - paths: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + /// - path: A [JSON path](https://www.sqlite.org/json1.html#path_arguments). + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public static func jsonType(_ value: some SQLExpressible, atPath path: some SQLExpressible) -> SQLExpression { .function("JSON_TYPE", [value.sqlExpression, path.sqlExpression]) } @@ -784,7 +1133,7 @@ extension Database { /// ``` /// /// Related SQLite documentation: - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public static func jsonIsValid(_ value: some SQLExpressible) -> SQLExpression { .function("JSON_VALID", [value.sqlExpression]) } @@ -802,7 +1151,7 @@ extension Database { /// ``` /// /// Related SQLite documentation: - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public static func jsonQuote(_ value: some SQLExpressible) -> SQLExpression { .function("JSON_QUOTE", [value.sqlExpression.jsonBuilderExpression]) } @@ -812,15 +1161,22 @@ extension Database { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// static let score = Column("score") + /// } + /// } + /// /// // SELECT JSON_GROUP_ARRAY(name) FROM player - /// Player.select(Database.jsonGroupArray(Column("name"))) + /// Player.select { Database.jsonGroupArray($0.name) } /// /// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player - /// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0)) + /// Player.select { Database.jsonGroupArray($0.name, filter: $0.score > 0) } /// ``` /// /// Related SQLite documentation: - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public static func jsonGroupArray( _ value: some SQLExpressible, filter: (any SQLSpecificExpressible)? = nil) @@ -837,20 +1193,31 @@ extension Database { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// static let score = Column("score") + /// } + /// } + /// /// // SELECT JSON_GROUP_OBJECT(name, score) FROM player - /// Player.select(Database.jsonGroupObject( - /// key: Column("name"), - /// value: Column("score"))) + /// Player.select { + /// Database.jsonGroupObject( + /// key: $0.name, + /// value: $0.score) + /// } /// /// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player - /// Player.select(Database.jsonGroupObject( - /// key: Column("name"), - /// value: Column("score"), - /// filter: Column("score") > 0)) + /// Player.select { + /// Database.jsonGroupObject( + /// key: $0.name, + /// value: $0.score, + /// filter: $0.score > 0) + /// } /// ``` /// /// Related SQLite documentation: - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS public static func jsonGroupObject( key: some SQLExpressible, value: some SQLExpressible, diff --git a/GRDB/Migration/DatabaseMigrator.swift b/GRDB/Migration/DatabaseMigrator.swift index f4de96c69..3ab11763c 100644 --- a/GRDB/Migration/DatabaseMigrator.swift +++ b/GRDB/Migration/DatabaseMigrator.swift @@ -40,7 +40,11 @@ import Foundation /// - ``completedMigrations(_:)`` /// - ``hasBeenSuperseded(_:)`` /// - ``hasCompletedMigrations(_:)`` -public struct DatabaseMigrator { +/// +/// ### Detecting Schema Changes +/// +/// - ``hasSchemaChanges(_:)`` +public struct DatabaseMigrator: Sendable { /// Controls how a migration handle foreign keys constraints. public enum ForeignKeyChecks: Sendable { /// The migration runs with disabled foreign keys. @@ -102,6 +106,8 @@ public struct DatabaseMigrator { /// migrator.eraseDatabaseOnSchemaChange = true /// #endif /// ``` + /// + /// See also ``hasSchemaChanges(_:)``. public var eraseDatabaseOnSchemaChange = false private var defersForeignKeyChecks = true private var _migrations: [Migration] = [] @@ -207,7 +213,7 @@ public struct DatabaseMigrator { public mutating func registerMigration( _ identifier: String, foreignKeyChecks: ForeignKeyChecks = .deferred, - migrate: @escaping (Database) throws -> Void) + migrate: @escaping @Sendable (Database) throws -> Void) { let migrationChecks: Migration.ForeignKeyChecks switch foreignKeyChecks { @@ -230,7 +236,7 @@ public struct DatabaseMigrator { /// /// - parameter writer: A DatabaseWriter. /// - throws: The error thrown by the first failed migration. - public func migrate(_ writer: some DatabaseWriter) throws { + public func migrate(_ writer: any DatabaseWriter) throws { guard let lastMigration = _migrations.last else { return } @@ -249,7 +255,7 @@ public struct DatabaseMigrator { /// - parameter writer: A DatabaseWriter. /// - parameter targetIdentifier: A migration identifier. /// - throws: The error thrown by the first failed migration. - public func migrate(_ writer: some DatabaseWriter, upTo targetIdentifier: String) throws { + public func migrate(_ writer: any DatabaseWriter, upTo targetIdentifier: String) throws { try writer.barrierWriteWithoutTransaction { db in try migrate(db, upTo: targetIdentifier) } @@ -263,8 +269,8 @@ public struct DatabaseMigrator { /// database, or the failure that prevented the migrations /// from succeeding. public func asyncMigrate( - _ writer: some DatabaseWriter, - completion: @escaping (Result) -> Void) + _ writer: any DatabaseWriter, + completion: @escaping @Sendable (Result) -> Void) { writer.asyncBarrierWriteWithoutTransaction { dbResult in do { @@ -279,6 +285,96 @@ public struct DatabaseMigrator { } } + // MARK: - Detecting Schema Changes + + /// Returns a boolean value indicating whether the migrator detects a + /// change in the definition of migrations. + /// + /// The result is true if one of those conditions is met: + /// + /// - A migration has been removed, or renamed. + /// - There exists any difference in the `sqlite_master` table, which + /// contains the SQL used to create database tables, indexes, + /// triggers, and views. + /// + /// This method supports the ``eraseDatabaseOnSchemaChange`` option. + /// When `eraseDatabaseOnSchemaChange` does not exactly fit your + /// needs, you can implement it manually as below: + /// + /// ```swift + /// #if DEBUG + /// // Speed up development by nuking the database when migrations change + /// if dbQueue.read(migrator.hasSchemaChanges) { + /// try dbQueue.erase() + /// // Perform other needed logic + /// } + /// #endif + /// try migrator.migrate(dbQueue) + /// ``` + /// + public func hasSchemaChanges(_ db: Database) throws -> Bool { + let appliedIdentifiers = try appliedIdentifiers(db) + let knownIdentifiers = Set(_migrations.map { $0.identifier }) + if !appliedIdentifiers.isSubset(of: knownIdentifiers) { + // Database contains an unknown migration + return true + } + + if let lastAppliedIdentifier = _migrations + .map(\.identifier) + .last(where: { appliedIdentifiers.contains($0) }) + { + // Some migrations were already applied. + // + // Let's migrate a temporary database up to the same + // level, and compare the database schemas. If they + // differ, we'll return true + let tmpSchema = try { + // Make sure the temporary database is configured + // just as the migrated database + var tmpConfig = db.configuration + tmpConfig.readonly = false // We need write access + tmpConfig.targetQueue = nil // Avoid deadlocks + tmpConfig.writeTargetQueue = nil // Avoid deadlocks + tmpConfig.label = "GRDB.DatabaseMigrator.temporary" + + // Create the temporary database on disk, just in + // case migrations would involve a lot of data. + // + // SQLite supports temporary on-disk databases, but + // those are not guaranteed to accept the + // preparation functions provided by the user. + // + // See https://github.com/groue/GRDB.swift/issues/931 + // for an issue created by such databases. + // + // So let's create a "regular" temporary database: + let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory()) + .appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString) + defer { + try? FileManager().removeItem(at: tmpURL) + } + let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig) + return try tmpDatabase.writeWithoutTransaction { db in + try runMigrations(db, upTo: lastAppliedIdentifier) + return try db.schema(.main) + } + }() + + // Only compare user objects + func isUserObject(_ object: SchemaObject) -> Bool { + !Database.isSQLiteInternalTable(object.name) && !Database.isGRDBInternalTable(object.name) + } + let tmpUserSchema = tmpSchema.filter(isUserObject) + let userSchema = try db.schema(.main).filter(isUserObject) + if userSchema != tmpUserSchema { + return true + } + } + + return false + } + // MARK: - Querying Migrations /// The list of registered migration identifiers, in the same order as they @@ -409,69 +505,9 @@ public struct DatabaseMigrator { if eraseDatabaseOnSchemaChange { var needsErase = false try db.inTransaction(.deferred) { - let appliedIdentifiers = try appliedIdentifiers(db) - let knownIdentifiers = Set(_migrations.map { $0.identifier }) - if !appliedIdentifiers.isSubset(of: knownIdentifiers) { - // Database contains an unknown migration - needsErase = true - return .commit - } - - if let lastAppliedIdentifier = _migrations - .map(\.identifier) - .last(where: { appliedIdentifiers.contains($0) }) - { - // Some migrations were already applied. - // - // Let's migrate a temporary database up to the same - // level, and compare the database schemas. If they - // differ, we'll erase the database. - let tmpSchema = try { - // Make sure the temporary database is configured - // just as the migrated database - var tmpConfig = db.configuration - tmpConfig.targetQueue = nil // Avoid deadlocks - tmpConfig.writeTargetQueue = nil // Avoid deadlocks - tmpConfig.label = "GRDB.DatabaseMigrator.temporary" - - // Create the temporary database on disk, just in - // case migrations would involve a lot of data. - // - // SQLite supports temporary on-disk databases, but - // those are not guaranteed to accept the - // preparation functions provided by the user. - // - // See https://github.com/groue/GRDB.swift/issues/931 - // for an issue created by such databases. - // - // So let's create a "regular" temporary database: - let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory()) - .appendingPathComponent(ProcessInfo.processInfo.globallyUniqueString) - defer { - try? FileManager().removeItem(at: tmpURL) - } - let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig) - return try tmpDatabase.writeWithoutTransaction { db in - try runMigrations(db, upTo: lastAppliedIdentifier) - return try db.schema(.main) - } - }() - - // Only compare user objects - func isUserObject(_ object: SchemaObject) -> Bool { - !Database.isSQLiteInternalTable(object.name) && !Database.isGRDBInternalTable(object.name) - } - let tmpUserSchema = tmpSchema.filter(isUserObject) - let userSchema = try db.schema(.main).filter(isUserObject) - if userSchema != tmpUserSchema { - needsErase = true - return .commit - } - } - + needsErase = try hasSchemaChanges(db) return .commit } - if needsErase { try db.erase() } @@ -496,10 +532,9 @@ extension DatabaseMigrator { /// - parameter writer: A DatabaseWriter. /// where migrations should apply. /// - parameter scheduler: A Combine Scheduler. - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func migratePublisher( - _ writer: some DatabaseWriter, - receiveOn scheduler: some Scheduler = DispatchQueue.main) + _ writer: any DatabaseWriter, + receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main) -> DatabasePublishers.Migrate { DatabasePublishers.Migrate( @@ -514,7 +549,6 @@ extension DatabaseMigrator { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension DatabasePublishers { /// A publisher that migrates a database. /// diff --git a/GRDB/Migration/Migration.swift b/GRDB/Migration/Migration.swift index 36676d017..5a100bdec 100644 --- a/GRDB/Migration/Migration.swift +++ b/GRDB/Migration/Migration.swift @@ -1,5 +1,5 @@ /// An internal struct that defines a migration. -struct Migration { +struct Migration: Sendable { enum ForeignKeyChecks { case deferred case immediate @@ -8,7 +8,7 @@ struct Migration { let identifier: String var foreignKeyChecks: ForeignKeyChecks - let migrate: (Database) throws -> Void + let migrate: @Sendable (Database) throws -> Void func run(_ db: Database) throws { if try Bool.fetchOne(db, sql: "PRAGMA foreign_keys") ?? false { diff --git a/GRDB/QueryInterface/FTS3+QueryInterface.swift b/GRDB/QueryInterface/FTS3+QueryInterface.swift index 49fbc559c..a2335d4b8 100644 --- a/GRDB/QueryInterface/FTS3+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS3+QueryInterface.swift @@ -21,7 +21,7 @@ extension TableRequest where Self: FilteredRequest { } let alias = TableAlias() let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression) - return self.aliased(alias).filter(matchExpression) + return self._aliased(alias).filter(matchExpression) } } diff --git a/GRDB/QueryInterface/FTS5+QueryInterface.swift b/GRDB/QueryInterface/FTS5+QueryInterface.swift index b49f10514..4d97fd00f 100644 --- a/GRDB/QueryInterface/FTS5+QueryInterface.swift +++ b/GRDB/QueryInterface/FTS5+QueryInterface.swift @@ -22,7 +22,7 @@ extension TableRequest where Self: FilteredRequest { } let alias = TableAlias() let matchExpression = SQLExpression.tableMatch(alias, pattern.sqlExpression) - return self.aliased(alias).filter(matchExpression) + return self._aliased(alias).filter(matchExpression) } } diff --git a/GRDB/QueryInterface/ForeignKey.swift b/GRDB/QueryInterface/ForeignKey.swift index fbe27461d..12e5ab408 100644 --- a/GRDB/QueryInterface/ForeignKey.swift +++ b/GRDB/QueryInterface/ForeignKey.swift @@ -25,9 +25,14 @@ /// /// ```swift /// struct Book: TableRecord { +/// enum Columns { +/// static let authorId = Column("authorId") +/// static let translatorId = Column("translatorId") +/// } +/// /// // Define foreign keys -/// static let authorForeignKey = ForeignKey(["authorId"])) -/// static let translatorForeignKey = ForeignKey(["translatorId"])) +/// static let authorForeignKey = ForeignKey([Columns.authorId])) +/// static let translatorForeignKey = ForeignKey([Columns.translatorId])) /// /// // Use foreign keys to define associations: /// static let author = belongsTo( @@ -41,19 +46,6 @@ /// } /// ``` /// -/// Foreign keys can also be defined from query interface columns: -/// -/// ```swift -/// struct Book: TableRecord { -/// enum Columns: String, ColumnExpression { -/// case id, title, authorId, translatorId -/// } -/// -/// static let authorForeignKey = ForeignKey([Columns.authorId])) -/// static let translatorForeignKey = ForeignKey([Columns.translatorId])) -/// } -/// ``` -/// /// When the destination table does not define any primary key, you need to /// provide the destination columns: /// diff --git a/GRDB/QueryInterface/Request/Association/Association.swift b/GRDB/QueryInterface/Request/Association/Association.swift index debe9590a..86a234c8d 100644 --- a/GRDB/QueryInterface/Request/Association/Association.swift +++ b/GRDB/QueryInterface/Request/Association/Association.swift @@ -33,7 +33,7 @@ import Foundation /// /// - ``ForeignKey`` /// - ``Inflections`` -public protocol Association: DerivableRequest { +public protocol Association: DerivableRequest, Sendable { // OriginRowDecoder and RowDecoder inherited from DerivableRequest provide // type safety: // @@ -164,7 +164,7 @@ extension Association { // TableRequest conformance extension Association { - public func aliased(_ alias: TableAlias) -> Self { + public func _aliased(_ alias: TableAliasBase) -> Self { withDestinationRelation { relation in relation = relation.aliased(alias) } @@ -173,7 +173,9 @@ extension Association { // SelectionRequest conformance extension Association { - public func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self { + public func selectWhenConnected( + _ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable] + ) -> Self { withDestinationRelation { relation in relation = relation.selectWhenConnected { db in try selection(db).map(\.sqlSelection) @@ -181,7 +183,9 @@ extension Association { } } - public func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self { + public func annotatedWhenConnected( + with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable] + ) -> Self { withDestinationRelation { relation in relation = relation.annotatedWhenConnected { db in try selection(db).map(\.sqlSelection) @@ -192,7 +196,9 @@ extension Association { // FilteredRequest conformance extension Association { - public func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self { + public func filterWhenConnected( + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible + ) -> Self { withDestinationRelation { relation in relation = relation.filterWhenConnected { db in try predicate(db).sqlExpression @@ -203,7 +209,9 @@ extension Association { // OrderedRequest conformance extension Association { - public func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self { + public func orderWhenConnected( + _ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm] + ) -> Self { withDestinationRelation { relation in relation = relation.orderWhenConnected { db in try orderings(db).map(\.sqlOrdering) @@ -239,7 +247,9 @@ extension Association { // AggregatingRequest conformance extension Association { - public func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self { + public func groupWhenConnected( + _ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible] + ) -> Self { withDestinationRelation { relation in relation = relation.groupWhenConnected { db in try expressions(db).map(\.sqlExpression) @@ -247,7 +257,9 @@ extension Association { } } - public func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self { + public func havingWhenConnected( + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible + ) -> Self { withDestinationRelation { relation in relation = relation.havingWhenConnected { db in try predicate(db).sqlExpression @@ -293,15 +305,25 @@ extension AssociationToOne { /// /// ### Building Association Aggregates /// -/// - ``average(_:)`` +/// - ``average(_:)-1ehdb`` /// - ``count`` /// - ``isEmpty`` -/// - ``max(_:)`` -/// - ``min(_:)`` -/// - ``sum(_:)`` -/// - ``total(_:)`` +/// - ``max(_:)-a32j`` +/// - ``min(_:)-41jp8`` +/// - ``sum(_:)-47yg7`` +/// - ``total(_:)-6dd9d`` /// /// - ``AssociationAggregate`` +/// +/// ### Legacy APIs +/// +/// It is recommended to prefer the closure-based apis defined above. +/// +/// - ``average(_:)-4bbk9`` +/// - ``max(_:)-4g5ut`` +/// - ``min(_:)-6al4w`` +/// - ``sum(_:)-6ge96`` +/// - ``total(_:)-56v8i`` public protocol AssociationToMany: Association { } extension AssociationToMany { diff --git a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift index 944d5c0f8..5132589be 100644 --- a/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift +++ b/GRDB/QueryInterface/Request/Association/AssociationAggregate.swift @@ -136,6 +136,56 @@ extension AssociationToMany { } } + /// Returns the average of the given expression in associated records. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } + /// + /// try dbQueue.read { db in + /// // Fetch all teams whose average player score is greater than 1000 + /// let averageScore = Team.players.average(\.score) + /// let teams: [Team] = try Team + /// .having(averageScore >= 1000) + /// .fetchAll(db) + /// } + /// ``` + /// + /// When the input expression is a ``ColumnExpression``, the returned + /// association aggregate is named `"average[Key][Column]"`, where `key` is + /// the association key. For example: + /// + /// ```swift + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var averagePlayerScore: Double + /// } + /// + /// try dbQueue.read { db in + /// let averageScore = Team.players.average(\.score) + /// let infos: [TeamInfo] = try Team + /// .annotated(with: averageScore) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` + public func average( + _ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible + ) rethrows -> AssociationAggregate + where RowDecoder: TableRecord + { + try average(expression(RowDecoder.databaseComponents)) + } + /// Returns the maximum value of the given expression in associated records. /// /// For example: @@ -183,6 +233,56 @@ extension AssociationToMany { } } + /// Returns the maximum value of the given expression in associated records. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } + /// + /// try dbQueue.read { db in + /// // Fetch all teams whose maximum player score is greater than 1000 + /// let maxScore = Team.players.max(\.score) + /// let teams: [Team] = try Team + /// .having(maxScore >= 1000) + /// .fetchAll(db) + /// } + /// ``` + /// + /// When the input expression is a ``ColumnExpression``, the returned + /// association aggregate is named `"maximum[Key][Column]"`, where `key` is + /// the association key. For example: + /// + /// ```swift + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var maximumPlayerScore: Double + /// } + /// + /// try dbQueue.read { db in + /// let maxScore = Team.players.max(\.score) + /// let infos: [TeamInfo] = try Team + /// .annotated(with: maxScore) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` + public func max( + _ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible + ) rethrows -> AssociationAggregate + where RowDecoder: TableRecord + { + try max(expression(RowDecoder.databaseComponents)) + } + /// Returns the minimum value of the given expression in associated records. /// /// For example: @@ -230,10 +330,61 @@ extension AssociationToMany { } } + /// Returns the minimum value of the given expression in associated records. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } + /// + /// try dbQueue.read { db in + /// // Fetch all teams whose minimum player score is less than 1000 + /// let minScore = Team.players.min(\.score) + /// let teams: [Team] = try Team + /// .having(minScore < 1000) + /// .fetchAll(db) + /// } + /// ``` + /// + /// When the input expression is a ``ColumnExpression``, the returned + /// association aggregate is named `"minimum[Key][Column]"`, where `key` is + /// the association key. For example: + /// + /// ```swift + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var minimumPlayerScore: Double + /// } + /// + /// try dbQueue.read { db in + /// let minScore = Team.players.min(\.score) + /// let infos: [TeamInfo] = try Team + /// .annotated(with: minScore) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` + public func min( + _ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible + ) rethrows -> AssociationAggregate + where RowDecoder: TableRecord + { + try min(expression(RowDecoder.databaseComponents)) + } + /// Returns the sum of the given expression in associated records. /// - /// This aggregate invokes the `SUM` SQL function. See also ``total(_:)`` - /// and . + /// This aggregate invokes the `SUM` SQL function. + /// See also ``AssociationToMany/total(_:)-56v8i`` and + /// . /// /// For example: /// @@ -282,8 +433,63 @@ extension AssociationToMany { /// Returns the sum of the given expression in associated records. /// - /// This aggregate invokes the `TOTAL` SQL function. See also ``sum(_:)`` - /// and . + /// This aggregate invokes the `SUM` SQL function. + /// See also ``AssociationToMany/total(_:)-6dd9d`` and + /// . + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } + /// + /// try dbQueue.read { db in + /// // Fetch all teams whose sum of player scores is greater than 1000 + /// let scoreSum = Team.players.sum(\.score) + /// let teams: [Team] = try Team + /// .having(scoreSum >= 1000) + /// .fetchAll(db) + /// } + /// ``` + /// + /// When the input expression is a ``ColumnExpression``, the returned + /// association aggregate is named `"[key][Column]Sum"`, where `key` is the + /// association key. For example: + /// + /// ```swift + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var playerScoreSum: Double + /// } + /// + /// try dbQueue.read { db in + /// let scoreSum = Team.players.sum(\.score) + /// let infos: [TeamInfo] = try Team + /// .annotated(with: scoreSum) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` + public func sum( + _ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible + ) rethrows -> AssociationAggregate + where RowDecoder: TableRecord + { + try sum(expression(RowDecoder.databaseComponents)) + } + + /// Returns the sum of the given expression in associated records. + /// + /// This aggregate invokes the `TOTAL` SQL function. + /// See also ``AssociationToMany/sum(_:)-6ge96`` and + /// . /// /// For example: /// @@ -331,6 +537,64 @@ extension AssociationToMany { return aggregate } } + + /// Returns the sum of the given expression in associated records. + /// + /// This aggregate invokes the `TOTAL` SQL function. + /// See also ``AssociationToMany/sum(_:)-47yg7`` and + /// . + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// struct Team: FetchableRecord, TableRecord { + /// static let players = Team.hasMany(Player.self) + /// } + /// + /// try dbQueue.read { db in + /// // Fetch all teams whose sum of player scores is greater than 1000 + /// let totalScore = Team.players.total(\.score) + /// let teams: [Team] = try Team + /// .having(totalScore >= 1000) + /// .fetchAll(db) + /// } + /// ``` + /// + /// When the input expression is a ``ColumnExpression``, the returned + /// association aggregate is named `"[key][Column]Sum"`, where `key` is the + /// association key. For example: + /// + /// ```swift + /// struct TeamInfo: FetchableRecord, Decodable { + /// var team: Team + /// var playerScoreSum: Double + /// } + /// + /// try dbQueue.read { db in + /// let totalScore = Team.players.total(\.score) + /// let infos: [TeamInfo] = try Team + /// .annotated(with: totalScore) + /// .asRequest(of: TeamInfo.self) + /// .fetchAll(db) + /// } + /// ``` + public func total( + _ expression: (DatabaseComponents) throws -> some SQLSpecificExpressible + ) rethrows -> AssociationAggregate + where RowDecoder: TableRecord + { + try total(expression(RowDecoder.databaseComponents)) + } +} + +extension AssociationToMany where RowDecoder: TableRecord { + public typealias DatabaseComponents = RowDecoder.DatabaseComponents } /// A value aggregated from a population of associated records. diff --git a/GRDB/QueryInterface/Request/CommonTableExpression.swift b/GRDB/QueryInterface/Request/CommonTableExpression.swift index 17d192fb2..ceef01931 100644 --- a/GRDB/QueryInterface/Request/CommonTableExpression.swift +++ b/GRDB/QueryInterface/Request/CommonTableExpression.swift @@ -380,17 +380,23 @@ extension CommonTableExpression { /// /// - parameter cte: A common table expression. /// - parameter condition: A function that returns the joining clause. - /// - parameter left: A `TableAlias` for the left table. - /// - parameter right: A `TableAlias` for the right table. + /// First argument is a ``TableAlias`` for the left table, second + /// argument an alias for the right table. /// - returns: An association to the common table expression. public func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable ( + _ left: TableAlias, + _ right: TableAlias + ) -> any SQLExpressible + ) -> JoinAssociation { JoinAssociation( to: cte.relationForAll, - condition: .expression { condition($0, $1).sqlExpression }) + condition: .expression { left, right in + condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression + }) } /// Creates an association to a common table expression that you can join @@ -416,18 +422,23 @@ extension CommonTableExpression { /// - parameter destination: The record type at the other side of /// the association. /// - parameter condition: A function that returns the joining clause. - /// - parameter left: A `TableAlias` for the left table. - /// - parameter right: A `TableAlias` for the right table. + /// First argument is a ``TableAlias`` for the left table, second + /// argument an alias for the right table. /// - returns: An association to the common table expression. public func association( to destination: Destination.Type, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable ( + _ left: TableAlias, + _ right: TableAlias + ) -> any SQLExpressible) -> JoinAssociation where Destination: TableRecord { JoinAssociation( to: Destination.relationForAll, - condition: .expression { condition($0, $1).sqlExpression }) + condition: .expression { left, right in + condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression + }) } /// Creates an association to a table record that you can join @@ -453,17 +464,22 @@ extension CommonTableExpression { /// /// - parameter destination: The table at the other side of the association. /// - parameter condition: A function that returns the joining clause. - /// - parameter left: A `TableAlias` for the left table. - /// - parameter right: A `TableAlias` for the right table. + /// First argument is a ``TableAlias`` for the left table, second + /// argument an alias for the right table. /// - returns: An association to the common table expression. public func association( to destination: Table, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable ( + _ left: TableAlias, + _ right: TableAlias + ) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( to: destination.relationForAll, - condition: .expression { condition($0, $1).sqlExpression }) + condition: .expression { left, right in + condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression + }) } /// Creates an association to a table that you can join diff --git a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift index 1d0d7cdad..66816236b 100644 --- a/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/Request/QueryInterfaceRequest.swift @@ -23,15 +23,20 @@ /// ``Table`` instance. For example: /// /// ```swift -/// struct Player: TableRecord, FetchableRecord, DecodableRecord { } +/// struct Player: TableRecord, FetchableRecord, DecodableRecord { +/// enum Columns { +/// static let name = Column("name") +/// static let score = Column("score") +/// } +/// } /// /// try dbQueue.read { db in /// // SELECT * FROM player /// // WHERE name = 'O''Reilly' /// // ORDER BY score DESC /// let request = Player -/// .filter(Column("name") == "O'Reilly") -/// .order(Column("score").desc) +/// .filter { $0.name == "O'Reilly" } +/// .order(\.score.desc) /// let players: [Player] = try request.fetchAll(db) /// } /// ``` @@ -52,10 +57,10 @@ /// ### Changing The Type of Fetched Results /// /// - ``asRequest(of:)`` -/// - ``select(_:as:)-282xc`` -/// - ``select(_:as:)-3o8qw`` +/// - ``select(_:as:)-4cj9h`` /// - ``select(literal:as:)`` /// - ``select(sql:arguments:as:)`` +/// - ``selectID()`` /// - ``selectPrimaryKey(as:)`` /// /// ### Batch Delete @@ -65,17 +70,31 @@ /// - ``deleteAndFetchCursor(_:)`` /// - ``deleteAndFetchAll(_:)`` /// - ``deleteAndFetchSet(_:)`` -/// - ``deleteAndFetchStatement(_:selection:)`` +/// - ``deleteAndFetchStatement(_:select:)`` /// /// ### Batch Update /// +/// - ``updateAll(_:onConflict:assignment:)`` +/// - ``updateAll(_:onConflict:assignments:)`` +/// - ``updateAndFetchCursor(_:onConflict:assignments:)`` +/// - ``updateAndFetchAll(_:onConflict:assignments:)`` +/// - ``updateAndFetchSet(_:onConflict:assignments:)`` +/// - ``updateAndFetchStatement(_:onConflict:assignments:select:)`` +/// - ``ColumnAssignment`` +/// +/// ### Legacy APIs +/// +/// It is recommended to prefer the closure-based apis defined above. +/// +/// - ``deleteAndFetchStatement(_:selection:)`` +/// - ``select(_:as:)-282xc`` +/// - ``select(_:as:)-3o8qw`` /// - ``updateAll(_:onConflict:_:)-9r4v`` /// - ``updateAll(_:onConflict:_:)-49qg8`` /// - ``updateAndFetchCursor(_:onConflict:_:)`` /// - ``updateAndFetchAll(_:onConflict:_:)`` /// - ``updateAndFetchSet(_:onConflict:_:)`` /// - ``updateAndFetchStatement(_:onConflict:_:selection:)`` -/// - ``ColumnAssignment`` public struct QueryInterfaceRequest { var relation: SQLRelation } @@ -118,7 +137,7 @@ extension QueryInterfaceRequest: FetchRequest { extension QueryInterfaceRequest: SelectionRequest { public func selectWhenConnected( - _ selection: @escaping (Database) throws -> [any SQLSelectable]) + _ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self { with { @@ -186,6 +205,37 @@ extension QueryInterfaceRequest: SelectionRequest { select(selection, as: type) } + /// Defines the result columns, and defines the type of decoded rows. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let id = Column("id") + /// static let score = Column("score") + /// } + /// } + /// + /// // SELECT id FROM player + /// let request = Player.all().select(\.id, as: Int.self) + /// let scores = try request.fetchSet(db) // Set + /// + /// // SELECT MAX(score) FROM player + /// let request = Player.all().select({ max($0.score) }, as: Int.self) + /// let maxScore = try request.fetchOne(db) // Int? + /// ``` + /// + /// Any previous selection is discarded. + public func select( + _ selection: (DatabaseComponents) throws -> any SQLSelectable, + as type: T.Type = T.self + ) rethrows -> QueryInterfaceRequest + where RowDecoder: TableRecord + { + try select(selection).asRequest(of: T.self) + } + /// Defines the result columns with an SQL string, and defines the type of /// decoded rows. /// @@ -237,7 +287,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,8 +331,48 @@ 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 + /// let ids = try Player.filter(...) + /// .selectID() + /// .fetchSet(db) + /// + /// // BETTER: Set + /// let ids = try Player.filter(...) + /// .selectPrimaryKey(as: Int64.self) + /// .fetchSet(db) + /// ``` + public func selectID() -> QueryInterfaceRequest + 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 (Database) throws -> [any SQLSelectable]) + with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable]) -> Self { with { @@ -295,7 +385,7 @@ extension QueryInterfaceRequest: SelectionRequest { extension QueryInterfaceRequest: FilteredRequest { public func filterWhenConnected( - _ predicate: @escaping (Database) throws -> any SQLExpressible) + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self { with { @@ -308,7 +398,7 @@ extension QueryInterfaceRequest: FilteredRequest { extension QueryInterfaceRequest: OrderedRequest { public func orderWhenConnected( - _ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) + _ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm]) -> Self { with { @@ -320,15 +410,27 @@ extension QueryInterfaceRequest: OrderedRequest { /// Creates a request that reverses applied orderings. /// - /// // SELECT * FROM player ORDER BY name DESC - /// var request = Player.all().order(Column("name")) - /// request = request.reversed() + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// + /// // SELECT * FROM player ORDER BY name DESC + /// var request = Player.all().order(\.name) + /// request = request.reversed() + /// ``` /// /// If no ordering was applied, the returned request is identical. /// - /// // SELECT * FROM player - /// var request = Player.all() - /// request = request.reversed() + /// ```swift + /// // SELECT * FROM player + /// var request = Player.all() + /// request = request.reversed() + /// ``` public func reversed() -> Self { with { $0.relation = $0.relation.reversed() @@ -337,9 +439,18 @@ extension QueryInterfaceRequest: OrderedRequest { /// Creates a request without any ordering. /// - /// // SELECT * FROM player - /// var request = Player.all().order(Column("name")) - /// request = request.unordered() + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// + /// // SELECT * FROM player + /// let request = Player.all() + /// .order(\.name) + /// .unordered() + /// ``` public func unordered() -> Self { with { $0.relation = $0.relation.unordered() @@ -355,7 +466,7 @@ extension QueryInterfaceRequest: OrderedRequest { extension QueryInterfaceRequest: AggregatingRequest { public func groupWhenConnected( - _ expressions: @escaping (Database) throws -> [any SQLExpressible]) + _ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible]) -> Self { with { @@ -366,7 +477,7 @@ extension QueryInterfaceRequest: AggregatingRequest { } public func havingWhenConnected( - _ predicate: @escaping (Database) throws -> any SQLExpressible) + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible) -> Self { with { @@ -414,7 +525,7 @@ extension QueryInterfaceRequest: TableRequest { relation.source.tableName } - public func aliased(_ alias: TableAlias) -> Self { + public func _aliased(_ alias: TableAliasBase) -> Self { with { $0.relation = $0.relation.aliased(alias) } @@ -462,9 +573,15 @@ extension QueryInterfaceRequest { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// /// try dbQueue.read { db in /// let maxScore: Int? = try Player - /// .select(max(scoreColumn)) + /// .select { max($0.score) } /// .asRequest(of: Int.self) // <-- /// .fetchOne(db) /// } @@ -474,6 +591,10 @@ extension QueryInterfaceRequest { } } +extension QueryInterfaceRequest where RowDecoder: TableRecord { + public typealias DatabaseComponents = RowDecoder.DatabaseComponents +} + // MARK: - Check Existence extension QueryInterfaceRequest { @@ -482,9 +603,15 @@ extension QueryInterfaceRequest { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// /// try dbQueue.read { db in /// let arthurIsMissing = try Player - /// .filter(Column("name") == "Arthur") + /// .filter { $0.name == "Arthur" } /// .isEmpty(db) /// } /// ``` @@ -545,6 +672,43 @@ extension QueryInterfaceRequest { return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection) } + /// Returns a `DELETE RETURNING` prepared statement. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// + /// // Delete all players and return their names + /// // DELETE FROM player RETURNING name + /// let request = Player.all() + /// let statement = try request.deleteAndFetchStatement(db, selection: \.name) + /// let deletedNames = try String.fetchSet(statement) + /// ``` + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter select: A closure that returns the returned columns + /// (must not be empty). + /// - returns: A prepared statement. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + /// - precondition: The result of `select` is not empty. + public func deleteAndFetchStatement( + _ db: Database, + select: (DatabaseComponents) throws -> [any SQLSelectable] + ) throws -> Statement + where RowDecoder: TableRecord + { + try deleteAndFetchStatement(db, selection: select(RowDecoder.databaseComponents)) + } + /// Returns a cursor over the records deleted by a /// `DELETE RETURNING` statement. /// @@ -646,7 +810,6 @@ extension QueryInterfaceRequest { /// - parameter db: A database connection. /// - returns: A set of deleted ids. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) // Identifiable public func deleteAndFetchIds(_ db: Database) throws -> Set where RowDecoder: TableRecord & Identifiable, @@ -693,6 +856,44 @@ extension QueryInterfaceRequest { return try SQLQueryGenerator(relation: relation).makeDeleteStatement(db, selection: selection) } + /// Returns a `DELETE RETURNING` prepared statement. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// + /// // Delete all players and return their names + /// // DELETE FROM player RETURNING name + /// let request = Player.all() + /// let statement = try request.deleteAndFetchStatement(db, selection: \.name) + /// let deletedNames = try String.fetchSet(statement) + /// ``` + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter select: A closure that returns the returned columns + /// (must not be empty). + /// - returns: A prepared statement. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + /// - precondition: The result of `select` is not empty. + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ + public func deleteAndFetchStatement( + _ db: Database, + select: (DatabaseComponents) throws -> [any SQLSelectable] + ) throws -> Statement + where RowDecoder: TableRecord + { + try deleteAndFetchStatement(db, selection: select(RowDecoder.databaseComponents)) + } + /// Returns a cursor over the records deleted by a /// `DELETE RETURNING` statement. /// @@ -831,6 +1032,75 @@ extension QueryInterfaceRequest { } } + /// Updates matching rows, and returns the number of updated rows. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// let request = Player.all() + /// try request.updateAll(db) { $0.score.set(to: 0) } + /// } + /// ``` + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignment: A closure that returns an assignment. + /// - returns: The number of updated rows. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + @discardableResult + public func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignment: (DatabaseComponents) throws -> ColumnAssignment + ) throws -> Int + where RowDecoder: TableRecord + { + try updateAll(db, onConflict: conflictResolution, [assignment(RowDecoder.databaseComponents)]) + } + + /// Updates matching rows, and returns the number of updated rows. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// let request = Player.all() + /// try request.updateAll(db) { $0.score.set(to: 0) } + /// } + /// ``` + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: A closure that returns an array of + /// column assignments. + /// - returns: The number of updated rows. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + @discardableResult + public func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignments: (DatabaseComponents) throws -> [ColumnAssignment] + ) throws -> Int + where RowDecoder: TableRecord + { + try updateAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents)) + } + /// Updates matching rows, and returns the number of updated rows. /// /// For example: @@ -899,6 +1169,57 @@ extension QueryInterfaceRequest { extension QueryInterfaceRequest { #if GRDBCUSTOMSQLITE || GRDBCIPHER + /// Returns an `UPDATE RETURNING` prepared statement. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score) + /// } + /// } + /// + /// // Fetch all updated scores + /// // UPDATE player SET score = score + 10 RETURNING score + /// let request = Player.all() + /// let statement = try request.updateAndFetchStatement(db) { + /// $0.score += 10 + /// } select: { + /// [$0.score] + /// } + /// let updatedScores = try Int.fetchAll(statement) + /// ``` + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: A closure that returns an array of + /// column assignments (must not be empty). + /// - parameter selection: A closure that returns the returned columns + /// (must not be empty). + /// - returns: A prepared statement. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + /// - precondition: The results of `select` and `assignments` results + /// are not empty. + public func updateAndFetchStatement( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignments: (DatabaseComponents) throws -> [ColumnAssignment], + select: (DatabaseComponents) -> [any SQLSelectable] + ) throws -> Statement + where RowDecoder: TableRecord + { + try updateAndFetchStatement( + db, + onConflict: conflictResolution, + assignments(RowDecoder.databaseComponents), + selection: select(RowDecoder.databaseComponents)) + } + /// Returns an `UPDATE RETURNING` prepared statement. /// /// For example: @@ -947,6 +1268,48 @@ extension QueryInterfaceRequest { return updateStatement } + /// Returns a cursor over the records updated by an + /// `UPDATE RETURNING` statement. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let players = try request.updateAndFetchCursor(db) { [$0.score += 10] } + /// while let player = try players.next() { + /// print("Player \(player) was updated") + /// } + /// ``` + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: A closure that returns an array of + /// column assignments. + /// - returns: A cursor over the updated records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + /// - precondition: The result of `assignments` is not empty. + public func updateAndFetchCursor( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignments: (DatabaseComponents) throws -> [ColumnAssignment] + ) throws -> RecordCursor + where RowDecoder: FetchableRecord & TableRecord + { + try updateAndFetchCursor(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents)) + } + /// Returns a cursor over the records updated by an /// `UPDATE RETURNING` statement. /// @@ -987,6 +1350,45 @@ extension QueryInterfaceRequest { return try RowDecoder.fetchCursor(statement) } + /// Execute an `UPDATE RETURNING` statement and returns the array of + /// updated records. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let updatedPlayers = try request.updateAndFetchAll(db) { [$0.score += 10] } + /// ``` + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: A closure that returns an array of + /// column assignments. + /// - returns: An array of updated records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + /// - precondition: The result of `assignments` is not empty. + public func updateAndFetchAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignments: (DatabaseComponents) throws -> [ColumnAssignment] + ) throws -> [RowDecoder] + where RowDecoder: FetchableRecord & TableRecord + { + try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents)) + } + /// Execute an `UPDATE RETURNING` statement and returns the array of /// updated records. /// @@ -1019,6 +1421,45 @@ extension QueryInterfaceRequest { try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments)) } + /// Execute an `UPDATE RETURNING` statement and returns the set of + /// updated records. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let updatedPlayers = try request.updateAndFetchSet(db) { [$0.score += 10]) } + /// ``` + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: A closure that returns an array of + /// column assignments. + /// - returns: A set of updated records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + /// - precondition: The result of `assignments` is not empty. + public func updateAndFetchSet( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignments: (DatabaseComponents) throws -> [ColumnAssignment] + ) throws -> Set + where RowDecoder: FetchableRecord & TableRecord & Hashable + { + try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents)) + } + /// Execute an `UPDATE RETURNING` statement and returns the set of /// updated records. /// @@ -1051,6 +1492,58 @@ extension QueryInterfaceRequest { try Set(updateAndFetchCursor(db, onConflict: conflictResolution, assignments)) } #else + /// Returns an `UPDATE RETURNING` prepared statement. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score) + /// } + /// } + /// + /// // Fetch all updated scores + /// // UPDATE player SET score = score + 10 RETURNING score + /// let request = Player.all() + /// let statement = try request.updateAndFetchStatement(db) { + /// $0.score += 10 + /// } select: { + /// [$0.score] + /// } + /// let updatedScores = try Int.fetchAll(statement) + /// ``` + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: A closure that returns an array of + /// column assignments (must not be empty). + /// - parameter select: A closure that returns the returned columns + /// (must not be empty). + /// - returns: A prepared statement. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + /// - precondition: The results of `select` and `assignments` results + /// are not empty. + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ + public func updateAndFetchStatement( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignments: (DatabaseComponents) throws -> [ColumnAssignment], + select: (DatabaseComponents) throws -> [any SQLSelectable] + ) throws -> Statement + where RowDecoder: TableRecord + { + try updateAndFetchStatement( + db, + onConflict: conflictResolution, + assignments(RowDecoder.databaseComponents), + selection: select(RowDecoder.databaseComponents)) + } + /// Returns an `UPDATE RETURNING` prepared statement. /// /// For example: @@ -1100,6 +1593,49 @@ extension QueryInterfaceRequest { return updateStatement } + /// Returns a cursor over the records updated by an + /// `UPDATE RETURNING` statement. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let players = try request.updateAndFetchCursor(db) { [$0.score += 10] } + /// while let player = try players.next() { + /// print("Player \(player) was updated") + /// } + /// ``` + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: A closure that returns an array of + /// column assignments. + /// - returns: A cursor over the updated records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + /// - precondition: The result of `assignments` is not empty. + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ + public func updateAndFetchCursor( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignments: (DatabaseComponents) throws -> [ColumnAssignment] + ) throws -> RecordCursor + where RowDecoder: FetchableRecord & TableRecord + { + try updateAndFetchCursor(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents)) + } + /// Returns a cursor over the records updated by an /// `UPDATE RETURNING` statement. /// @@ -1141,6 +1677,46 @@ extension QueryInterfaceRequest { return try RowDecoder.fetchCursor(statement) } + /// Execute an `UPDATE RETURNING` statement and returns the array of + /// updated records. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let updatedPlayers = try request.updateAndFetchAll(db) { [$0.score += 10] } + /// ``` + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: A closure that returns an array of + /// column assignments. + /// - returns: An array of updated records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + /// - precondition: The result of `assignments` is not empty. + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ + public func updateAndFetchAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignments: (DatabaseComponents) throws -> [ColumnAssignment] + ) throws -> [RowDecoder] + where RowDecoder: FetchableRecord & TableRecord + { + try updateAndFetchAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents)) + } + /// Execute an `UPDATE RETURNING` statement and returns the array of /// updated records. /// @@ -1174,6 +1750,46 @@ extension QueryInterfaceRequest { try Array(updateAndFetchCursor(db, onConflict: conflictResolution, assignments)) } + /// Execute an `UPDATE RETURNING` statement and returns the set of + /// updated records. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// // Fetch all updated players + /// // UPDATE player SET score = score + 10 RETURNING * + /// let request = Player.all() + /// let updatedPlayers = try request.updateAndFetchSet(db) { [$0.score += 10]) } + /// ``` + /// + /// - important: Make sure you check the documentation of the `RETURNING` + /// clause, which describes important limitations and caveats: + /// . + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: A closure that returns an array of + /// column assignments. + /// - returns: A set of updated records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + /// - precondition: The result of `assignments` is not empty. + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ + public func updateAndFetchSet( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignments: (DatabaseComponents) throws -> [ColumnAssignment] + ) throws -> Set + where RowDecoder: FetchableRecord & TableRecord & Hashable + { + try updateAndFetchSet(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents)) + } + /// Execute an `UPDATE RETURNING` statement and returns the set of /// updated records. /// @@ -1217,10 +1833,17 @@ extension QueryInterfaceRequest { /// such as ``ColumnExpression/set(to:)`` or `+=`: /// /// ```swift +/// struct Player: TableRecord { +/// enum Columns { +/// static let score = Column("score") +/// } +/// } +/// /// try dbQueue.write { db in /// // UPDATE player SET score = 0 -/// let assignment = Column("score").set(to: 0) -/// try Player.updateAll(db, assignment) +/// try Player.updateAll(db) { +/// $0.score.set(to: 0) +/// } /// } /// ``` public struct ColumnAssignment { @@ -1262,9 +1885,15 @@ extension ColumnExpression { /// Usage: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// /// try dbQueue.write { db in /// // UPDATE player SET score = 0 - /// try Player.updateAll(db, Column("score").set(to: 0)) + /// try Player.updateAll(db) { $0.set(to: 0) } /// } /// ``` public func set(to value: (any SQLExpressible)?) -> ColumnAssignment { @@ -1290,9 +1919,15 @@ extension ColumnExpression { /// Usage: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// /// try dbQueue.write { db in /// // UPDATE player SET score = score + 1 - /// try Player.updateAll(db, Column("score") += 1) + /// try Player.updateAll(db) { $0.score += 1 } /// } /// ``` public static func += (column: Self, value: some SQLExpressible) -> ColumnAssignment { @@ -1311,9 +1946,15 @@ extension ColumnExpression { /// Usage: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// /// try dbQueue.write { db in /// // UPDATE player SET score = score - 1 - /// try Player.updateAll(db, Column("score") -= 1) + /// try Player.updateAll(db) { $0.score -= 1 } /// } /// ``` public static func -= (column: Self, value: some SQLExpressible) -> ColumnAssignment { @@ -1332,9 +1973,15 @@ extension ColumnExpression { /// Usage: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// /// try dbQueue.write { db in /// // UPDATE player SET score = score * 2 - /// try Player.updateAll(db, Column("score") *= 2) + /// try Player.updateAll(db) { $0.score *= 2 } /// } /// ``` public static func *= (column: Self, value: some SQLExpressible) -> ColumnAssignment { @@ -1353,9 +2000,15 @@ extension ColumnExpression { /// Usage: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// /// try dbQueue.write { db in /// // UPDATE player SET score = score / 2 - /// try Player.updateAll(db, Column("score") /= 2) + /// try Player.updateAll(db) { $0.score /= 2 } /// } /// ``` public static func /= (column: Self, value: some SQLExpressible) -> ColumnAssignment { @@ -1374,9 +2027,15 @@ extension ColumnExpression { /// Usage: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let mask = Column("mask") + /// } + /// } + /// /// try dbQueue.write { db in - /// // UPDATE player SET score = score & 2 - /// try Player.updateAll(db, Column("mask") &= 2) + /// // UPDATE player SET mask = mask & 2 + /// try Player.updateAll(db) { $0.mask &= 2 } /// } /// ``` public static func &= (column: Self, value: some SQLExpressible) -> ColumnAssignment { @@ -1395,9 +2054,15 @@ extension ColumnExpression { /// Usage: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let mask = Column("mask") + /// } + /// } + /// /// try dbQueue.write { db in - /// // UPDATE player SET score = score | 2 - /// try Player.updateAll(db, Column("mask") |= 2) + /// // UPDATE player SET mask = mask | 2 + /// try Player.updateAll(db) { $0.mask |= 2 } /// } /// ``` public static func |= (column: Self, value: some SQLExpressible) -> ColumnAssignment { @@ -1416,9 +2081,15 @@ extension ColumnExpression { /// Usage: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let mask = Column("mask") + /// } + /// } + /// /// try dbQueue.write { db in - /// // UPDATE player SET score = score << 2 - /// try Player.updateAll(db, Column("mask") <<= 2) + /// // UPDATE player SET mask = mask << 2 + /// try Player.updateAll(db) { $0.mask <<= 2 } /// } /// ``` public static func <<= (column: Self, value: some SQLExpressible) -> ColumnAssignment { @@ -1437,9 +2108,15 @@ extension ColumnExpression { /// Usage: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let mask = Column("mask") + /// } + /// } + /// /// try dbQueue.write { db in - /// // UPDATE player SET score = score >> 2 - /// try Player.updateAll(db, Column("mask") >>= 2) + /// // UPDATE player SET mask = mask >> 2 + /// try Player.updateAll(db) { $0.mask >>= 2 } /// } /// ``` public static func >>= (column: Self, value: some SQLExpressible) -> ColumnAssignment { diff --git a/GRDB/QueryInterface/Request/RequestProtocols.swift b/GRDB/QueryInterface/Request/RequestProtocols.swift index def5c2f52..9e13293f6 100644 --- a/GRDB/QueryInterface/Request/RequestProtocols.swift +++ b/GRDB/QueryInterface/Request/RequestProtocols.swift @@ -22,14 +22,23 @@ public protocol TypedRequest { /// /// ### The SELECT Clause /// -/// - ``annotated(with:)-4qcem`` -/// - ``annotated(with:)-6ehs4`` +/// - ``annotated(with:)-9wodv`` +/// - ``annotated(with:)-69r3`` /// - ``annotatedWhenConnected(with:)`` -/// - ``select(_:)-30yzl`` -/// - ``select(_:)-7e2y5`` +/// - ``select(_:)-270ge`` +/// - ``select(_:)-4jw13`` /// - ``select(literal:)`` /// - ``select(sql:arguments:)`` /// - ``selectWhenConnected(_:)`` +/// +/// ### Legacy APIs +/// +/// It is recommended to prefer the closure-based apis defined above. +/// +/// - ``annotated(with:)-4qcem`` +/// - ``annotated(with:)-6ehs4`` +/// - ``select(_:)-30yzl`` +/// - ``select(_:)-7e2y5`` public protocol SelectionRequest { /// Defines the result columns. /// @@ -58,7 +67,9 @@ public protocol SelectionRequest { /// /// - parameter selection: A closure that accepts a database connection and /// returns an array of result columns. - func selectWhenConnected(_ selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self + func selectWhenConnected( + _ selection: @escaping @Sendable (Database) throws -> [any SQLSelectable] + ) -> Self /// Appends result columns to the selected columns. /// @@ -78,7 +89,9 @@ public protocol SelectionRequest { /// /// - parameter selection: A closure that accepts a database connection and /// returns an array of result columns. - func annotatedWhenConnected(with selection: @escaping (Database) throws -> [any SQLSelectable]) -> Self + func annotatedWhenConnected( + with selection: @escaping @Sendable (Database) throws -> [any SQLSelectable] + ) -> Self } extension SelectionRequest { @@ -100,7 +113,8 @@ extension SelectionRequest { /// .select([Column("score")]) /// ``` public func select(_ selection: [any SQLSelectable]) -> Self { - selectWhenConnected { _ in selection } + let selection = selection.map(\.sqlSelection) + return selectWhenConnected { _ in selection } } /// Defines the result columns. @@ -186,7 +200,8 @@ extension SelectionRequest { /// let request = Player.all().annotated(with: [totalScore]) /// ``` public func annotated(with selection: [any SQLSelectable]) -> Self { - annotatedWhenConnected(with: { _ in selection }) + let selection = selection.map(\.sqlSelection) + return annotatedWhenConnected(with: { _ in selection }) } /// Appends result columns to the selected columns. @@ -203,6 +218,122 @@ extension SelectionRequest { } } +extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecord { + public typealias DatabaseComponents = RowDecoder.DatabaseComponents + + /// Defines the result column. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let id = Column("id") + /// static let score = Column("score") + /// } + /// } + /// + /// // SELECT score FROM player + /// let request = Player.all().select(\.score) + /// ``` + /// + /// Any previous selection is replaced: + /// + /// ```swift + /// // SELECT score FROM player + /// let request = Player.all() + /// .select(\.id) + /// .select(\.score) + /// ``` + public func select( + _ selection: (DatabaseComponents) throws -> any SQLSelectable + ) rethrows -> Self { + try select(selection(Self.RowDecoder.databaseComponents)) + } + + /// Defines the result columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let id = Column("id") + /// static let score = Column("score") + /// } + /// } + /// + /// // SELECT id, score FROM player + /// let request = Player.all().select { [$0.id, $0.score] } + /// ``` + /// + /// Any previous selection is replaced: + /// + /// ```swift + /// // SELECT score FROM player + /// let request = Player.all() + /// .select { [$0.id] } + /// .select { [$0.score] } + /// ``` + public func select( + _ selection: (DatabaseComponents) throws -> [any SQLSelectable] + ) rethrows -> Self { + try select(selection(Self.RowDecoder.databaseComponents)) + } + + /// Appends a result column to the selected columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let bonus = Column("bonus") + /// } + /// } + /// + /// // SELECT *, score + bonus AS totalScore FROM player + /// let request = Player.all().annotated { + /// ($0.score + $0.bonus).forKey("totalScore") + /// } + /// ``` + /// + /// - parameter selection: A closure that accepts a database connection and + /// returns an array of result columns. + public func annotated( + with selection: (DatabaseComponents) throws -> any SQLSelectable + ) rethrows -> Self { + try annotated(with: selection(Self.RowDecoder.databaseComponents)) + } + + /// Appends result columns to the selected columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let bonus = Column("bonus") + /// } + /// } + /// + /// // SELECT *, score + bonus AS totalScore FROM player + /// let request = Player.all().annotated { + /// [($0.score + $0.bonus).forKey("totalScore")] + /// } + /// ``` + /// + /// - parameter selection: A closure that accepts a database connection and + /// returns an array of result columns. + public func annotated( + with selection: (DatabaseComponents) throws -> [any SQLSelectable] + ) rethrows -> Self { + try annotated(with: selection(Self.RowDecoder.databaseComponents)) + } +} + // MARK: - FilteredRequest /// A request that can filter database rows. @@ -215,11 +346,17 @@ extension SelectionRequest { /// ### The WHERE and JOIN ON Clauses /// /// - ``all()`` -/// - ``filter(_:)`` +/// - ``filter(_:)-7j0nw`` /// - ``filter(literal:)`` /// - ``filter(sql:arguments:)`` /// - ``filterWhenConnected(_:)`` /// - ``none()`` +/// +/// ### Legacy APIs +/// +/// It is recommended to prefer the closure-based apis defined above. +/// +/// - ``filter(_:)-48a4t`` public protocol FilteredRequest { /// Filters the fetched rows with a boolean SQL expression. /// @@ -240,7 +377,9 @@ public protocol FilteredRequest { /// /// - parameter predicate: A closure that accepts a database connection and /// returns a boolean SQL expression. - func filterWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self + func filterWhenConnected( + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible + ) -> Self } extension FilteredRequest { @@ -257,7 +396,8 @@ extension FilteredRequest { /// let request = Player.all().filter(Column("name") == name) /// ``` public func filter(_ predicate: some SQLSpecificExpressible) -> Self { - filterWhenConnected { _ in predicate } + let predicate = predicate.sqlExpression + return filterWhenConnected { _ in predicate } } /// Filters the fetched rows with an SQL string. @@ -301,6 +441,34 @@ extension FilteredRequest { } } +extension FilteredRequest where Self: TypedRequest, Self.RowDecoder: TableRecord { + public typealias DatabaseComponents = RowDecoder.DatabaseComponents + + // Accept SQLSpecificExpressible instead of SQLExpressible, so that we + // prevent the `Player.filter { 42 }` misuse. + // See https://github.com/groue/GRDB.swift/pull/864 + /// Filters the fetched rows with a boolean SQL expression. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = Player.all().filter { $0.name == name } + /// ``` + public func filter( + _ predicate: (DatabaseComponents) throws -> any SQLSpecificExpressible + ) rethrows -> Self { + try filter(predicate(Self.RowDecoder.databaseComponents)) + } +} + // MARK: - TableRequest /// A request that feeds from a database table @@ -313,7 +481,7 @@ extension FilteredRequest { /// /// ### Instance Methods /// -/// - ``aliased(_:)`` +/// - ``aliased(_:)-3k5h4`` /// - ``TableAlias`` /// /// ### The WHERE Clause @@ -322,7 +490,7 @@ extension FilteredRequest { /// - ``filter(ids:)`` /// - ``filter(key:)-1p9sq`` /// - ``filter(key:)-2te6v`` -/// - ``filter(keys:)-6ggt1`` +/// - ``filter(keys:)-9p9i5`` /// - ``filter(keys:)-8fbn9`` /// - ``matching(_:)-3s3zr`` /// - ``matching(_:)-7c1e8`` @@ -334,11 +502,23 @@ extension FilteredRequest { /// ### The ORDER BY Clause /// /// - ``orderByPrimaryKey()`` +/// +/// ### Legacy APIs +/// +/// It is recommended to prefer record aliases over anonymous aliases. +/// +/// - ``aliased(_:)-772vb`` public protocol TableRequest { /// The name of the database table var databaseTableName: String { get } /// Returns a request that can be referred to with the provided alias. + func _aliased(_ alias: TableAliasBase) -> Self +} + +extension TableRequest where Self: TypedRequest { + /// Returns a request that can be referred to with the provided + /// anonymous alias. /// /// Use this method when you need to refer to this request from /// another request. @@ -393,7 +573,77 @@ public protocol TableRequest { /// .filter(sql: "b.publishDate >= a.deathDate") /// .fetchAll(db) /// ``` - func aliased(_ alias: TableAlias) -> Self + public func aliased(_ alias: TableAlias) -> Self { + self._aliased(alias) + } + + /// Returns a request that can be referred to with the provided + /// record alias. + /// + /// Use this method when you need to refer to this request from + /// another request. + /// + /// The first example fetches posthumous books: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord { + /// enum Columns { + /// static let deathDate = Column("deathDate") + /// } + /// } + /// + /// struct Book: TableRecord, FetchableRecord { + /// static let author = belongsTo(Author.self) + /// enum Columns { + /// static let publishDate = Column("publishDate") + /// } + /// } + /// + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // WHERE book.publishDate >= author.deathDate + /// let authorAlias = TableAlias() + /// let posthumousBooks = try Book + /// .joining(required: Book.author.aliased(authorAlias)) + /// .filter { $0.publishDate >= authorAlias.deathDate } + /// .fetchAll(db) + /// ``` + /// + /// The second example sorts books by author name first, and then by title: + /// + /// ```swift + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // ORDER BY author.name, book.title + /// let authorAlias = TableAlias() + /// let books = try Book + /// .joining(required: Book.author.aliased(authorAlias)) + /// .order { [authorAlias.name, $0.title] } + /// .fetchAll(db) + /// ``` + /// + /// The third example uses named ``TableAlias`` so that SQL snippets can + /// refer to SQL tables with those names: + /// + /// ```swift + /// // SELECT b.* + /// // FROM book b + /// // JOIN author a ON a.id = b.authorId + /// // AND a.countryCode = 'FR' + /// // WHERE b.publishDate >= a.deathDate + /// let bookAlias = TableAlias(name: "b") + /// let authorAlias = TableAlias(name: "a") + /// let posthumousFrenchBooks = try Book.aliased(bookAlias) + /// .joining(required: Book.author.aliased(authorAlias) + /// .filter(sql: "a.countryCode = ?", arguments: ["FR"])) + /// .filter(sql: "b.publishDate >= a.deathDate") + /// .fetchAll(db) + /// ``` + public func aliased(_ alias: TableAlias) -> Self { + self._aliased(alias) + } } extension TableRequest where Self: FilteredRequest, Self: TypedRequest { @@ -431,9 +681,8 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { /// ``` /// /// - parameter keys: A collection of primary keys - public func filter(keys: Sequence) - -> Self - where Sequence.Element: DatabaseValueConvertible + public func filter(keys: Keys) -> Self + where Keys: Collection, Keys.Element: DatabaseValueConvertible { // In order to encode keys in the database, we perform a runtime check // for EncodableRecord, and look for a customized encoding strategy. @@ -442,51 +691,70 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { // make it impractical to define `filter(id:)`, `fetchOne(_:key:)`, // `deleteAll(_:ids:)` etc. if let recordType = RowDecoder.self as? any EncodableRecord.Type { - if Sequence.Element.self == Data.self || Sequence.Element.self == Optional.self { - let strategy = recordType.databaseDataEncodingStrategy - let keys = keys.compactMap { ($0 as! Data?).flatMap(strategy.encode)?.databaseValue } - return filter(rawKeys: keys) - } else if Sequence.Element.self == Date.self || Sequence.Element.self == Optional.self { - let strategy = recordType.databaseDateEncodingStrategy - let keys = keys.compactMap { ($0 as! Date?).flatMap(strategy.encode)?.databaseValue } - return filter(rawKeys: keys) - } else if Sequence.Element.self == UUID.self || Sequence.Element.self == Optional.self { - let strategy = recordType.databaseUUIDEncodingStrategy - let keys = keys.map { ($0 as! UUID?).map(strategy.encode)?.databaseValue } - return filter(rawKeys: keys) + if Keys.Element.self == Data.self || Keys.Element.self == Optional.self { + let datas = keys.compactMap { ($0 as! Data?) } + if datas.isEmpty { + // Don't hit the database + return none() + } + + return filterWhenConnected(keys: { [databaseTableName] db in + let column = try db.filteringPrimaryKeyColumn(databaseTableName) + let strategy = recordType.databaseDataEncodingStrategy(for: column) + let expressions = try datas.map { try strategy.encode($0).sqlExpression } + return expressions + }) + } else if Keys.Element.self == Date.self || Keys.Element.self == Optional.self { + let dates = keys.compactMap { ($0 as! Date?) } + if dates.isEmpty { + // Don't hit the database + return none() + } + + return filterWhenConnected(keys: { [databaseTableName] db in + let column = try db.filteringPrimaryKeyColumn(databaseTableName) + let strategy = recordType.databaseDateEncodingStrategy(for: column) + let expressions = dates.map { strategy.encode($0).sqlExpression } + return expressions + }) + } else if Keys.Element.self == UUID.self || Keys.Element.self == Optional.self { + let uuids = keys.compactMap { ($0 as! UUID?) } + if uuids.isEmpty { + // Don't hit the database + return none() + } + + return filterWhenConnected(keys: { [databaseTableName] db in + let column = try db.filteringPrimaryKeyColumn(databaseTableName) + let strategy = recordType.databaseUUIDEncodingStrategy(for: column) + let expressions = uuids.map { strategy.encode($0).sqlExpression } + return expressions + }) } } - return filter(rawKeys: keys) + let expressions = keys.map { $0.sqlExpression } + if expressions.isEmpty { + // Don't hit the database + return none() + } + return filterWhenConnected(keys: { _ in expressions }) } /// Creates a request filtered by primary key. /// /// // SELECT * FROM player WHERE ... id IN (1, 2, 3) - /// let request = try Player...filter(rawKeys: [1, 2, 3]) + /// let request = try Player...filterWhenConnected(keys: { db in [1, 2, 3] }) /// /// - parameter keys: A collection of primary keys - func filter(rawKeys: Keys) -> Self - where Keys: Sequence, Keys.Element: DatabaseValueConvertible - { - // Don't bother removing NULLs. We'd lose CPU cycles, and this does not - // change the SQLite results anyway. - let expressions = rawKeys.map { - $0.databaseValue.sqlExpression - } - - if expressions.isEmpty { - // Don't hit the database - return none() - } - + fileprivate func filterWhenConnected(keys: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self { let databaseTableName = self.databaseTableName return filterWhenConnected { db in - let primaryKey = try db.primaryKey(databaseTableName) - GRDBPrecondition( - primaryKey.columns.count == 1, - "Requesting by key requires a single-column primary key in the table \(databaseTableName)") - return SQLCollection.array(expressions).contains(Column(primaryKey.columns[0]).sqlExpression) + // Don't bother removing NULLs. We'd lose CPU cycles, and this does not + // change the SQLite results anyway. + let expressions = try keys(db) + let column = try db.filteringPrimaryKeyColumn(databaseTableName) + return SQLCollection.array(expressions).contains(Column(column).sqlExpression) } } @@ -545,6 +813,11 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { return none() } + // Turn key values into sendable DatabaseValue + let keys = keys.map { key in + key.mapValues { $0?.databaseValue ?? .null } + } + let databaseTableName = self.databaseTableName return filterWhenConnected { db in try keys @@ -583,7 +856,6 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension TableRequest where Self: FilteredRequest, Self: TypedRequest, @@ -620,9 +892,7 @@ where Self: FilteredRequest, /// ``` /// /// - parameter ids: A collection of primary keys - public func filter(ids: IDS) -> Self - where IDS: Collection, IDS.Element == RowDecoder.ID - { + public func filter(ids: some Collection) -> Self { filter(keys: ids) } } @@ -694,18 +964,26 @@ extension TableRequest where Self: AggregatingRequest { /// /// ### The GROUP BY Clause /// -/// - ``group(_:)-edak`` -/// - ``group(_:)-4216o`` +/// - ``group(_:)-5soxm`` +/// - ``group(_:)-32exm`` /// - ``group(literal:)`` /// - ``group(sql:arguments:)`` /// - ``groupWhenConnected(_:)`` /// /// ### The HAVING Clause /// -/// - ``having(_:)`` +/// - ``having(_:)-27hlo`` /// - ``having(literal:)`` /// - ``having(sql:arguments:)`` /// - ``havingWhenConnected(_:)`` +/// +/// ### Legacy APIs +/// +/// It is recommended to prefer the closure-based apis defined above. +/// +/// - ``group(_:)-edak`` +/// - ``group(_:)-4216o`` +/// - ``having(_:)-2ssg9`` public protocol AggregatingRequest { /// Returns an aggregate request grouped on the given SQL expressions. /// @@ -729,7 +1007,9 @@ public protocol AggregatingRequest { /// /// - parameter expressions: A closure that accepts a database connection /// and returns an array of SQL expressions. - func groupWhenConnected(_ expressions: @escaping (Database) throws -> [any SQLExpressible]) -> Self + func groupWhenConnected( + _ expressions: @escaping @Sendable (Database) throws -> [any SQLExpressible] + ) -> Self /// Filters the aggregated groups with a boolean SQL expression. /// @@ -753,7 +1033,9 @@ public protocol AggregatingRequest { /// /// - parameter predicate: A closure that accepts a database connection and /// returns a boolean SQL expression. - func havingWhenConnected(_ predicate: @escaping (Database) throws -> any SQLExpressible) -> Self + func havingWhenConnected( + _ predicate: @escaping @Sendable (Database) throws -> any SQLExpressible + ) -> Self } extension AggregatingRequest { @@ -774,7 +1056,8 @@ extension AggregatingRequest { /// /// - parameter expressions: An array of SQL expressions. public func group(_ expressions: [any SQLExpressible]) -> Self { - groupWhenConnected { _ in expressions } + let expressions = expressions.map(\.sqlExpression) + return groupWhenConnected { _ in expressions } } /// Returns an aggregate request grouped on the given SQL expressions. @@ -849,7 +1132,8 @@ extension AggregatingRequest { /// .having(max(Column("score")) > 1000) /// ``` public func having(_ predicate: some SQLExpressible) -> Self { - havingWhenConnected { _ in predicate } + let predicate = predicate.sqlExpression + return havingWhenConnected { _ in predicate } } /// Filters the aggregated groups with an SQL string. @@ -890,6 +1174,71 @@ extension AggregatingRequest { } } +extension AggregatingRequest where Self: TypedRequest, Self.RowDecoder: TableRecord { + public typealias DatabaseComponents = RowDecoder.DatabaseComponents + + /// Returns an aggregate request grouped on the given SQL expression. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let teamId = Column("teamId") + /// static let score = Column("score") + /// } + /// } + /// + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// let request = Player + /// .select { [$0.teamId, max($0.score)] } + /// .group(\.teamId) + /// ``` + /// + /// Any previous grouping is discarded. + public func group( + _ expression: (DatabaseComponents) throws -> any SQLExpressible + ) rethrows -> Self { + try group(expression(Self.RowDecoder.databaseComponents)) + } + + /// Returns an aggregate request grouped on the given SQL expressions. + public func group( + _ expressions: (DatabaseComponents) throws -> [any SQLExpressible] + ) rethrows -> Self { + try group(expressions(Self.RowDecoder.databaseComponents)) + } + + /// Filters the aggregated groups with a boolean SQL expression. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let teamId = Column("teamId") + /// static let score = Column("score") + /// } + /// } + /// + /// // SELECT teamId, MAX(score) + /// // FROM player + /// // GROUP BY teamId + /// // HAVING MAX(score) > 1000 + /// let request = Player + /// .select { [$0.teamId, max($0.score)] } + /// .group(\.teamId) + /// .having { max($0.score) > 1000 } + /// ``` + public func having( + _ predicate: (DatabaseComponents) throws -> any SQLExpressible + ) rethrows -> Self { + try having(predicate(Self.RowDecoder.databaseComponents)) + } +} + // MARK: - OrderedRequest /// A request that can sort database rows. @@ -898,14 +1247,21 @@ extension AggregatingRequest { /// /// ### The ORDER BY Clause /// -/// - ``order(_:)-63rzl`` -/// - ``order(_:)-6co0m`` +/// - ``order(_:)-5q7wj`` +/// - ``order(_:)-711zj`` /// - ``order(literal:)`` /// - ``order(sql:arguments:)`` /// - ``orderWhenConnected(_:)`` /// - ``reversed()`` /// - ``unordered()`` /// - ``withStableOrder()`` +/// +/// ### Legacy APIs +/// +/// It is recommended to prefer the closure-based apis defined above. +/// +/// - ``order(_:)-63rzl`` +/// - ``order(_:)-6co0m`` public protocol OrderedRequest { /// Sorts the fetched rows according to the given SQL ordering terms. /// @@ -934,16 +1290,24 @@ public protocol OrderedRequest { /// /// - parameter orderings: A closure that accepts a database connection and /// returns an array of SQL ordering terms. - func orderWhenConnected(_ orderings: @escaping (Database) throws -> [any SQLOrderingTerm]) -> Self + func orderWhenConnected( + _ orderings: @escaping @Sendable (Database) throws -> [any SQLOrderingTerm] + ) -> Self /// Returns a request with reversed ordering. /// /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// /// // SELECT * FROM player ORDER BY name DESC /// let request = Player.all() - /// .order(Column("name")) + /// .order(\.name) /// .reversed() /// ``` /// @@ -957,12 +1321,16 @@ public protocol OrderedRequest { /// Returns a request without any ordering. /// - /// For example: - /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// /// // SELECT * FROM player /// let request = Player.all() - /// .order(Column("name")) + /// .order(\.name) /// .unordered() /// ``` func unordered() -> Self @@ -996,7 +1364,8 @@ extension OrderedRequest { /// .order(Column("name")) /// ``` public func order(_ orderings: any SQLOrderingTerm...) -> Self { - orderWhenConnected { _ in orderings } + let orderings = orderings.map(\.sqlOrdering) + return orderWhenConnected { _ in orderings } } /// Sorts the fetched rows according to the given SQL ordering terms. @@ -1018,7 +1387,8 @@ extension OrderedRequest { /// .order([Column("name")]) /// ``` public func order(_ orderings: [any SQLOrderingTerm]) -> Self { - orderWhenConnected { _ in orderings } + let orderings = orderings.map(\.sqlOrdering) + return orderWhenConnected { _ in orderings } } /// Sorts the fetched rows according to the given SQL string. @@ -1053,6 +1423,74 @@ extension OrderedRequest { } } +extension OrderedRequest where Self: TypedRequest, Self.RowDecoder: TableRecord { + public typealias DatabaseComponents = RowDecoder.DatabaseComponents + + /// Sorts the fetched rows according to the given SQL ordering term. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let name = Column("name") + /// } + /// } + /// + /// // SELECT * FROM player ORDER BY name + /// let request = Player.all().order(\.name) + /// + /// // SELECT * FROM player ORDER BY score DESC + /// let request = Player.all().order(\.score.desc) + /// ``` + /// + /// Any previous ordering is discarded: + /// + /// ```swift + /// // SELECT * FROM player ORDER BY name + /// let request = Player.all() + /// .order(\.score.desc) + /// .order(\.name) + /// ``` + public func order( + _ ordering: (DatabaseComponents) throws -> any SQLOrderingTerm + ) rethrows -> Self { + try order(ordering(Self.RowDecoder.databaseComponents)) + } + + /// Sorts the fetched rows according to the given SQL ordering terms. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let name = Column("name") + /// } + /// } + /// + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = Player.all() + /// .order { [$0.score.desc, $0.name] } + /// ``` + /// + /// Any previous ordering is discarded: + /// + /// ```swift + /// // SELECT * FROM player ORDER BY name + /// let request = Player.all() + /// .order { [$0.score.desc] } + /// .order { [$0.name] } + /// ``` + public func order( + _ orderings: (DatabaseComponents) throws -> [any SQLOrderingTerm] + ) rethrows -> Self { + try order(orderings(Self.RowDecoder.databaseComponents)) + } +} + // MARK: - JoinableRequest /// A request that can join and prefetch associations. @@ -1195,12 +1633,17 @@ extension JoinableRequest { /// For example, we can fetch only books whose author is French: /// /// ```swift - /// struct Author: TableRecord, FetchableRecord, Decodable { } - /// struct Book: TableRecord, FetchableRecord, Decodable { + /// struct Author: TableRecord { + /// enum Columns { + /// static let countryCode = Column("countryCode") + /// } + /// } + /// + /// struct Book: TableRecord, FetchableRecord { /// static let author = belongsTo(Author.self) /// } /// - /// let frenchAuthors = Book.author.filter(Column("countryCode") == "FR") + /// let frenchAuthors = Book.author.filter { $0.countryCode == "FR" } /// let bookInfos = try Book.all() /// .joining(required: frenchAuthors) /// .fetchAll(db) @@ -1217,9 +1660,19 @@ extension JoinableRequest where Self: SelectionRequest { /// For example: /// /// ```swift + /// struct Team: TableRecord { + /// enum Columns { + /// static let countryCode = Column("countryCode") + /// } + /// } + /// + /// struct Player: Decodable, TableRecord, FetchableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// /// // SELECT player.*, team.color /// // FROM player LEFT JOIN team ... - /// let teamColor = Player.team.select(Column("color")) + /// let teamColor = Player.team.select(\.color) /// let request = Player.all().annotated(withOptional: teamColor) /// ``` /// @@ -1245,9 +1698,9 @@ extension JoinableRequest where Self: SelectionRequest { /// ``JoinableRequest/joining(optional:)``: /// /// ```swift - /// let teamAlias = TableAlias() + /// let teamAlias = TableAlias() /// let request = Player.all() - /// .annotated(with: teamAlias[Column("color")]) + /// .annotated(with: teamAlias.color) /// .joining(optional: Player.team.aliased(teamAlias)) /// ``` public func annotated(withOptional association: A) -> Self where A.OriginRowDecoder == RowDecoder { @@ -1269,9 +1722,19 @@ extension JoinableRequest where Self: SelectionRequest { /// For example: /// /// ```swift + /// struct Team: TableRecord { + /// enum Columns { + /// static let color = Column("color") + /// } + /// } + /// + /// struct Player: Decodable, FetchableRecord, TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// /// // SELECT player.*, team.color /// // FROM player JOIN team ... - /// let teamColor = Player.team.select(Column("color")) + /// let teamColor = Player.team.select(\.color) /// let request = Player.all().annotated(withRequired: teamColor) /// ``` /// @@ -1297,9 +1760,9 @@ extension JoinableRequest where Self: SelectionRequest { /// ``JoinableRequest/joining(required:)``: /// /// ```swift - /// let teamAlias = TableAlias() + /// let teamAlias = TableAlias() /// let request = Player.all() - /// .annotated(with: teamAlias[Column("color")]) + /// .annotated(with: teamAlias.color]) /// .joining(required: Player.team.aliased(teamAlias)) /// ``` public func annotated(withRequired association: A) -> Self where A.OriginRowDecoder == RowDecoder { @@ -1328,7 +1791,7 @@ extension JoinableRequest where Self: SelectionRequest { /// /// ### Instance Methods /// -/// - ``TableRequest/aliased(_:)`` +/// - ``TableRequest/aliased(_:)-3k5h4`` /// - ``TableAlias`` /// /// ### The WITH Clause @@ -1337,12 +1800,12 @@ extension JoinableRequest where Self: SelectionRequest { /// /// ### The SELECT Clause /// -/// - ``SelectionRequest/annotated(with:)-4qcem`` -/// - ``SelectionRequest/annotated(with:)-6ehs4`` +/// - ``SelectionRequest/annotated(with:)-9wodv`` +/// - ``SelectionRequest/annotated(with:)-69r3`` /// - ``SelectionRequest/annotatedWhenConnected(with:)`` /// - ``distinct()`` -/// - ``SelectionRequest/select(_:)-30yzl`` -/// - ``SelectionRequest/select(_:)-7e2y5`` +/// - ``SelectionRequest/select(_:)-270ge`` +/// - ``SelectionRequest/select(_:)-4jw13`` /// - ``SelectionRequest/select(literal:)`` /// - ``SelectionRequest/select(sql:arguments:)`` /// - ``SelectionRequest/selectWhenConnected(_:)`` @@ -1350,12 +1813,12 @@ extension JoinableRequest where Self: SelectionRequest { /// ### The WHERE Clause /// /// - ``FilteredRequest/all()`` -/// - ``FilteredRequest/filter(_:)`` +/// - ``FilteredRequest/filter(_:)-7j0nw`` /// - ``TableRequest/filter(id:)`` /// - ``TableRequest/filter(ids:)`` /// - ``TableRequest/filter(key:)-1p9sq`` /// - ``TableRequest/filter(key:)-2te6v`` -/// - ``TableRequest/filter(keys:)-6ggt1`` +/// - ``TableRequest/filter(keys:)-9p9i5`` /// - ``TableRequest/filter(keys:)-8fbn9`` /// - ``FilteredRequest/filter(literal:)`` /// - ``FilteredRequest/filter(sql:arguments:)`` @@ -1366,21 +1829,21 @@ extension JoinableRequest where Self: SelectionRequest { /// /// ### The GROUP BY and HAVING Clauses /// -/// - ``AggregatingRequest/group(_:)-edak`` -/// - ``AggregatingRequest/group(_:)-4216o`` +/// - ``AggregatingRequest/group(_:)-5soxm`` +/// - ``AggregatingRequest/group(_:)-32exm`` /// - ``AggregatingRequest/group(literal:)`` /// - ``AggregatingRequest/group(sql:arguments:)`` /// - ``TableRequest/groupByPrimaryKey()`` /// - ``AggregatingRequest/groupWhenConnected(_:)`` -/// - ``AggregatingRequest/having(_:)`` +/// - ``AggregatingRequest/having(_:)-27hlo`` /// - ``AggregatingRequest/having(literal:)`` /// - ``AggregatingRequest/having(sql:arguments:)`` /// - ``AggregatingRequest/havingWhenConnected(_:)`` /// /// ### The ORDER BY Clause /// -/// - ``OrderedRequest/order(_:)-63rzl`` -/// - ``OrderedRequest/order(_:)-6co0m`` +/// - ``OrderedRequest/order(_:)-5q7wj`` +/// - ``OrderedRequest/order(_:)-711zj`` /// - ``OrderedRequest/order(literal:)`` /// - ``OrderedRequest/order(sql:arguments:)`` /// - ``OrderedRequest/orderWhenConnected(_:)`` @@ -1411,6 +1874,23 @@ extension JoinableRequest where Self: SelectionRequest { /// - ``SelectionRequest`` /// - ``TableRequest`` /// - ``TypedRequest`` +/// +/// ### Legacy APIs +/// +/// It is recommended to prefer the closure-based apis defined above, as +/// well as record aliases over anonymous aliases. +/// +/// - ``TableRequest/aliased(_:)-772vb`` +/// - ``SelectionRequest/annotated(with:)-4qcem`` +/// - ``SelectionRequest/annotated(with:)-6ehs4`` +/// - ``FilteredRequest/filter(_:)-48a4t`` +/// - ``AggregatingRequest/group(_:)-edak`` +/// - ``AggregatingRequest/group(_:)-4216o`` +/// - ``AggregatingRequest/having(_:)-2ssg9`` +/// - ``OrderedRequest/order(_:)-63rzl`` +/// - ``OrderedRequest/order(_:)-6co0m`` +/// - ``SelectionRequest/select(_:)-30yzl`` +/// - ``SelectionRequest/select(_:)-7e2y5`` public protocol DerivableRequest: AggregatingRequest, FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest @@ -1420,11 +1900,17 @@ public protocol DerivableRequest: AggregatingRequest, FilteredReques /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// /// // SELECT DISTINCT * FROM player /// let request = Player.all().distinct() /// /// // SELECT DISTINCT name FROM player - /// let request = Player.select(Column("name")).distinct() + /// let request = Player.select(\.name).distinct() /// ``` func distinct() -> Self @@ -1437,18 +1923,31 @@ public protocol DerivableRequest: AggregatingRequest, FilteredReques /// latest message: /// /// ```swift - /// let latestMessageRequest = Message - /// .annotated(with: max(Column("date"))) - /// .group(Column("chatID")) + /// struct Chat: TableRecord { + /// enum Columns { + /// static let id = Column("id") + /// } + /// } /// - /// let latestMessageCTE = CommonTableExpression( + /// struct Message: TableRecord { + /// enum Columns { + /// static let date = Column("date") + /// static let chatId = Column("chatId") + /// } + /// } + /// + /// let latestMessageRequest = Message + /// .annotated { max($0.date) } + /// .group(\.chatId) + /// + /// let latestMessageCTE = CommonTableExpression( /// named: "latestMessage", /// request: latestMessageRequest) /// /// let latestMessageAssociation = Chat.association( /// to: latestMessageCTE, /// on: { chat, latestMessage in - /// chat[Column("id")] == latestMessage[Column("chatID")] + /// chat.id == latestMessage.chatId /// }) /// /// // WITH latestMessage AS diff --git a/GRDB/QueryInterface/SQL/Column.swift b/GRDB/QueryInterface/SQL/Column.swift index 535166789..0ca14d630 100644 --- a/GRDB/QueryInterface/SQL/Column.swift +++ b/GRDB/QueryInterface/SQL/Column.swift @@ -39,9 +39,18 @@ extension ColumnExpression { /// SQL generated by the query interface. /// /// For example, see how `Column("total").detached` makes it possible to - /// sort this query, when a raw `Column("total")` could not: + /// sort this query: /// /// ```swift + /// struct Player: TableRecord { + /// static let team = belongsTo(Team.self) + /// + /// enum Columns { + /// static let score = Column("score") + /// static let bonus = Column("bonus") + /// } + /// } + /// /// // SELECT player.*, /// // (player.score + player.bonus) AS total, /// // team.* @@ -50,9 +59,9 @@ extension ColumnExpression { /// // ORDER BY total, player.name /// // ~~~~~ /// let request = Player - /// .annotated(with: (Column("score") + Column("bonus")).forKey("total")) + /// .annotated { ($0.score + $0.bonus).forKey("total") } /// .including(required: Player.team) - /// .order(Column("total").detached, Column("name")) + /// .order { [Column("total").detached, $0.name] } /// ``` public var detached: SQLExpression { SQL(sql: name.quotedDatabaseIdentifier).sqlExpression @@ -61,6 +70,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 } } @@ -69,14 +85,29 @@ extension ColumnExpression where Self == Column { /// For example: /// /// ```swift -/// struct Player: TableRecord { +/// struct Player: FetchableRecord, TableRecord { /// var score: Int +/// +/// enum Columns { +/// static let score = Column("score") +/// } /// } /// -/// let maximumScore = try dbQueue.read { db in -/// // SELECT MAX(score) FROM player +/// try dbQueue.read { db in +/// // DELETE FROM player WHERE score = 0 /// try Player -/// .select(max(Column("score")), as: Int.self) +/// .filter { $0.score == 0 } +/// .deleteAll(db) +/// +/// // SELECT * FROM player ORDER BY score DESC LIMIT 10 +/// let bestPlayers = try Player +/// .order(\.score) +/// .limit(10) +/// .fetchAll(db) +/// +/// // SELECT MAX(score) FROM player +/// let maximumScore = try Player +/// .select({ max($0.score) }, as: Int.self) /// .fetchOne(db) /// } /// ``` @@ -116,11 +147,13 @@ extension Column: ColumnExpression { } /// Support for column enums: /// -/// struct Player { -/// enum Columns: String, ColumnExpression { -/// case id, name, score -/// } +/// ```swift +/// struct Player { +/// enum Columns: String, ColumnExpression { +/// case id, name, score /// } +/// } +/// ``` extension ColumnExpression where Self: RawRepresentable, Self.RawValue == String { public var name: String { rawValue } } diff --git a/GRDB/QueryInterface/SQL/DatabasePromise.swift b/GRDB/QueryInterface/SQL/DatabasePromise.swift index 9d497b584..7fb7c3ede 100644 --- a/GRDB/QueryInterface/SQL/DatabasePromise.swift +++ b/GRDB/QueryInterface/SQL/DatabasePromise.swift @@ -23,20 +23,20 @@ /// see SQLRelation.filterPromise. struct DatabasePromise { /// Returns the resolved value. - let resolve: (Database) throws -> T + let resolve: @Sendable (Database) throws -> T /// Creates a promise that resolves to a value. - init(value: T) { + init(value: T) where T: Sendable { self.resolve = { _ in value } } /// Creates a promise from a closure. - init(_ resolve: @escaping (Database) throws -> T) { + init(_ resolve: @escaping @Sendable (Database) throws -> T) { self.resolve = resolve } /// Returns a promise whose value is transformed by the given closure. - func map(_ transform: @escaping (T) throws -> U) -> DatabasePromise { + func map(_ transform: @escaping @Sendable (T) throws -> U) -> DatabasePromise { DatabasePromise { db in try transform(resolve(db)) } diff --git a/GRDB/QueryInterface/SQL/SQLAssociation.swift b/GRDB/QueryInterface/SQL/SQLAssociation.swift index 4d9a8d30c..ea31e2f8d 100644 --- a/GRDB/QueryInterface/SQL/SQLAssociation.swift +++ b/GRDB/QueryInterface/SQL/SQLAssociation.swift @@ -49,7 +49,7 @@ /// through: Pivot1.hasMany(Pivot2.self), /// via: Pivot2.belongsTo(Destination.self))) /// Origin.including(required: association) -public struct _SQLAssociation { +public struct _SQLAssociation: Sendable { // All steps, from pivot to destination. Never empty. private(set) var steps: [SQLAssociationStep] var keyPath: [String] { steps.map(\.keyName) } diff --git a/GRDB/QueryInterface/SQL/SQLCollection.swift b/GRDB/QueryInterface/SQL/SQLCollection.swift index 98435bc02..a3bf6fabb 100644 --- a/GRDB/QueryInterface/SQL/SQLCollection.swift +++ b/GRDB/QueryInterface/SQL/SQLCollection.swift @@ -39,7 +39,7 @@ struct SQLCollection { extension SQLCollection { /// Returns a qualified collection. - func qualified(with alias: TableAlias) -> SQLCollection { + func qualified(with alias: TableAliasBase) -> SQLCollection { switch impl { case .subquery, .table: diff --git a/GRDB/QueryInterface/SQL/SQLExpression.swift b/GRDB/QueryInterface/SQL/SQLExpression.swift index eb63e59c4..36116c7d5 100644 --- a/GRDB/QueryInterface/SQL/SQLExpression.swift +++ b/GRDB/QueryInterface/SQL/SQLExpression.swift @@ -29,12 +29,18 @@ /// SQL("DATE(\(value))").sqlExpression /// } /// +/// struct Player: TableRecord { +/// enum Columns { +/// static let createdAt = Column("createdAt") +/// } +/// } +/// /// // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23' -/// let request = Player.filter(date(Column("createdAt")) == "2020-01-23") +/// let request = Player.filter { date($0.createdAt) == "2020-01-23" } /// ``` /// /// Related SQLite documentation: -public struct SQLExpression { +public struct SQLExpression: Sendable { private var impl: Impl /// The preferred interpretation of the expression in JSON @@ -68,7 +74,7 @@ public struct SQLExpression { /// /// player.id /// player.name - case qualifiedColumn(String, TableAlias) + case qualifiedColumn(String, TableAliasBase) /// A database value. /// @@ -151,7 +157,7 @@ public struct SQLExpression { /// A table full-text match. /// /// MATCH - indirect case tableMatch(TableAlias, SQLExpression) + indirect case tableMatch(TableAliasBase, SQLExpression) /// A logical `NOT` operator. /// @@ -199,7 +205,7 @@ public struct SQLExpression { /// player.id /// document.rowid /// country.code - case qualifiedFastPrimaryKey(TableAlias) + case qualifiedFastPrimaryKey(TableAliasBase) /// An expression that is true iff the row exists: /// @@ -207,10 +213,10 @@ public struct SQLExpression { /// - For tables WITHOUT ROWID, it is true iff any primary key column is not null. /// - For views, it is true iff any column is not null. /// - For CTEs, it is not implemented yet. - case qualifiedExists(TableAlias, isNegated: Bool) + case qualifiedExists(TableAliasBase, isNegated: Bool) /// Returns a qualified expression - func qualified(with alias: TableAlias) -> Impl { + func qualified(with alias: TableAliasBase) -> Impl { switch self { case .databaseValue, .qualifiedColumn, @@ -316,12 +322,17 @@ public struct SQLExpression { /// Use it with the `joined(operator:)` method. For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let bonus = Column("bonus") + /// } + /// } + /// /// // SELECT score + bonus + 1000 FROM player - /// let values = [ - /// scoreColumn, - /// bonusColumn, - /// 1000.databaseValue] - /// let request = Player.select(values.joined(operator: .add)) + /// let request = Player.select { + /// [$0.score, $0.bonus, 1000.databaseValue].joined(operator: .add) + /// } /// ``` public struct AssociativeBinaryOperator: Hashable, Sendable { /// The SQL operator @@ -637,7 +648,7 @@ extension SQLExpression { /// /// player.id /// player.name - static func qualifiedColumn(_ name: String, _ alias: TableAlias) -> Self { + static func qualifiedColumn(_ name: String, _ alias: TableAliasBase) -> Self { self.init(impl: .qualifiedColumn(name, alias)) } @@ -860,7 +871,7 @@ extension SQLExpression { /// A table full-text match. /// ///
MATCH - static func tableMatch(_ alias: TableAlias, _ expression: SQLExpression) -> Self { + static func tableMatch(_ alias: TableAliasBase, _ expression: SQLExpression) -> Self { self.init(impl: .tableMatch(alias, expression)) } @@ -954,6 +965,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 +1027,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. @@ -1127,7 +1159,7 @@ extension SQLExpression { /// player.id /// document.rowid /// country.code - static func qualifiedFastPrimaryKey(_ alias: TableAlias) -> Self { + static func qualifiedFastPrimaryKey(_ alias: TableAliasBase) -> Self { self.init(impl: .qualifiedFastPrimaryKey(alias)) } @@ -1137,7 +1169,7 @@ extension SQLExpression { /// - For tables WITHOUT ROWID, it is true iff any primary key column is not null. /// - For views, it is true iff any column is not null. /// - For CTEs, it is not implemented yet. - static func qualifiedExists(_ alias: TableAlias) -> Self { + static func qualifiedExists(_ alias: TableAliasBase) -> Self { self.init(impl: .qualifiedExists(alias, isNegated: false)) } } @@ -1146,7 +1178,7 @@ extension SQLExpression { extension SQLExpression { /// Returns a qualified expression - func qualified(with alias: TableAlias) -> Self { + func qualified(with alias: TableAliasBase) -> Self { .init(impl: impl.qualified(with: alias), preferredJSONInterpretation: preferredJSONInterpretation) } @@ -1191,7 +1223,7 @@ extension SQLExpression { /// - parameter acceptsBijection: If true, expressions that define a /// bijection on a column return this column. For example: `-score` /// returns `score`. - func column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool = false) throws -> String? { + func column(_ db: Database, for alias: TableAliasBase, acceptsBijection: Bool = false) throws -> String? { switch impl { case let .qualifiedColumn(name, a): if alias == a { @@ -1478,7 +1510,7 @@ extension SQLExpression { /// /// // SELECT * FROM "player" WHERE "name" = 'Arthur' LIMIT 1 /// try Player.filter(Column("name") == "Arthur").fetchOne(db) - func identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set { + func identifyingColums(_ db: Database, for alias: TableAliasBase) throws -> Set { switch impl { case let .rowValue(expressions): assert(!expressions.isEmpty) @@ -1546,7 +1578,7 @@ extension SQLExpression { /// let request = Player.filter(keys: [1, 2, 3]) /// let regionObservation = DatabaseRegionObservation(tracking: request) /// let valueObservation = ValueObservation.tracking(request.fetchAll) - func identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set? { + func identifyingRowIDs(_ db: Database, for alias: TableAliasBase) throws -> Set? { switch impl { case let .databaseValue(dbValue): if dbValue.isNull || dbValue == false.databaseValue { @@ -1953,7 +1985,7 @@ struct SQLSimpleFunctionInvocation { isPure && arguments.allSatisfy(\.isConstantInRequest) } - func qualified(with alias: TableAlias) -> Self { + func qualified(with alias: TableAliasBase) -> Self { SQLSimpleFunctionInvocation( name: name, arguments: arguments.map { $0.qualified(with: alias) }, @@ -1961,7 +1993,7 @@ struct SQLSimpleFunctionInvocation { isJSONValue: isJSONValue) } - func column(_ db: Database, for alias: TableAlias) throws -> String? { + func column(_ db: Database, for alias: TableAliasBase) throws -> String? { let name = name.uppercased() if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 { return try arguments[0].column(db, for: alias, acceptsBijection: true) @@ -1989,7 +2021,7 @@ struct SQLAggregateFunctionInvocation { var arguments: [SQLExpression] var isDistinct = false var ordering: SQLOrdering? = nil // SQLite 3.44.0+ - var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) SQLite 3.30+ + var filter: SQLExpression? = nil // @available(iOS 14, macOS 10.16, tvOS 14, *) SQLite 3.30+ /// A boolean value indicating if a function is known to return a /// JSON value. @@ -1997,7 +2029,7 @@ struct SQLAggregateFunctionInvocation { /// A false value does not provide any information. var isJSONValue: Bool - func qualified(with alias: TableAlias) -> Self { + func qualified(with alias: TableAliasBase) -> Self { SQLAggregateFunctionInvocation( name: name, arguments: arguments.map { $0.qualified(with: alias) }, @@ -2099,14 +2131,15 @@ 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]) } } } #else - @available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS + @available(iOS 16, tvOS 17, watchOS 9, *) // SQLite 3.38+ with exceptions for macOS /// Returns an expression suitable in JSON building contexts. var jsonBuilderExpression: SQLExpression { switch preferredJSONInterpretation { @@ -2116,8 +2149,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 +2170,14 @@ public protocol SQLExpressible { } extension SQLExpressible where Self == Column { - /// The hidden rowID column + /// The hidden rowID column. + /// + /// For example: + /// + /// ```swift + /// // SELECT rowid FROM player + /// let rowids = try Player.select(.rowID).fetchSet(db) + /// ``` public static var rowID: Self { Column.rowID } } @@ -2168,6 +2209,7 @@ extension SQLExpressible where Self == Column { /// - ``average(_:filter:)`` /// - ``capitalized`` /// - ``cast(_:as:)-1dmu3`` +/// - ``coalesce(_:)`` /// - ``count(_:)`` /// - ``count(distinct:)`` /// - ``dateTime(_:_:)`` @@ -2178,8 +2220,10 @@ extension SQLExpressible where Self == Column { /// - ``localizedLowercased`` /// - ``localizedUppercased`` /// - ``lowercased`` +/// - ``min(_:_:_:)`` /// - ``min(_:)`` /// - ``min(_:filter:)`` +/// - ``max(_:_:_:)`` /// - ``max(_:)`` /// - ``max(_:filter:)`` /// - ``sum(_:)`` @@ -2248,15 +2292,21 @@ extension Sequence where Element: SQLSpecificExpressible { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let isRegistered = Column("isRegistered") + /// static let score = Column("score") + /// static let name = Column("name") + /// } + /// } + /// /// // SELECT * FROM player - /// // WHERE (registered + /// // WHERE (isRegistered /// // AND (score >= 1000) /// // AND (name IS NOT NULL)) - /// let conditions = [ - /// Column("registered"), - /// Column("score") >= 1000, - /// Column("name") != nil] - /// Player.filter(conditions.joined(operator: .and)) + /// Player.filter { + /// [$0.isRegistered, $0.score >= 1000, $0.name != nil].joined(operator: .and) + /// } /// ``` /// /// When the sequence is empty, `joined(operator:)` returns the neutral @@ -2279,15 +2329,21 @@ extension Sequence where Element == any SQLSpecificExpressible { /// For example: /// /// ``` + /// struct Player: TableRecord { + /// enum Columns { + /// static let isRegistered = Column("isRegistered") + /// static let score = Column("score") + /// static let name = Column("name") + /// } + /// } + /// /// // SELECT * FROM player - /// // WHERE (registered + /// // WHERE (isRegistered /// // AND (score >= 1000) /// // AND (name IS NOT NULL)) - /// let conditions = [ - /// Column("registered"), - /// Column("score") >= 1000, - /// Column("name") != nil] - /// Player.filter(conditions.joined(operator: .and)) + /// Player.filter { + /// [$0.isRegistered, $0.score >= 1000, $0.name != nil].joined(operator: .and) + /// } /// ``` /// /// When the sequence is empty, `joined(operator:)` returns the neutral @@ -2329,13 +2385,13 @@ extension SQLSpecificExpressible { } #elseif !GRDBCIPHER /// An ordering term for ascending order (nulls last). - @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+ + @available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+ public var ascNullsLast: SQLOrdering { .ascNullsLast(sqlExpression) } /// An ordering term for descending order (nulls first). - @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+ + @available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+ public var descNullsFirst: SQLOrdering { .descNullsFirst(sqlExpression) } @@ -2350,9 +2406,17 @@ extension SQLSpecificExpressible { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// static let bonus = Column("bonus") + /// } + /// } + /// /// // SELECT (score + bonus) AS totalScore FROM player - /// let totalScore = (Column("score") * Column("bonus")).forKey("totalScore") - /// let request = Player.select(totalScore) + /// let request = Player.select { + /// ($0.score * $0.bonus).forKey("totalScore") + /// } /// ``` /// /// If you need to refer to the aliased column in another part of a request, @@ -2363,7 +2427,9 @@ extension SQLSpecificExpressible { /// // FROM player /// // ORDER BY totalScore /// let request = Player - /// .select(totalScore) + /// .select { + /// ($0.score * $0.bonus).forKey("totalScore") + /// } /// .order(Column("totalScore").detached) /// ``` public func forKey(_ key: String) -> SQLSelection { @@ -2387,9 +2453,17 @@ extension SQLSpecificExpressible { /// For example: /// /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let email = Column("email") + /// } + /// } + /// /// // SELECT * FROM player /// // WHERE email = 'contact@example.com' COLLATE NOCASE - /// Player.filter(Column("email").collating(.nocase) == "contact@example.com") + /// Player.filter { + /// $0.email.collating(.nocase) == "contact@example.com" + /// } /// ``` public func collating(_ collation: Database.CollationName) -> SQLExpression { .collated(sqlExpression, collation) diff --git a/GRDB/QueryInterface/SQL/SQLFunctions.swift b/GRDB/QueryInterface/SQL/SQLFunctions.swift index 08a1a39ea..b30fe89b5 100644 --- a/GRDB/QueryInterface/SQL/SQLFunctions.swift +++ b/GRDB/QueryInterface/SQL/SQLFunctions.swift @@ -11,7 +11,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression { } #if GRDBCUSTOMSQLITE || GRDBCIPHER -/// The `AVG` SQL function. +/// The `AVG` SQL aggregate function. /// /// For example: /// @@ -26,7 +26,7 @@ public func average( .aggregateFunction("AVG", [value.sqlExpression], filter: filter?.sqlExpression) } #else -/// The `AVG` SQL function. +/// The `AVG` SQL aggregate function. /// /// For example: /// @@ -34,7 +34,7 @@ public func average( /// // AVG(length) FILTER (WHERE length > 0) /// average(Column("length"), filter: Column("length") > 0) /// ``` -@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+ +@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+ public func average( _ value: some SQLSpecificExpressible, filter: some SQLSpecificExpressible) @@ -44,7 +44,7 @@ public func average( filter: filter.sqlExpression) } -/// The `AVG` SQL function. +/// The `AVG` SQL aggregate function. /// /// For example: /// @@ -71,6 +71,32 @@ public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Dat .cast(expression.sqlExpression, as: storageClass) } +/// The `COALESCE` SQL function. +/// +/// For example: +/// +/// ```swift +/// // COALESCE(value1, value2, ...) +/// coalesce([Column("value1"), Column("value2"), ...]) +/// ``` +/// +/// Unlike the SQL function, `coalesce` accepts any number of arguments. +/// When `values` is empty, the result is `NULL`. When `values` contains a +/// single value, the result is this value. `COALESCE` is used from +/// two values upwards. +public func coalesce(_ values: some Collection) -> SQLExpression { + // SQLite COALESCE wants at least two arguments. + // There is no reason to apply the same limitation. + guard let value = values.first else { + return .null + } + if values.count > 1 { + return .function("COALESCE", values.map { $0.sqlExpression }) + } else { + return value.sqlExpression + } +} + /// The `COUNT` SQL function. /// /// For example: @@ -121,8 +147,24 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression { .function("LENGTH", [value.sqlExpression]) } +/// The `MAX` SQL multi-argument function. +/// +/// For example: +/// +/// ```swift +/// // MAX(score, 1000) +/// max(Column("score"), 1000) +/// ``` +public func max( + _ value1: any SQLSpecificExpressible, + _ value2: any SQLExpressible, + _ values: any SQLExpressible... +) -> SQLExpression { + .simpleFunction("MAX", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression)) +} + #if GRDBCUSTOMSQLITE || GRDBCIPHER -/// The `MAX` SQL function. +/// The `MAX` SQL aggregate function. /// /// For example: /// @@ -137,7 +179,7 @@ public func max( .aggregateFunction("MAX", [value.sqlExpression], filter: filter?.sqlExpression) } #else -/// The `MAX` SQL function. +/// The `MAX` SQL aggregate function. /// /// For example: /// @@ -145,7 +187,7 @@ public func max( /// // MAX(score) FILTER (WHERE score < 0) /// max(Column("score"), filter: Column("score") < 0) /// ``` -@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+ +@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+ public func max( _ value: some SQLSpecificExpressible, filter: some SQLSpecificExpressible) @@ -153,7 +195,7 @@ public func max( .aggregateFunction("MAX", [value.sqlExpression], filter: filter.sqlExpression) } -/// The `MAX` SQL function. +/// The `MAX` SQL aggregate function. /// /// For example: /// @@ -166,8 +208,24 @@ public func max(_ value: some SQLSpecificExpressible) -> SQLExpression { } #endif +/// The `MIN` SQL multi-argument function. +/// +/// For example: +/// +/// ```swift +/// // MIN(score, 1000) +/// min(Column("score"), 1000) +/// ``` +public func min( + _ value1: any SQLSpecificExpressible, + _ value2: any SQLExpressible, + _ values: any SQLExpressible... +) -> SQLExpression { + .simpleFunction("MIN", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression)) +} + #if GRDBCUSTOMSQLITE || GRDBCIPHER -/// The `MIN` SQL function. +/// The `MIN` SQL aggregate function. /// /// For example: /// @@ -182,7 +240,7 @@ public func min( .aggregateFunction("MIN", [value.sqlExpression], filter: filter?.sqlExpression) } #else -/// The `MIN` SQL function. +/// The `MIN` SQL aggregate function. /// /// For example: /// @@ -190,7 +248,7 @@ public func min( /// // MIN(score) FILTER (WHERE score > 0) /// min(Column("score"), filter: Column("score") > 0) /// ``` -@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+ +@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+ public func min( _ value: some SQLSpecificExpressible, filter: some SQLSpecificExpressible) @@ -198,7 +256,7 @@ public func min( .aggregateFunction("MIN", [value.sqlExpression], filter: filter.sqlExpression) } -/// The `MIN` SQL function. +/// The `MIN` SQL aggregate function. /// /// For example: /// @@ -212,7 +270,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression { #endif #if GRDBCUSTOMSQLITE || GRDBCIPHER -/// The `SUM` SQL function. +/// The `SUM` SQL aggregate function. /// /// For example: /// @@ -236,7 +294,7 @@ public func sum( filter: filter?.sqlExpression) } #else -/// The `SUM` SQL function. +/// The `SUM` SQL aggregate function. /// /// For example: /// @@ -248,7 +306,7 @@ public func sum( /// See also ``total(_:)``. /// /// Related SQLite documentation: . -@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+ +@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+ public func sum( _ value: some SQLSpecificExpressible, filter: some SQLSpecificExpressible) @@ -258,7 +316,7 @@ public func sum( filter: filter.sqlExpression) } -/// The `SUM` SQL function. +/// The `SUM` SQL aggregate function. /// /// For example: /// @@ -276,7 +334,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression { #endif #if GRDBCUSTOMSQLITE || GRDBCIPHER -/// The `TOTAL` SQL function. +/// The `TOTAL` SQL aggregate function. /// /// For example: /// @@ -300,7 +358,7 @@ public func total( filter: filter?.sqlExpression) } #else -/// The `TOTAL` SQL function. +/// The `TOTAL` SQL aggregate function. /// /// For example: /// @@ -312,7 +370,7 @@ public func total( /// See also ``total(_:)``. /// /// Related SQLite documentation: . -@available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // SQLite 3.30+ +@available(iOS 14, macOS 10.16, tvOS 14, *) // SQLite 3.30+ public func total( _ value: some SQLSpecificExpressible, filter: some SQLSpecificExpressible) @@ -322,7 +380,7 @@ public func total( filter: filter.sqlExpression) } -/// The `TOTAL` SQL function. +/// The `TOTAL` SQL aggregate function. /// /// For example: /// diff --git a/GRDB/QueryInterface/SQL/SQLOrdering.swift b/GRDB/QueryInterface/SQL/SQLOrdering.swift index e7b18f974..b3b536309 100644 --- a/GRDB/QueryInterface/SQL/SQLOrdering.swift +++ b/GRDB/QueryInterface/SQL/SQLOrdering.swift @@ -12,7 +12,7 @@ /// function arguments, prefer the ``SQLOrderingTerm`` protocol. /// /// Related SQLite documentation: -public struct SQLOrdering { +public struct SQLOrdering: Sendable { private var impl: Impl private enum Impl { @@ -86,7 +86,7 @@ extension SQLOrdering { } extension SQLOrdering { - func qualified(with alias: TableAlias) -> SQLOrdering { + func qualified(with alias: TableAliasBase) -> SQLOrdering { switch impl { case .expression(let expression): return .expression(expression.qualified(with: alias)) diff --git a/GRDB/QueryInterface/SQL/SQLRelation.swift b/GRDB/QueryInterface/SQL/SQLRelation.swift index 9f01841c2..fcbb7b884 100644 --- a/GRDB/QueryInterface/SQL/SQLRelation.swift +++ b/GRDB/QueryInterface/SQL/SQLRelation.swift @@ -90,7 +90,7 @@ /// // JOIN passport ON passport.citizenId = citizens.id /// // AND passport.countryCode IN ('BE', 'DE', 'FR', ...); /// Country.including(all: Country.citizens) -struct SQLRelation { +struct SQLRelation: Sendable { struct Child: Refinable { enum Kind { // Record.including(optional: association) @@ -171,7 +171,7 @@ struct SQLRelation { var source: SQLSource var selectionPromise: DatabasePromise<[SQLSelection]> var filterPromise: DatabasePromise? - var ordering: SQLRelation.Ordering = SQLRelation.Ordering() + var ordering = SQLRelation.Ordering() var ctes: OrderedDictionary = [:] // See also `allCTEs` var children: OrderedDictionary = [:] @@ -187,7 +187,7 @@ extension SQLRelation { /// Convenience factory methods which selects all rows from a table. static func all( fromTable tableName: String, - selection: @escaping (Database) -> [SQLSelection] = { _ in [.allColumns] }) + selection: @escaping @Sendable (Database) -> [SQLSelection] = { _ in [.allColumns] }) -> Self { SQLRelation( @@ -197,7 +197,7 @@ extension SQLRelation { } extension SQLRelation: Refinable { - func selectWhenConnected(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self { + func selectWhenConnected(_ selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self { with { $0.selectionPromise = DatabasePromise(selection) } @@ -228,7 +228,7 @@ extension SQLRelation: Refinable { } } - func annotatedWhenConnected(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self { + func annotatedWhenConnected(with selection: @escaping @Sendable (Database) throws -> [SQLSelection]) -> Self { with { let old = $0.selectionPromise $0.selectionPromise = DatabasePromise { db in @@ -242,7 +242,7 @@ extension SQLRelation: Refinable { annotatedWhenConnected(with: { _ in selection }) } - func filterWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { + func filterWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self { with { if let old = $0.filterPromise { $0.filterPromise = DatabasePromise { db in @@ -259,7 +259,7 @@ extension SQLRelation: Refinable { filterWhenConnected { _ in predicate } } - func orderWhenConnected(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self { + func orderWhenConnected(_ orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) -> Self { with { $0.ordering = SQLRelation.Ordering(orderings: orderings) } @@ -313,13 +313,13 @@ extension SQLRelation: Refinable { } } - func groupWhenConnected(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self { + func groupWhenConnected(_ expressions: @escaping @Sendable (Database) throws -> [SQLExpression]) -> Self { with { $0.groupPromise = DatabasePromise(expressions) } } - func havingWhenConnected(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self { + func havingWhenConnected(_ predicate: @escaping @Sendable (Database) throws -> SQLExpression) -> Self { with { if let old = $0.havingExpressionPromise { $0.havingExpressionPromise = DatabasePromise { db in @@ -331,7 +331,7 @@ extension SQLRelation: Refinable { } } - func aliased(_ alias: TableAlias) -> Self { + func aliased(_ alias: TableAliasBase) -> Self { with { $0.source = $0.source.aliased(alias) } @@ -636,7 +636,7 @@ extension SQLRelation { } // - guard selection.allSatisfy(\.isTriviallyCountable) else { + if selection.contains(where: \.requiresTrivialCount) { return try fetchTrivialCount(db) } @@ -672,11 +672,11 @@ struct SQLLimit { // MARK: - SQLSource -struct SQLSource { +struct SQLSource: Sendable { var tableName: String - var alias: TableAlias? + var alias: TableAliasBase? - func aliased(_ alias: TableAlias) -> SQLSource { + func aliased(_ alias: TableAliasBase) -> SQLSource { if let sourceAlias = self.alias { alias.becomeProxy(of: sourceAlias) return self @@ -691,7 +691,7 @@ struct SQLSource { extension SQLRelation { /// SQLRelation.Ordering provides the order clause to SQLRelation. - struct Ordering { + struct Ordering: Sendable { private enum Element { case terms(DatabasePromise<[SQLOrdering]>) case ordering(SQLRelation.Ordering) @@ -705,7 +705,7 @@ extension SQLRelation { } } - func qualified(with alias: TableAlias) -> Element { + func qualified(with alias: TableAliasBase) -> Element { switch self { case .terms(let terms): return .terms(terms.map { $0.map { $0.qualified(with: alias) } }) @@ -740,7 +740,7 @@ extension SQLRelation { isReversed: false) } - init(orderings: @escaping (Database) throws -> [SQLOrdering]) { + init(orderings: @escaping @Sendable (Database) throws -> [SQLOrdering]) { self.init( elements: [.terms(DatabasePromise(orderings))], isReversed: false) @@ -752,7 +752,7 @@ extension SQLRelation { isReversed: !isReversed) } - func qualified(with alias: TableAlias) -> Ordering { + func qualified(with alias: TableAliasBase) -> Ordering { Ordering( elements: elements.map { $0.qualified(with: alias) }, isReversed: isReversed) @@ -796,7 +796,7 @@ extension SQLRelation { /// // SELECT * FROM book WHERE author.id = 1 /// // ~~~~~~~~~~~~~ /// author.request(for: Author.books) -enum SQLAssociationCondition { +enum SQLAssociationCondition: Sendable { /// A condition based on a foreign key. case foreignKey(SQLForeignKeyCondition) @@ -814,7 +814,7 @@ enum SQLAssociationCondition { /// player[Column("id")] == bonus[Column("playerID")] /// }) /// Player.with(bonus).joining(required: association) - case expression((_ left: TableAlias, _ right: TableAlias) -> SQLExpression?) + case expression(@Sendable (_ left: TableAliasBase, _ right: TableAliasBase) -> SQLExpression?) /// The condition that does not constrain the two associated tables /// in any way. @@ -831,8 +831,8 @@ enum SQLAssociationCondition { func joinExpression( _ db: Database, - leftAlias: TableAlias, - rightAlias: TableAlias) + leftAlias: TableAliasBase, + rightAlias: TableAliasBase) throws -> SQLExpression? { switch self { @@ -923,10 +923,9 @@ extension JoinMapping { /// - precondition: leftRows contains all mapping left columns. /// - precondition: All rows have the same layout: a column index returned /// by `index(forColumn:)` refers to the same column in all rows. - func joinExpression(leftRows: Rows) - -> SQLExpression - where Rows: Collection, Rows.Element: ColumnAddressable - { + func joinExpression( + leftRows: some Collection + ) -> SQLExpression { guard let firstLeftRow = leftRows.first else { // We could return `false.sqlExpression`. // @@ -1000,7 +999,7 @@ extension JoinMapping { /// JOIN operator. /// - parameter rightAlias: A TableAlias for the table on the right of the /// JOIN operator. - func joinExpression(leftAlias: TableAlias, rightAlias: TableAlias) -> SQLExpression { + func joinExpression(leftAlias: TableAliasBase, rightAlias: TableAliasBase) -> SQLExpression { map { rightAlias[$0.right] == leftAlias[$0.left] }.joined(operator: .and) } } @@ -1027,9 +1026,6 @@ extension Row: ColumnAddressable { /// PersistenceContainer has columns extension PersistenceContainer: ColumnAddressable { func index(forColumn column: String) -> String? { column } - func databaseValue(at column: String) -> DatabaseValue { - self[caseInsensitive: column]?.databaseValue ?? .null - } } // MARK: - Merging diff --git a/GRDB/QueryInterface/SQL/SQLSelection.swift b/GRDB/QueryInterface/SQL/SQLSelection.swift index c4ff88045..4a414109d 100644 --- a/GRDB/QueryInterface/SQL/SQLSelection.swift +++ b/GRDB/QueryInterface/SQL/SQLSelection.swift @@ -15,7 +15,7 @@ /// function arguments, prefer the ``SQLSelectable`` protocol. /// /// Related SQLite documentation: -public struct SQLSelection { +public struct SQLSelection: Sendable { private var impl: Impl /// The private implementation of the public `SQLSelection`. @@ -24,8 +24,14 @@ public struct SQLSelection { case allColumns /// All columns, qualified: `player.*` - case qualifiedAllColumns(TableAlias) + case qualifiedAllColumns(TableAliasBase) + /// All columns but the specified ones + case allColumnsExcluding(Set) + + /// All columns but the specified ones, qualified. + case qualifiedAllColumnsExcluding(TableAliasBase, Set) + /// An expression case expression(SQLExpression) @@ -41,11 +47,24 @@ public struct SQLSelection { /// All columns: `*` static let allColumns = SQLSelection(impl: .allColumns) + /// All columns but the specified ones. + static func allColumnsExcluding(_ excludedColumns: Set) -> Self { + SQLSelection(impl: .allColumnsExcluding(excludedColumns)) + } + /// All columns, qualified: `player.*` - static func qualifiedAllColumns(_ alias: TableAlias) -> Self { + static func qualifiedAllColumns(_ alias: TableAliasBase) -> Self { self.init(impl: .qualifiedAllColumns(alias)) } + /// All columns but the specified ones, qualified. + static func qualifiedAllColumnsExcluding( + _ alias: TableAliasBase, + _ excludedColumns: Set + ) -> Self { + self.init(impl: .qualifiedAllColumnsExcluding(alias, excludedColumns)) + } + /// An expression static func expression(_ expression: SQLExpression) -> Self { self.init(impl: .expression(expression)) @@ -70,13 +89,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 +126,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 +169,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 +187,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) @@ -226,14 +261,17 @@ extension SQLSelection { } /// Returns a qualified selection - func qualified(with alias: TableAlias) -> SQLSelection { + func qualified(with alias: TableAliasBase) -> 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 +283,27 @@ extension SQLSelection { } } + /// Returns whether this selection MUST be counted with a "trivial" + /// count: `SELECT COUNT(*) FROM (SELECT ...)`. + /// /// Supports SQLRelation.fetchCount. /// /// See - 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 +347,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 +395,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 +414,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 + + public init(_ excludedColumns: some Collection) { + 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) -> 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) -> Self { + AllColumnsExcluding(excludedColumns.map(\.name)) + } +} diff --git a/GRDB/QueryInterface/SQL/SQLSubquery.swift b/GRDB/QueryInterface/SQL/SQLSubquery.swift index fb3d59584..fdc9c3a3a 100644 --- a/GRDB/QueryInterface/SQL/SQLSubquery.swift +++ b/GRDB/QueryInterface/SQL/SQLSubquery.swift @@ -1,7 +1,7 @@ /// An SQL subquery. /// /// `SQLSubquery` is an opaque representation of an SQL subquery. -public struct SQLSubquery { +public struct SQLSubquery: Sendable { private var impl: Impl private enum Impl { diff --git a/GRDB/QueryInterface/SQL/Table.swift b/GRDB/QueryInterface/SQL/Table.swift index c6de851c7..b60c05291 100644 --- a/GRDB/QueryInterface/SQL/Table.swift +++ b/GRDB/QueryInterface/SQL/Table.swift @@ -40,7 +40,7 @@ /// /// - ``deleteAll(_:)`` /// - ``deleteAll(_:ids:)`` -/// - ``deleteAll(_:keys:)-5t865`` +/// - ``deleteAll(_:keys:)-594uc`` /// - ``deleteAll(_:keys:)-28sff`` /// - ``deleteOne(_:id:)`` /// - ``deleteOne(_:key:)-404su`` @@ -48,6 +48,8 @@ /// /// ### Updating Rows /// +/// - ``updateAll(_:onConflict:assignment:)`` +/// - ``updateAll(_:onConflict:assignments:)`` /// - ``updateAll(_:onConflict:_:)-4w9b`` /// - ``updateAll(_:onConflict:_:)-4cvap`` /// @@ -56,7 +58,8 @@ /// `Table` provide convenience access to most ``DerivableRequest`` and /// ``QueryInterfaceRequest`` methods. /// -/// - ``aliased(_:)`` +/// - ``aliased(_:)-3135k`` +/// - ``aliased(_:)-5dkyd`` /// - ``all()`` /// - ``annotated(with:)-6i101`` /// - ``annotated(with:)-6x399`` @@ -69,7 +72,7 @@ /// - ``filter(ids:)`` /// - ``filter(key:)-tw3i`` /// - ``filter(key:)-4sun7`` -/// - ``filter(keys:)-85e0v`` +/// - ``filter(keys:)-5ws7f`` /// - ``filter(keys:)-qqgf`` /// - ``filter(literal:)`` /// - ``filter(sql:arguments:)`` @@ -94,6 +97,7 @@ /// - ``select(literal:as:)`` /// - ``select(sql:arguments:)`` /// - ``select(sql:arguments:as:)`` +/// - ``selectID()`` /// - ``selectPrimaryKey(as:)`` /// - ``with(_:)`` /// @@ -424,6 +428,40 @@ extension Table { all().selectPrimaryKey(as: type) } + /// Returns a request that selects the primary key. + /// + /// For example: + /// + /// ```swift + /// let table = Table("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") + /// + /// // NOT RECOMMENDED: Set + /// let ids = try table.selectID().fetchSet(db) + /// + /// // BETTER: Set + /// let ids = try table.selectPrimaryKey(as: Int64.self).fetchSet(db) + /// ``` + public func selectID() -> QueryInterfaceRequest + where RowDecoder: Identifiable + { + all().selectID() + } + /// Returns a request with the provided result columns appended to the /// table columns. /// @@ -507,10 +545,9 @@ extension Table { /// ``` /// /// - parameter keys: A collection of primary keys - public func filter(keys: Keys) - -> QueryInterfaceRequest - where Keys: Sequence, Keys.Element: DatabaseValueConvertible - { + public func filter( + keys: some Collection + ) -> QueryInterfaceRequest { all().filter(keys: keys) } @@ -706,11 +743,23 @@ extension Table { all().limit(limit, offset: offset) } - /// Returns a request that can be referred to with the provided alias. + /// Returns a request that can be referred to with the provided + /// anonymous alias. /// /// `table.aliased(alias)` is equivalent to `table.all().aliased(alias)`. - /// See ``TableRequest/aliased(_:)`` for more information. - public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + /// + /// See ``TableRequest/aliased(_:)-772vb`` for more information. + public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + all().aliased(alias) + } + + /// Returns a request that can be referred to with the provided + /// record alias. + /// + /// `table.aliased(alias)` is equivalent to `table.all().aliased(alias)`. + /// + /// See ``TableRequest/aliased(_:)-3k5h4`` for more information. + public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { all().aliased(alias) } @@ -723,7 +772,6 @@ extension Table { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible { /// Returns a request filtered by primary key. /// @@ -775,9 +823,9 @@ extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConv /// ``` /// /// - parameter ids: A collection of primary keys - public func filter(ids: IDS) -> QueryInterfaceRequest - where IDS: Collection, IDS.Element == RowDecoder.ID - { + public func filter( + ids: some Collection + ) -> QueryInterfaceRequest { all().filter(ids: ids) } } @@ -1292,17 +1340,22 @@ extension Table { /// /// - parameter cte: A common table expression. /// - parameter condition: A function that returns the joining clause. - /// - parameter left: A `TableAlias` for the left table. - /// - parameter right: A `TableAlias` for the right table. + /// First argument is a ``TableAlias`` for the left table, second + /// argument an alias for the right table. /// - returns: An association to the common table expression. public func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable ( + _ left: TableAlias, + _ right: TableAlias + ) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( to: cte.relationForAll, - condition: .expression { condition($0, $1).sqlExpression }) + condition: .expression { left, right in + condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression + }) } /// Creates an association to a common table expression. @@ -1546,7 +1599,6 @@ extension Table { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible @@ -1644,11 +1696,10 @@ extension Table { /// - keys: A sequence of primary keys. /// - returns: The number of deleted rows. @discardableResult - public func deleteAll(_ db: Database, keys: Keys) - throws -> Int - where Keys: Sequence, Keys.Element: DatabaseValueConvertible - { - let keys = Array(keys) + public func deleteAll( + _ db: Database, + keys: some Collection + ) throws -> Int { if keys.isEmpty { // Avoid hitting the database return 0 @@ -1688,7 +1739,6 @@ extension Table { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Table where RowDecoder: Identifiable, RowDecoder.ID: DatabaseValueConvertible @@ -1723,9 +1773,10 @@ where RowDecoder: Identifiable, /// - ids: A collection of primary keys. /// - returns: The number of deleted rows. @discardableResult - public func deleteAll(_ db: Database, ids: IDS) throws -> Int - where IDS: Collection, IDS.Element == RowDecoder.ID - { + public func deleteAll( + _ db: Database, + ids: some Collection + ) throws -> Int { if ids.isEmpty { // Avoid hitting the database return 0 @@ -1853,6 +1904,77 @@ extension Table { // MARK: - Batch Update extension Table { + /// Updates all rows, and returns the number of updated rows. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// let playerTable = Table("player") + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try playerTable.updateAll(db) { $0.score.set(to: 0) } + /// } + /// ``` + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignment: A closure that returns an assignments. + /// - returns: The number of updated rows. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + @discardableResult + public func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignment: (DatabaseComponents) throws -> ColumnAssignment + ) throws -> Int + where RowDecoder: TableRecord + { + try updateAll(db, onConflict: conflictResolution, [assignment(RowDecoder.databaseComponents)]) + } + + /// Updates all rows, and returns the number of updated rows. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// let playerTable = Table("player") + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try playerTable.updateAll(db) { $0.score.set(to: 0) } + /// } + /// ``` + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. + /// - parameter assignments: A closure that returns an array of + /// column assignments. + /// - returns: The number of updated rows. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + @discardableResult + public func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignments: (DatabaseComponents) throws -> [ColumnAssignment] + ) throws -> Int + where RowDecoder: TableRecord + { + try updateAll(db, onConflict: conflictResolution, assignments(RowDecoder.databaseComponents)) + } + /// Updates all rows, and returns the number of updated rows. /// /// For example: @@ -1909,3 +2031,7 @@ extension Table { try updateAll(db, onConflict: conflictResolution, assignments) } } + +extension Table where RowDecoder: TableRecord { + public typealias DatabaseComponents = RowDecoder.DatabaseComponents +} diff --git a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift index d364a6bbb..d4fac3f8d 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLGenerationContext.swift @@ -37,8 +37,8 @@ final class SQLGenerationContext { } } - private let resolvedNames: [TableAlias: String] - private let ownAliases: Set + private let resolvedNames: [TableAliasBase: String] + private let ownAliases: Set private let ownCTEs: [String: SQLCTE] /// Creates a generation context. @@ -50,7 +50,7 @@ final class SQLGenerationContext { init( _ db: Database, argumentsSink: StatementArgumentsSink = StatementArgumentsSink(), - aliases: [TableAlias] = [], + aliases: [TableAliasBase] = [], ctes: OrderedDictionary = [:]) { self.parent = .none(db: db, argumentsSink: argumentsSink) @@ -66,7 +66,7 @@ final class SQLGenerationContext { /// - parameter ctes: An dictionary of available CTEs. private init( parent: SQLGenerationContext, - aliases: [TableAlias], + aliases: [TableAliasBase], ctes: OrderedDictionary) { self.parent = .context(parent) @@ -77,7 +77,7 @@ final class SQLGenerationContext { /// Returns a generation context suitable for subqueries. func subqueryContext( - aliases: [TableAlias] = [], + aliases: [TableAliasBase] = [], ctes: OrderedDictionary = [:]) -> SQLGenerationContext { SQLGenerationContext(parent: self, aliases: aliases, ctes: ctes) @@ -118,7 +118,7 @@ final class SQLGenerationContext { /// /// WHERE column == 1 /// SELECT * - func qualifier(for alias: TableAlias) -> String? { + func qualifier(for alias: TableAliasBase) -> String? { if alias.hasUserName { return alias.identityName } @@ -132,7 +132,7 @@ final class SQLGenerationContext { } /// WHERE MATCH pattern - func resolvedName(for alias: TableAlias) -> String { + func resolvedName(for alias: TableAliasBase) -> String { if let name = resolvedNames[alias] { return name } @@ -145,7 +145,7 @@ final class SQLGenerationContext { } /// FROM tableName - func aliasName(for alias: TableAlias) -> String? { + func aliasName(for alias: TableAliasBase) -> String? { let resolvedName = self.resolvedName(for: alias) if resolvedName != alias.tableName { return resolvedName @@ -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 + ) 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) } } } @@ -172,11 +207,14 @@ class StatementArgumentsSink { private(set) var arguments: StatementArguments private let rawSQL: Bool + // This non-Sendable instance can be used from multiple threads + // concurrently, because it never modifies its `arguments` + // mutable state. /// A sink which turns all argument values into SQL literals. /// /// The `"WHERE name = \("O'Brien")"` SQL literal is turned into the /// `WHERE name = 'O''Brien'` SQL. - static let literalValues = StatementArgumentsSink(rawSQL: true) + nonisolated(unsafe) static let literalValues = StatementArgumentsSink(rawSQL: true) private init(rawSQL: Bool) { self.arguments = [] @@ -206,318 +244,9 @@ class StatementArgumentsSink { } } -// MARK: - TableAlias - -/// A TableAlias identifies a table in a request. -/// -/// See ``TableRequest/aliased(_:)`` for more information and examples. -/// -/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) -public class TableAlias { - private enum Impl { - /// A TableAlias is undefined when it is created by the GRDB user: - /// - /// let alias = TableAlias() - /// let alias = TableAlias(name: "custom") - case undefined(userName: String?) - - /// A TableAlias is a table when explicitly specified: - /// - /// let alias = TableAlias(tableName: "player") - /// - /// Or when it qualifies a request that wasn't qualified yet (in which - /// case it turns from undefined to a table): - /// - /// // SELECT custom.* FROM player custom - /// let alias = TableAlias(name: "custom") - /// let request = Player.all().aliased(alias) - case table(tableName: String, userName: String?) - - /// A TableAlias can be a proxy for another table alias. Two different - /// instances for the same table identifier: - /// - /// // Pointless example: make alias2 a proxy for alias1 - /// let alias1 = TableAlias() - /// let alias2 = TableAlias() - /// Player.all() - /// .aliased(alias1) - /// .aliased(alias2) - /// - /// Proxies are useful because queries get implicit aliases as soon - /// as they are joined with associations. In the example below, - /// customAlias becomes a proxy for the request's implicit alias, which - /// gets a custom name. This allows implicit and user aliases to merge - /// into a single "table identifier" that matches the user's expectations: - /// - /// // SELECT custom.*, team.* - /// // FROM player custom - /// // JOIN team ON taem.id = custom.teamId - /// // WHERE custom.name = 'Arthur' - /// let customAlias = TableAlias(name: "custom") - /// let request = Player - /// .including(required: Player.team) - /// .filter(sql: "custom.name = 'Arthur'") - /// .aliased(customAlias) - case proxy(TableAlias) - } - - private var impl: Impl - - /// Resolve all proxies - private var root: TableAlias { - if case .proxy(let base) = impl { - return base.root - } else { - return self - } - } - - // exposed to SQLGenerationContext - fileprivate var identityName: String { - userName ?? tableName - } - - // exposed to SQLGenerationContext - fileprivate var hasUserName: Bool { - userName != nil - } - - var tableName: String { - switch impl { - case .undefined: - // Likely a GRDB bug - fatalError("Undefined alias has no table name") - case .table(tableName: let tableName, userName: _): - return tableName - case .proxy(let base): - return base.tableName - } - } - - private var userName: String? { - switch impl { - case .undefined(let userName): - return userName - case .table(tableName: _, userName: let userName): - return userName - case .proxy(let base): - return base.userName - } - } - - /// Creates a TableAlias. - /// - /// When the alias is given a name, this name is guaranteed to be used as - /// the table alias in the SQL query: - /// - /// ```swift - /// // SELECT p.* FROM player p - /// let alias = TableAlias(name: "p") - /// let request = Player.all().aliased(alias) - /// ``` - public init(name: String? = nil) { - self.impl = .undefined(userName: name) - } - - init(tableName: String, userName: String? = nil) { - self.impl = .table(tableName: tableName, userName: userName) - } - - func becomeProxy(of base: TableAlias) { - if self === base { - return - } - - switch impl { - case let .undefined(userName): - if let userName { - // rename - assert(base.userName == nil || base.userName == userName) - base.setUserName(userName) - } - self.impl = .proxy(base) - case let .table(tableName: tableName, userName: userName): - assert(tableName == base.tableName) - if let userName { - // rename - assert(base.userName == nil || base.userName == userName) - base.setUserName(userName) - } - self.impl = .proxy(base) - case let .proxy(selfBase): - selfBase.becomeProxy(of: base) - } - } - - /// Returns nil if aliases can't be merged (conflict in tables, aliases...) - func merged(with other: TableAlias) -> TableAlias? { - if self === other { - return self - } - - let root = self.root - let otherRoot = other.root - switch (root.impl, otherRoot.impl) { - case let (.table(tableName: tableName, userName: userName), - .table(tableName: otherTableName, userName: otherUserName)): - guard tableName == otherTableName else { - // can't merge - return nil - } - if let userName, let otherUserName, userName != otherUserName { - // can't merge - return nil - } - root.becomeProxy(of: otherRoot) - return otherRoot - default: - // can't merge - return nil - } - } - - private func setUserName(_ userName: String) { - switch impl { - case .undefined: - self.impl = .undefined(userName: userName) - case .table(tableName: let tableName, userName: _): - self.impl = .table(tableName: tableName, userName: userName) - case .proxy(let base): - base.setUserName(userName) - } - } - - func setTableName(_ tableName: String) { - switch impl { - case .undefined(let userName): - self.impl = .table(tableName: tableName, userName: userName) - case .table(tableName: let initialTableName, userName: _): - // It is a programmer error to reuse the same TableAlias for - // multiple tables. - // - // // Don't do that - // let alias = TableAlias() - // let books = Book.aliased(alias)... - // let authors = Author.aliased(alias)... - GRDBPrecondition( - tableName.lowercased() == initialTableName.lowercased(), - "A TableAlias most not be used to refer to multiple tables") - case .proxy(let base): - base.setTableName(tableName) - } - } - - /// Returns a result column that refers to the aliased table. - public subscript(_ selectable: some SQLSelectable) -> SQLSelection { - // TODO: test - selectable.sqlSelection.qualified(with: self) - } - - /// Returns an SQL expression that refers to the aliased table. - /// - /// For example, let's sort books by author name first, and then by title: - /// - /// ```swift - /// // SELECT book.* - /// // FROM book - /// // JOIN author ON author.id = book.authorId - /// // ORDER BY author.name, book.title - /// let authorAlias = TableAlias() - /// let request = Book - /// .joining(required: Book.author.aliased(authorAlias)) - /// .order(authorAlias[Column("name")], Column("title")) - /// ``` - public subscript(_ expression: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression { - expression.sqlExpression.qualified(with: self) - } - - public subscript(_ expression: some SQLJSONExpressible & - SQLSpecificExpressible & - SQLSelectable & - SQLOrderingTerm) - -> AnySQLJSONExpressible - { - AnySQLJSONExpressible(sqlExpression: expression.sqlExpression.qualified(with: self)) - } - - /// Returns an SQL ordering term that refers to the aliased table. - /// - /// For example, let's sort books by author name first, and then by title: - /// - /// ```swift - /// // SELECT book.* - /// // FROM book - /// // JOIN author ON author.id = book.authorId - /// // ORDER BY author.name ASC, book.title ASC - /// let authorAlias = TableAlias() - /// let request = Book - /// .joining(required: Book.author.aliased(authorAlias)) - /// .order(authorAlias[Column("name").asc], Column("title").asc) - /// ``` - public subscript(_ ordering: some SQLOrderingTerm) -> SQLOrdering { - ordering.sqlOrdering.qualified(with: self) - } - - /// Returns an SQL column that refers to the aliased table. - /// - /// For example, let's sort books by author name first, and then by title: - /// - /// ```swift - /// // SELECT book.* - /// // FROM book - /// // JOIN author ON author.id = book.authorId - /// // ORDER BY author.name, book.title - /// let authorAlias = TableAlias() - /// let request = Book - /// .joining(required: Book.author.aliased(authorAlias)) - /// .order(authorAlias["name"], Column("title")) - /// ``` - public subscript(_ column: String) -> SQLExpression { - .qualifiedColumn(column, self) - } - - /// A boolean SQL expression indicating whether this alias refers to some - /// rows, or not. - /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// - /// In the example below, we only fetch books that are not associated to - /// any author: - /// - /// ```swift - /// struct Author: TableRecord, FetchableRecord { } - /// struct Book: TableRecord, FetchableRecord { - /// static let author = belongsTo(Author.self) - /// } - /// - /// try dbQueue.read { db in - /// let authorAlias = TableAlias() - /// let request = Book - /// .joining(optional: Book.author.aliased(authorAlias)) - /// .filter(!authorAlias.exists) - /// let books = try request.fetchAll(db) - /// } - /// ``` - public var exists: SQLExpression { - SQLExpression.qualifiedExists(self) - } -} - -extension TableAlias: Equatable { - public static func == (lhs: TableAlias, rhs: TableAlias) -> Bool { - ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root) - } -} - -extension TableAlias: Hashable { - public func hash(into hasher: inout Hasher) { - hasher.combine(ObjectIdentifier(root)) - } -} - -extension [TableAlias] { +extension [TableAliasBase] { /// Resolve ambiguities in aliases' names. - fileprivate var resolvedNames: [TableAlias: String] { + fileprivate var resolvedNames: [TableAliasBase: String] { // It is a programmer error to reuse the same TableAlias for // multiple tables. // @@ -533,7 +262,7 @@ extension [TableAlias] { } var uniqueLowercaseNames: Set = [] - var ambiguousGroups: [[TableAlias]] = [] + var ambiguousGroups: [[TableAliasBase]] = [] for (lowercaseName, group) in groups { if group.count > 1 { @@ -547,7 +276,7 @@ extension [TableAlias] { } } - var resolvedNames: [TableAlias: String] = [:] + var resolvedNames: [TableAliasBase: String] = [:] for group in ambiguousGroups { var index = 1 for alias in group { diff --git a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift index 17551514b..f4b8fdccf 100644 --- a/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift +++ b/GRDB/QueryInterface/SQLGeneration/SQLQueryGenerator.swift @@ -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) @@ -513,6 +535,9 @@ struct SQLQueryGenerator: Refinable { } } +// This type is marked as `Sendable` in order to avoid compiler warnings, +// but it should not need to be: instances are synchronously created, used, +// and discarded. /// To generate SQL, we need a "qualified" relation, where all tables, /// expressions, etc, are qualified with table aliases. /// @@ -546,10 +571,9 @@ struct SQLQueryGenerator: Refinable { /// HAVING ... -- havingExpressionPromise /// ORDER BY ... -- ordering /// LIMIT ... -- limit - -private struct SQLQualifiedRelation { +private struct SQLQualifiedRelation: Sendable { /// All aliases, including aliases of joined relations - var allAliases: [TableAlias] { + var allAliases: [TableAliasBase] { joins.reduce(into: [source.alias].compactMap { $0 }) { $0.append(contentsOf: $1.value.relation.allAliases) } @@ -715,7 +739,7 @@ extension SQLQualifiedRelation: Refinable { } /// A "qualified" source, where all tables are identified with a table alias. private struct SQLQualifiedSource { var tableName: String - var alias: TableAlias + var alias: TableAliasBase init(_ source: SQLSource) { self.tableName = source.tableName @@ -764,13 +788,13 @@ private struct SQLQualifiedJoin: Refinable { self.relation = SQLQualifiedRelation(child.relation) } - func sql(_ context: SQLGenerationContext, leftAlias: TableAlias) throws -> String { + func sql(_ context: SQLGenerationContext, leftAlias: TableAliasBase) throws -> String { try sql(context, leftAlias: leftAlias, allowingInnerJoin: true) } private func sql( _ context: SQLGenerationContext, - leftAlias: TableAlias, + leftAlias: TableAliasBase, allowingInnerJoin allowsInnerJoin: Bool) throws -> String { diff --git a/GRDB/QueryInterface/SQLGeneration/TableAlias.swift b/GRDB/QueryInterface/SQLGeneration/TableAlias.swift new file mode 100644 index 000000000..f8a737941 --- /dev/null +++ b/GRDB/QueryInterface/SQLGeneration/TableAlias.swift @@ -0,0 +1,437 @@ +/// `TableAliasBase` is the base class of `TableAlias`. +/// +/// See for more information and examples. +/// +/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) +public class TableAliasBase: @unchecked Sendable { + // This Sendable conformance is transient. TableAlias IS NOT really Sendable. + // TODO: Make TableAlias really Sendable + private enum Impl { + /// A TableAlias is undefined when it is created by the GRDB user: + /// + /// let alias = TableAlias() + /// let alias = TableAlias(name: "custom") + case undefined(userName: String?) + + /// A TableAlias is a table when explicitly specified: + /// + /// let alias = TableAlias(tableName: "player") + /// + /// Or when it qualifies a request that wasn't qualified yet (in which + /// case it turns from undefined to a table): + /// + /// // SELECT custom.* FROM player custom + /// let alias = TableAlias(name: "custom") + /// let request = Player.all().aliased(alias) + case table(tableName: String, userName: String?) + + /// A TableAlias can be a proxy for another table alias. Two different + /// instances for the same table identifier: + /// + /// // Pointless example: make alias2 a proxy for alias1 + /// let alias1 = TableAlias() + /// let alias2 = TableAlias() + /// Player.all() + /// .aliased(alias1) + /// .aliased(alias2) + /// + /// Proxies are useful because queries get implicit aliases as soon + /// as they are joined with associations. In the example below, + /// customAlias becomes a proxy for the request's implicit alias, which + /// gets a custom name. This allows implicit and user aliases to merge + /// into a single "table identifier" that matches the user's expectations: + /// + /// // SELECT custom.*, team.* + /// // FROM player custom + /// // JOIN team ON taem.id = custom.teamId + /// // WHERE custom.name = 'Arthur' + /// let customAlias = TableAlias(name: "custom") + /// let request = Player + /// .including(required: Player.team) + /// .filter(sql: "custom.name = 'Arthur'") + /// .aliased(customAlias) + case proxy(TableAliasBase) + } + + private var impl: Impl + + /// Resolve all proxies + private var root: TableAliasBase { + if case .proxy(let base) = impl { + return base.root + } else { + return self + } + } + + // exposed to SQLGenerationContext + var identityName: String { + userName ?? tableName + } + + // exposed to SQLGenerationContext + var hasUserName: Bool { + userName != nil + } + + var tableName: String { + switch impl { + case .undefined: + // Likely a GRDB bug + fatalError("Undefined alias has no table name") + case .table(tableName: let tableName, userName: _): + return tableName + case .proxy(let base): + return base.tableName + } + } + + private var userName: String? { + switch impl { + case .undefined(let userName): + return userName + case .table(tableName: _, userName: let userName): + return userName + case .proxy(let base): + return base.userName + } + } + + /// Creates a TableAlias. + /// + /// When the alias is given a name, this name is guaranteed to be used as + /// the table alias in the SQL query: + /// + /// ```swift + /// // SELECT p.* FROM player p + /// let alias = TableAlias(name: "p") + /// let request = Player.all().aliased(alias) + /// ``` + init(name: String? = nil) { + self.impl = .undefined(userName: name) + } + + init(tableName: String, userName: String? = nil) { + self.impl = .table(tableName: tableName, userName: userName) + } + + func becomeProxy(of base: TableAliasBase) { + if self === base { + return + } + + switch impl { + case let .undefined(userName): + if let userName { + // rename + assert(base.userName == nil || base.userName == userName) + base.setUserName(userName) + } + self.impl = .proxy(base) + case let .table(tableName: tableName, userName: userName): + assert(tableName == base.tableName) + if let userName { + // rename + assert(base.userName == nil || base.userName == userName) + base.setUserName(userName) + } + self.impl = .proxy(base) + case let .proxy(selfBase): + selfBase.becomeProxy(of: base) + } + } + + /// Returns nil if aliases can't be merged (conflict in tables, aliases...) + func merged(with other: TableAliasBase) -> TableAliasBase? { + if self === other { + return self + } + + let root = self.root + let otherRoot = other.root + switch (root.impl, otherRoot.impl) { + case let (.table(tableName: tableName, userName: userName), + .table(tableName: otherTableName, userName: otherUserName)): + guard tableName == otherTableName else { + // can't merge + return nil + } + if let userName, let otherUserName, userName != otherUserName { + // can't merge + return nil + } + root.becomeProxy(of: otherRoot) + return otherRoot + default: + // can't merge + return nil + } + } + + private func setUserName(_ userName: String) { + switch impl { + case .undefined: + self.impl = .undefined(userName: userName) + case .table(tableName: let tableName, userName: _): + self.impl = .table(tableName: tableName, userName: userName) + case .proxy(let base): + base.setUserName(userName) + } + } + + func setTableName(_ tableName: String) { + switch impl { + case .undefined(let userName): + self.impl = .table(tableName: tableName, userName: userName) + case .table(tableName: let initialTableName, userName: _): + // It is a programmer error to reuse the same TableAlias for + // multiple tables. + // + // // Don't do that + // let alias = TableAlias() + // let books = Book.aliased(alias)... + // let authors = Author.aliased(alias)... + GRDBPrecondition( + tableName.lowercased() == initialTableName.lowercased(), + "A TableAlias most not be used to refer to multiple tables") + case .proxy(let base): + base.setTableName(tableName) + } + } +} + +extension TableAliasBase: Equatable { + public static func == (lhs: TableAliasBase, rhs: TableAliasBase) -> Bool { + ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root) + } +} + +extension TableAliasBase: Hashable { + public func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(root)) + } +} + +extension TableAliasBase { + /// Returns a result column that refers to the aliased table. + public subscript(_ selectable: some SQLSelectable) -> SQLSelection { + // TODO: test + selectable.sqlSelection.qualified(with: self) + } + + /// Returns an SQL expression that refers to the aliased table. + /// + /// For example, let's sort books by author name first, and then by title: + /// + /// ```swift + /// struct Author: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// + /// enum Columns { + /// static let title = Column("title") + /// } + /// } + /// + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // ORDER BY author.name, book.title + /// let authorAlias = TableAlias() + /// let request = Book + /// .joining(required: Book.author.aliased(authorAlias)) + /// .order { [authorAlias.name, $0.title] } + /// ``` + public subscript(_ expression: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression { + expression.sqlExpression.qualified(with: self) + } + + public subscript(_ expression: some SQLJSONExpressible & + SQLSpecificExpressible & + SQLSelectable & + SQLOrderingTerm) + -> AnySQLJSONExpressible + { + AnySQLJSONExpressible(sqlExpression: expression.sqlExpression.qualified(with: self)) + } + + public subscript(_ ordering: some SQLOrderingTerm) -> SQLOrdering { + ordering.sqlOrdering.qualified(with: self) + } + + /// Returns an SQL column that refers to the aliased table. + /// + /// For example, let's sort books by author name first, and then by title: + /// + /// ```swift + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // ORDER BY author.name, book.title + /// let authorAlias = TableAlias() + /// let request = Book + /// .joining(required: Book.author.aliased(authorAlias)) + /// .order(authorAlias["name"], Column("title")) + /// ``` + public subscript(_ column: String) -> SQLExpression { + .qualifiedColumn(column, self) + } +} + +// MARK: - TableAlias + +/// A TableAlias identifies a table in a request. +/// +/// See for more information and examples. +/// +/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) +@dynamicMemberLookup +public final class TableAlias: TableAliasBase, @unchecked Sendable { + init(tableName: String, userName: String? = nil) + where RowDecoder == Void + { + super.init(tableName: tableName, userName: userName) + } + + init(root: TableAliasBase) { + super.init() + becomeProxy(of: root) + } + + /// Creates an anonymous TableAlias. + /// + /// When the alias is given a name, this name is guaranteed to be used as + /// the table alias in the SQL query: + /// + /// ```swift + /// // SELECT p.* FROM player p + /// let alias = TableAlias(name: "p") + /// let request = Player.all().aliased(alias) + /// ``` + /// + /// Anonymous aliases do not provide convenience access to table + /// columns, unlike record aliases. See ``TableAlias`` for + /// more information. + public init(name: String? = nil) + where RowDecoder == Void + { + super.init(name: name) + } + + /// Creates a TableAlias for the specified record type. + /// + /// When the alias is given a name, this name is guaranteed to be used as + /// the table alias in the SQL query: + /// + /// ```swift + /// // SELECT p.* FROM player p + /// let alias = TableAlias(name: "p") + /// let request = Player.all().aliased(alias) + /// ``` + public init( + name: String? = nil, + for record: RowDecoder.Type = RowDecoder.self + ) { + super.init(name: name) + } +} + +extension TableAlias { + /// A boolean SQL expression indicating whether this alias refers to some + /// rows, or not. + /// + /// In the example below, we only fetch books that are not associated to + /// any author: + /// + /// ```swift + /// struct Author: TableRecord, FetchableRecord { } + /// struct Book: TableRecord, FetchableRecord { + /// static let author = belongsTo(Author.self) + /// } + /// + /// try dbQueue.read { db in + /// let authorAlias = TableAlias() + /// let request = Book + /// .joining(optional: Book.author.aliased(authorAlias)) + /// .filter(!authorAlias.exists) + /// let books = try request.fetchAll(db) + /// } + /// ``` + public var exists: SQLExpression { + SQLExpression.qualifiedExists(self) + } +} + +extension TableAlias where RowDecoder: TableRecord { + public typealias DatabaseComponents = RowDecoder.DatabaseComponents + + /// Returns a result column that refers to the aliased table. + public subscript( + dynamicMember keyPath: KeyPath + ) -> SQLSelection + where T: SQLSelectable + { + self[RowDecoder.databaseComponents[keyPath: keyPath]] + } + + /// Returns an SQL expression that refers to the aliased table. + /// + /// For example, let's sort books by author name first, and then by title: + /// + /// ```swift + /// struct Author: TableRecord { + /// enum Columns { + /// static let name = Column("name") + /// } + /// } + /// + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// + /// enum Columns { + /// static let title = Column("title") + /// } + /// } + /// + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // ORDER BY author.name, book.title + /// let authorAlias = TableAlias() + /// let request = Book + /// .joining(required: Book.author.aliased(authorAlias)) + /// .order { [authorAlias.name, $0.title] } + /// ``` + public subscript( + dynamicMember keyPath: KeyPath + ) -> SQLExpression + where T: SQLSpecificExpressible & + SQLSelectable & + SQLOrderingTerm + { + self[RowDecoder.databaseComponents[keyPath: keyPath]] + } + + public subscript( + dynamicMember keyPath: KeyPath + ) -> AnySQLJSONExpressible + where T: SQLJSONExpressible & + SQLSpecificExpressible & + SQLSelectable & + SQLOrderingTerm + { + self[RowDecoder.databaseComponents[keyPath: keyPath]] + } + + public subscript( + dynamicMember keyPath: KeyPath + ) -> SQLOrdering + where T: SQLOrderingTerm { + self[RowDecoder.databaseComponents[keyPath: keyPath]] + } +} diff --git a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift index eb161ab8b..eb54261da 100644 --- a/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift +++ b/GRDB/QueryInterface/SQLInterpolation+QueryInterface.swift @@ -67,7 +67,12 @@ extension SQLInterpolation { /// let player: Player = ... /// let request: SQLRequest = "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 = """ - /// 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 = """ - /// SELECT \(AllColumns()) FROM player + /// SELECT \(.allColumns) FROM player /// """ @_disfavoredOverload public mutating func appendInterpolation(_ selection: (any SQLSelectable)?) { @@ -194,7 +199,7 @@ extension SQLInterpolation { /// Appends the request SQL (not wrapped inside parentheses). /// - /// let subquery = Player.select(max(Column("score"))) + /// let subquery = Player.select { max($0.score) } /// // or /// let subQuery: SQLRequest = "SELECT MAX(score) FROM player" /// @@ -227,9 +232,9 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player WHERE id IN \(ids) /// """ - public mutating func appendInterpolation(_ sequence: S) - where S: Sequence, S.Element: SQLExpressible - { + public mutating func appendInterpolation( + _ sequence: some Sequence + ) { let e: [SQL.Element] = sequence.map { .expression($0.sqlExpression) } if e.isEmpty { appendLiteral("(SELECT NULL WHERE NULL)") @@ -255,9 +260,9 @@ extension SQLInterpolation { /// let request: SQLRequest = """ /// SELECT * FROM player WHERE a IN \(expressions) /// """ - public mutating func appendInterpolation(_ sequence: S) - where S: Sequence, S.Element == any SQLExpressible - { + public mutating func appendInterpolation( + _ sequence: some Sequence + ) { appendInterpolation(sequence.lazy.map(\.sqlExpression)) } diff --git a/GRDB/QueryInterface/Schema/ColumnDefinition.swift b/GRDB/QueryInterface/Schema/ColumnDefinition.swift index 88cf0103a..18ee6a983 100644 --- a/GRDB/QueryInterface/Schema/ColumnDefinition.swift +++ b/GRDB/QueryInterface/Schema/ColumnDefinition.swift @@ -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: /// /// - 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: /// /// - 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: /// /// - 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: /// /// - parameters: diff --git a/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift b/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift index 10b95ebc3..eb8b4b64c 100644 --- a/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift +++ b/GRDB/QueryInterface/Schema/Database+SchemaDefinition.swift @@ -339,7 +339,7 @@ extension Database { /// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1 /// try db.create( /// view: "hero", - /// as: Player.filter(Column("isHero") == true)) + /// as: Player.filter(\.isHero)) /// ``` /// /// When creating views in , it is not recommended to @@ -356,7 +356,7 @@ extension Database { /// Related SQLite documentation: /// /// - parameters: - /// - view: The view name. + /// - name: The view name. /// - options: View creation options. /// - columns: The columns of the view. If nil, the columns are the /// columns of the request. @@ -410,7 +410,7 @@ extension Database { /// Related SQLite documentation: /// /// - parameters: - /// - view: The view name. + /// - name: The view name. /// - options: View creation options. /// - columns: The columns of the view. If nil, the columns are the /// columns of the request. diff --git a/GRDB/QueryInterface/Schema/TableAlteration.swift b/GRDB/QueryInterface/Schema/TableAlteration.swift index c731e7ea5..d967d073a 100644 --- a/GRDB/QueryInterface/Schema/TableAlteration.swift +++ b/GRDB/QueryInterface/Schema/TableAlteration.swift @@ -125,11 +125,32 @@ public final class TableAlteration { /// } /// ``` /// + /// Take care, when you rename **foreign keys** in , + /// to run the migration with the ``DatabaseMigrator/ForeignKeyChecks/immediate`` + /// foreign key checks, in order to avoid integrity failures: + /// + /// ```swift + /// // RECOMMENDED: rename foreign keys with immediate foreign key checks. + /// migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in + /// try db.rename(table: "team", to: "guild") + /// try db.alter(table: "player") { t in + /// t.rename(column: "teamId", to: "guildId") + /// } + /// } + /// + /// // NOT RECOMMENDED: rename foreign keys with disabled foreign keys. + /// migrator.registerMigration("Guilds") { db in + /// try db.rename(table: "team", to: "guild") + /// try db.alter(table: "player") { t in + /// t.rename(column: "teamId", to: "guildId") + /// } + /// } + /// ``` + /// /// Related SQLite documentation: /// /// - parameter name: the old name of the column. /// - parameter newName: the new name of the column. - @available(iOS 13, tvOS 13, watchOS 6, *) // SQLite 3.25+ public func rename(column name: String, to newName: String) { _rename(column: name, to: newName) } diff --git a/GRDB/QueryInterface/Schema/TableDefinition.swift b/GRDB/QueryInterface/Schema/TableDefinition.swift index 235c54bf8..2395d62b0 100644 --- a/GRDB/QueryInterface/Schema/TableDefinition.swift +++ b/GRDB/QueryInterface/Schema/TableDefinition.swift @@ -136,6 +136,7 @@ public final class TableDefinition { /// - /// - /// + /// - parameter name: the name of the primary key. /// - parameter conflictResolution: An optional conflict resolution /// (see ). /// - returns: `self` so that you can further refine the column definition. @@ -163,6 +164,8 @@ public final class TableDefinition { /// /// - parameter name: the column name. /// - parameter type: the column type. + /// - parameter conflictResolution: An optional conflict resolution + /// (see ). /// - returns: A ``ColumnDefinition`` that allows you to refine the /// column definition. @discardableResult diff --git a/GRDB/QueryInterface/Schema/VirtualTableModule.swift b/GRDB/QueryInterface/Schema/VirtualTableModule.swift index 07bdf7bdd..5af956f02 100644 --- a/GRDB/QueryInterface/Schema/VirtualTableModule.swift +++ b/GRDB/QueryInterface/Schema/VirtualTableModule.swift @@ -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: " ") @@ -113,22 +138,22 @@ extension Database { /// Related SQLite documentation: /// /// - 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. + /// - tableName: The table name. + /// - 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( 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: + /// + /// - 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: + /// + /// - 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( + 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) + } } diff --git a/GRDB/QueryInterface/TableRecord+Association.swift b/GRDB/QueryInterface/TableRecord+Association.swift index e86a54814..ff37d7423 100644 --- a/GRDB/QueryInterface/TableRecord+Association.swift +++ b/GRDB/QueryInterface/TableRecord+Association.swift @@ -308,18 +308,31 @@ extension TableRecord { /// latest message: /// /// ```swift - /// let latestMessageRequest = Message - /// .annotated(with: max(Column("date"))) - /// .group(Column("chatID")) + /// struct Chat: TableRecord { + /// enum Columns { + /// static let id = Column("id") + /// } + /// } /// - /// let latestMessageCTE = CommonTableExpression( + /// struct Message: TableRecord { + /// enum Columns { + /// static let date = Column("date") + /// static let chatId = Column("chatId") + /// } + /// } + /// + /// let latestMessageRequest = Message + /// .annotated { max($0.date) } + /// .group(\.chatId) + /// + /// let latestMessageCTE = CommonTableExpression( /// named: "latestMessage", /// request: latestMessageRequest) /// /// let latestMessageAssociation = Chat.association( /// to: latestMessageCTE, /// on: { chat, latestMessage in - /// chat[Column("id")] == latestMessage[Column("chatID")] + /// chat.id == latestMessage.chatId /// }) /// /// // WITH latestMessage AS @@ -334,17 +347,22 @@ extension TableRecord { /// /// - parameter cte: A common table expression. /// - parameter condition: A function that returns the joining clause. - /// - parameter left: A `TableAlias` for the left table. - /// - parameter right: A `TableAlias` for the right table. + /// First argument is a ``TableAlias`` for the left table, second + /// argument an alias for the right table. /// - returns: An association to the common table expression. public static func association( to cte: CommonTableExpression, - on condition: @escaping (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible) + on condition: @escaping @Sendable ( + _ left: TableAlias, + _ right: TableAlias + ) -> any SQLExpressible) -> JoinAssociation { JoinAssociation( to: cte.relationForAll, - condition: .expression { condition($0, $1).sqlExpression }) + condition: .expression { left, right in + condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression + }) } /// Creates an association to a common table expression. @@ -567,6 +585,19 @@ extension TableRecord where Self: EncodableRecord { fatalError("Not implemented: request association without any foreign key") case let .foreignKey(foreignKey): + // Build the sendable persistence container before building the + // request, and catch the eventual error in a Result, so that it + // is thrown later, when the request is executed. This allows + // this method to not throw: + // + // extension Player { + // // We don't want this property to have a throwing getter: + // var team: QueryInterfaceRequest { + // request(for: Player.team) + // } + // } + let persistenceContainer = Result { try PersistenceContainer(self) } + let destinationRelation = association ._sqlAssociation .with { @@ -574,7 +605,7 @@ extension TableRecord where Self: EncodableRecord { // Filter the pivot on self try foreignKey .joinMapping(db, from: Self.databaseTableName) - .joinExpression(leftRows: [PersistenceContainer(db, self)]) + .joinExpression(leftRows: [persistenceContainer.get()]) } } .destinationRelation() @@ -687,12 +718,17 @@ extension TableRecord { /// For example, we can fetch only books whose author is French: /// /// ```swift - /// struct Author: TableRecord, FetchableRecord, Decodable { } + /// struct Author: TableRecord, FetchableRecord, Decodable { + /// enum Columns { + /// static let countryCode = Column("countryCode") + /// } + /// } + /// /// struct Book: TableRecord, FetchableRecord, Decodable { /// static let author = belongsTo(Author.self) /// } /// - /// let frenchAuthors = Book.author.filter(Column("countryCode") == "FR") + /// let frenchAuthors = Book.author.filter { $0.countryCode == "FR" } /// let bookInfos = try Book /// .joining(required: frenchAuthors) /// .fetchAll(db) @@ -713,9 +749,19 @@ extension TableRecord { /// For example: /// /// ```swift + /// struct Team: TableRecord { + /// enum Columns { + /// static let color = Column("color") + /// } + /// } + /// + /// struct Player: Decodable, FetchableRecord, TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// /// // SELECT player.*, team.color /// // FROM player LEFT JOIN team ... - /// let teamColor = Player.team.select(Column("color")) + /// let teamColor = Player.team.select(\.color) /// let request = Player.annotated(withOptional: teamColor) /// ``` /// @@ -737,9 +783,19 @@ extension TableRecord { /// For example: /// /// ```swift + /// struct Team: TableRecord { + /// enum Columns { + /// static let color = Column("color") + /// } + /// } + /// + /// struct Player: Decodable, FetchableRecord, TableRecord { + /// static let team = belongsTo(Team.self) + /// } + /// /// // SELECT player.*, team.color /// // FROM player JOIN team ... - /// let teamColor = Player.team.select(Column("color")) + /// let teamColor = Player.team.select(\.color) /// let request = Player.annotated(withRequired: teamColor) /// ``` /// diff --git a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift index 8044373f3..37d3ec190 100644 --- a/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift +++ b/GRDB/QueryInterface/TableRecord+QueryInterfaceRequest.swift @@ -67,6 +67,38 @@ extension TableRecord { all().select(selection) } + /// Returns a request that selects the provided result columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT score FROM player + /// let request = Player.select(\.score) + /// ``` + public static func select( + _ selection: (DatabaseComponents) throws -> any SQLSelectable + ) rethrows -> QueryInterfaceRequest { + try all().select(selection) + } + + /// Returns a request that selects the provided result columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT id, score FROM player + /// let request = Player.select { [$0.id, $0.score] } + /// ``` + public static func select( + _ selection: (DatabaseComponents) throws -> [any SQLSelectable] + ) rethrows -> QueryInterfaceRequest { + try all().select(selection) + } + /// Returns a request that selects the provided SQL string. /// /// For example: @@ -163,6 +195,35 @@ extension TableRecord { all().select(selection, as: type) } + /// Returns a request that selects the provided result columns, and defines + /// the type of decoded rows. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let id = Column("id") + /// static let score = Column("score") + /// } + /// } + /// + /// // SELECT id FROM player + /// let request = Player.select(\.id, as: Int.self) + /// let scores = try request.fetchSet(db) // Set + /// + /// // SELECT MAX(score) FROM player + /// let request = Player.select({ max($0.score) }, as: Int.self) + /// let maxScore = try request.fetchOne(db) // Int? + /// ``` + public static func select( + _ selection: (DatabaseComponents) throws -> any SQLSelectable, + as type: RowDecoder.Type = RowDecoder.self + ) rethrows -> QueryInterfaceRequest + { + try all().select(selection, as: type) + } + /// Returns a request that selects the provided SQL string, and defines the /// type of decoded rows. /// @@ -251,6 +312,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 + /// let ids = try Player.selectID().fetchSet(db) + /// + /// // BETTER: Set + /// let ids = try Player.selectPrimaryKey(as: Int64.self).fetchSet(db) + /// ``` + public static func selectID() -> QueryInterfaceRequest + where Self: Identifiable + { + all().selectID() + } + /// Returns a request with the provided result columns appended to the /// record selection. /// @@ -289,6 +380,46 @@ extension TableRecord { all().annotated(with: selection) } + /// Returns a request with the provided result columns appended to the + /// record selection. + /// + /// The record selection is determined by + /// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT *, score + bonus AS totalScore FROM player + /// let request = Player.annotated { ($0.score + $0.bonus).forKey("totalScore") } + /// ``` + public static func annotated( + with selection: (DatabaseComponents) throws -> any SQLSelectable + ) rethrows -> QueryInterfaceRequest { + try all().annotated(with: selection) + } + + /// Returns a request with the provided result columns appended to the + /// record selection. + /// + /// The record selection is determined by + /// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT *, score + bonus AS totalScore FROM player + /// let request = Player.annotated { [($0.score + $0.bonus).forKey("totalScore")] } + /// ``` + public static func annotated( + with selection: (DatabaseComponents) throws -> [any SQLSelectable] + ) rethrows -> QueryInterfaceRequest { + try all().annotated(with: selection) + } + // Accept SQLSpecificExpressible instead of SQLExpressible, so that we // prevent the `Player.filter(42)` misuse. // See https://github.com/groue/GRDB.swift/pull/864 @@ -307,6 +438,26 @@ extension TableRecord { all().filter(predicate) } + // Accept SQLSpecificExpressible instead of SQLExpressible, so that we + // prevent the `Player.filter(42)` misuse. + // See https://github.com/groue/GRDB.swift/pull/864 + /// Returns a request filtered with a boolean SQL expression. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player WHERE name = 'O''Brien' + /// let name = "O'Brien" + /// let request = Player.filter { $0.name == name } + /// ``` + public static func filter( + _ predicate: (DatabaseComponents) throws -> any SQLSpecificExpressible + ) rethrows -> QueryInterfaceRequest { + try all().filter(predicate) + } + /// Returns a request filtered by primary key. /// /// All single-column primary keys are supported: @@ -343,10 +494,9 @@ extension TableRecord { /// ``` /// /// - parameter keys: A collection of primary keys - public static func filter(keys: Keys) - -> QueryInterfaceRequest - where Keys: Sequence, Keys.Element: DatabaseValueConvertible - { + public static func filter( + keys: some Collection + ) -> QueryInterfaceRequest { all().filter(keys: keys) } @@ -471,6 +621,38 @@ extension TableRecord { all().order(orderings) } + /// Returns a request sorted according to the given SQL ordering term. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player ORDER BY score DESC + /// let request = Player.order(\.score.desc) + /// ``` + public static func order( + _ orderings: (DatabaseComponents) throws -> any SQLOrderingTerm + ) rethrows -> QueryInterfaceRequest { + try all().order(orderings) + } + + /// Returns a request sorted according to the given SQL ordering terms. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { } + /// + /// // SELECT * FROM player ORDER BY score DESC, name + /// let request = Player.order { [$0.score.desc, $0.name] } + /// ``` + public static func order( + _ orderings: (DatabaseComponents) throws -> [any SQLOrderingTerm] + ) rethrows -> QueryInterfaceRequest { + try all().order(orderings) + } + /// Returns a request sorted by primary key. /// /// All primary keys are supported: @@ -566,8 +748,45 @@ extension TableRecord { /// .joining(required: Book.author.filter(Column("deathDate") <= bookAlias[Column("publishDate")]) /// ``` /// - /// See ``TableRequest/aliased(_:)`` for more information. - public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + /// See ``TableRequest/aliased(_:)-772vb`` for more information. + public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { + all().aliased(alias) + } + + /// Returns a request that can be referred to with the provided alias. + /// + /// Use this method when you need to refer to this table from + /// another request. + /// + /// For example, the request below fetches posthumous books: + /// + /// ```swift + /// struct Author: TableRecord { + /// enum Columns { + /// static let deathDate = Column("deathDate") + /// } + /// } + /// + /// struct Book: TableRecord { + /// static let author = belongsTo(Author.self) + /// + /// enum Columns { + /// static let publishDate = Column("publishDate") + /// } + /// } + /// + /// // SELECT book.* + /// // FROM book + /// // JOIN author ON author.id = book.authorId + /// // AND author.deathDate <= book.publishDate + /// let bookAlias = TableAlias() + /// let request = Book + /// .aliased(bookAlias) + /// .joining(required: Book.author.filter { $0.deathDate <= bookAlias.publishDate }) + /// ``` + /// + /// See ``TableRequest/aliased(_:)-3k5h4`` for more information. + public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest { all().aliased(alias) } @@ -577,18 +796,31 @@ extension TableRecord { /// latest message: /// /// ```swift - /// let latestMessageRequest = Message - /// .annotated(with: max(Column("date"))) - /// .group(Column("chatID")) + /// struct Chat: TableRecord { + /// enum Columns { + /// static let id = Column("id") + /// } + /// } /// - /// let latestMessageCTE = CommonTableExpression( + /// struct Message: TableRecord { + /// enum Columns { + /// static let date = Column("date") + /// static let chatId = Column("chatId") + /// } + /// } + /// + /// let latestMessageRequest = Message + /// .annotated { max($0.date) } + /// .group(\.chatId) + /// + /// let latestMessageCTE = CommonTableExpression( /// named: "latestMessage", /// request: latestMessageRequest) /// /// let latestMessageAssociation = Chat.association( /// to: latestMessageCTE, /// on: { chat, latestMessage in - /// chat[Column("id")] == latestMessage[Column("chatID")] + /// chat.id == latestMessage.chatId /// }) /// /// // WITH latestMessage AS @@ -605,7 +837,6 @@ extension TableRecord { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// Returns a request filtered by primary key. /// @@ -651,9 +882,9 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// ``` /// /// - parameter ids: A collection of primary keys - public static func filter(ids: IDS) -> QueryInterfaceRequest - where IDS: Collection, IDS.Element == ID - { + public static func filter( + ids: some Collection + ) -> QueryInterfaceRequest { all().filter(ids: ids) } } diff --git a/GRDB/Record/EncodableRecord+Encodable.swift b/GRDB/Record/EncodableRecord+Encodable.swift index 4ecbd5f80..788f4b1c9 100644 --- a/GRDB/Record/EncodableRecord+Encodable.swift +++ b/GRDB/Record/EncodableRecord+Encodable.swift @@ -118,11 +118,17 @@ private class RecordEncoder: Encoder { fileprivate func encode(_ value: T, forKey key: any CodingKey) throws where T: Encodable { if let data = value as? Data { - persist(Record.databaseDataEncodingStrategy.encode(data), forKey: key) + let column = keyEncodingStrategy.column(forKey: key) + let dbValue = try Record.databaseDataEncodingStrategy(for: column).encode(data) + _persistenceContainer[column] = dbValue } else if let date = value as? Date { - persist(Record.databaseDateEncodingStrategy.encode(date), forKey: key) + let column = keyEncodingStrategy.column(forKey: key) + let dbValue = Record.databaseDateEncodingStrategy(for: column).encode(date) + _persistenceContainer[column] = dbValue } else if let uuid = value as? UUID { - persist(Record.databaseUUIDEncodingStrategy.encode(uuid), forKey: key) + let column = keyEncodingStrategy.column(forKey: key) + let dbValue = Record.databaseUUIDEncodingStrategy(for: column).encode(uuid) + _persistenceContainer[column] = dbValue } else if let value = value as? any DatabaseValueConvertible { // Prefer DatabaseValueConvertible encoding over Decodable. persist(value.databaseValue, forKey: key) @@ -150,7 +156,7 @@ private class RecordEncoder: Encoder { // eventually perform JSON decoding. // TODO: possible optimization: avoid this conversion to string, // and store raw data bytes as an SQLite string - let jsonString = String(data: jsonData, encoding: .utf8)! + let jsonString = String(decoding: jsonData, as: UTF8.self) persist(jsonString, forKey: key) } } @@ -223,7 +229,7 @@ extension RecordEncoder: SingleValueEncodingContainer { unsupportedSingleValueEncoding() } - func encode(_ value: T) throws where T : Encodable { + func encode(_ value: T) throws where T: Encodable { if let record = value as? EncodableRecord { try record.encode(to: &_persistenceContainer) } else { diff --git a/GRDB/Record/EncodableRecord.swift b/GRDB/Record/EncodableRecord.swift index b1015c751..27f995370 100644 --- a/GRDB/Record/EncodableRecord.swift +++ b/GRDB/Record/EncodableRecord.swift @@ -20,11 +20,11 @@ import Foundation // For JSONEncoder /// ### Configuring Persistence for the Standard Encodable Protocol /// /// - ``databaseColumnEncodingStrategy-5sx4v`` -/// - ``databaseDataEncodingStrategy-9y0c7`` -/// - ``databaseDateEncodingStrategy-2gtc1`` -/// - ``databaseEncodingUserInfo-8upii`` +/// - ``databaseDataEncodingStrategy(for:)`` +/// - ``databaseDateEncodingStrategy(for:)`` /// - ``databaseJSONEncoder(for:)-6x62c`` -/// - ``databaseUUIDEncodingStrategy-2t96q`` +/// - ``databaseUUIDEncodingStrategy(for:)`` +/// - ``databaseEncodingUserInfo-8upii`` /// - ``DatabaseColumnEncodingStrategy`` /// - ``DatabaseDataEncodingStrategy`` /// - ``DatabaseDateEncodingStrategy`` @@ -89,7 +89,9 @@ public protocol EncodableRecord { /// /// struct Player: PersistableRecord, Encodable { /// // Customize the encoder name when encoding a database row - /// static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"] + /// static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { + /// [encoderName: "Database"] + /// } /// /// func encode(to encoder: Encoder) throws { /// // Print the encoder name @@ -108,6 +110,23 @@ public protocol EncodableRecord { /// encoder.userInfo = [encoderName: "JSON"] /// let data = try encoder.encode(player) /// ``` + /// + /// > Important: Make sure the `databaseEncodingUserInfo` property is + /// > explicitly declared as `[CodingUserInfoKey: Any]`. If it is not, + /// > the Swift compiler may silently miss the protocol requirement. + /// + /// > Important: Make sure the property is declared as a computed + /// > property (`static var`), instead of a stored property + /// > (`static let`). Computed properties avoid a compiler diagnostic + /// > with stored properties: + /// > + /// > ```swift + /// > // static property 'databaseEncodingUserInfo' is not + /// > // concurrency-safe because non-'Sendable' type + /// > // '[CodingUserInfoKey: Any]' may have shared + /// > // mutable state. + /// > static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [encoderName: "Database"] + /// > ``` static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { get } /// Returns the `JSONEncoder` that encodes the value for a given column. @@ -127,13 +146,15 @@ public protocol EncodableRecord { /// /// ```swift /// struct Player: EncodableRecord, Encodable { - /// static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text + /// static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy { + /// .text + /// } /// /// // Encoded as SQL text. Data must contain valid UTF8 bytes. /// var jsonData: Data /// } /// ``` - static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { get } + static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy /// The strategy for encoding `Date` columns. /// @@ -145,13 +166,15 @@ public protocol EncodableRecord { /// /// ```swift /// struct Player: EncodableRecord, Encodable { - /// static let databaseDateEncodingStrategy = DatabaseDateEncodingStrategy.timeIntervalSince1970 + /// static func databaseDateEncodingStrategy(for column: String) -> DatabaseDateEncodingStrategy { + /// .timeIntervalSince1970 + /// } /// /// // Encoded as an epoch timestamp /// var creationDate: Date /// } /// ``` - static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get } + static func databaseDateEncodingStrategy(for column: String) -> DatabaseDateEncodingStrategy /// The strategy for encoding `UUID` columns. /// @@ -163,13 +186,15 @@ public protocol EncodableRecord { /// /// ```swift /// struct Player: EncodableRecord, Encodable { - /// static let databaseUUIDEncodingStrategy = DatabaseUUIDEncodingStrategy.uppercaseString + /// static func databaseUUIDEncodingStrategy(for column: String) -> DatabaseUUIDEncodingStrategy { + /// .uppercaseString + /// } /// /// // Encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" /// var uuid: UUID /// } /// ``` - static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get } + static func databaseUUIDEncodingStrategy(for column: String) -> DatabaseUUIDEncodingStrategy /// The strategy for converting coding keys to column names. /// @@ -221,19 +246,19 @@ extension EncodableRecord { /// Returns the default strategy for encoding `Data` columns: /// ``DatabaseDataEncodingStrategy/deferredToData``. - public static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { + public static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy { .deferredToData } /// Returns the default strategy for encoding `Date` columns: /// ``DatabaseDateEncodingStrategy/deferredToDate``. - public static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { + public static func databaseDateEncodingStrategy(for column: String) -> DatabaseDateEncodingStrategy { .deferredToDate } /// Returns the default strategy for encoding `UUID` columns: /// ``DatabaseUUIDEncodingStrategy/deferredToUUID``. - public static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { + public static func databaseUUIDEncodingStrategy(for column: String) -> DatabaseUUIDEncodingStrategy { .deferredToUUID } @@ -252,7 +277,7 @@ extension EncodableRecord { /// database representation. public var databaseDictionary: [String: DatabaseValue] { get throws { - try Dictionary(PersistenceContainer(self).storage).mapValues { $0?.databaseValue ?? .null } + try Dictionary(uniqueKeysWithValues: PersistenceContainer(self)) } } } @@ -330,19 +355,32 @@ extension EncodableRecord { /// /// `PersistenceContainer` is the argument of the /// ``EncodableRecord/encode(to:)-k9pf`` method. -public struct PersistenceContainer { - // fileprivate for Row(_:PersistenceContainer) +public struct PersistenceContainer: Sendable { // The ordering of the OrderedDictionary helps generating always the same // SQL queries, and hit the statement cache. - fileprivate var storage: OrderedDictionary + private var storage: OrderedDictionary /// The value associated with the given column. + /// + /// The getter may not return the exact same value that has been + /// previously set. The only guarantee is that both are encoded + /// identically in the database. public subscript(_ column: String) -> (any DatabaseValueConvertible)? { - get { self[caseInsensitive: column] } - set { storage.updateValue(newValue, forKey: column) } + get { + storage[CaseInsensitiveIdentifier(rawValue: column)] + } + set { + storage.updateValue( + newValue?.databaseValue ?? .null, + forKey: CaseInsensitiveIdentifier(rawValue: column)) + } } /// The value associated with the given column. + /// + /// The getter may not return the exact same value that has been + /// previously set. The only guarantee is that both are encoded + /// identically in the database. public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? { get { self[column.name] } set { self[column.name] = newValue } @@ -372,66 +410,25 @@ public struct PersistenceContainer { } /// Columns stored in the container, ordered like values. - var columns: [String] { Array(storage.keys) } + var columns: [String] { storage.keys.map(\.rawValue) } /// Values stored in the container, ordered like columns. - var values: [(any DatabaseValueConvertible)?] { Array(storage.values) } + var values: [DatabaseValue] { storage.values } - /// Accesses the value associated with the given column, in a - /// case-insensitive fashion. - subscript(caseInsensitive column: String) -> (any DatabaseValueConvertible)? { - get { - if let value = storage[column] { - return value - } - let lowercaseColumn = column.lowercased() - for (key, value) in storage where key.lowercased() == lowercaseColumn { - return value - } - return nil - } - set { - if storage[column] != nil { - storage[column] = newValue - return - } - let lowercaseColumn = column.lowercased() - for key in storage.keys where key.lowercased() == lowercaseColumn { - storage[key] = newValue - return - } - - storage[column] = newValue - } - } - - // Returns nil if column is not defined - func value(forCaseInsensitiveColumn column: String) -> DatabaseValue? { - let lowercaseColumn = column.lowercased() - for (key, value) in storage where key.lowercased() == lowercaseColumn { - return value?.databaseValue ?? .null - } - return nil - } - - var isEmpty: Bool { storage.isEmpty } - - /// An iterator over the (column, value) pairs - func makeIterator() -> IndexingIterator> { - storage.makeIterator() + /// Returns ``DatabaseValue/null`` if column is not defined + func databaseValue(at column: String) -> DatabaseValue { + storage[CaseInsensitiveIdentifier(rawValue: column)] ?? .null } @usableFromInline func changesIterator(from container: PersistenceContainer) -> AnyIterator<(String, DatabaseValue)> { - var newValueIterator = makeIterator() + var newValueIterator = storage.makeIterator() return AnyIterator { // Loop until we find a change, or exhaust columns: - while let (column, newValue) = newValueIterator.next() { - let oldValue = container[caseInsensitive: column] - let oldDbValue = oldValue?.databaseValue ?? .null - let newDbValue = newValue?.databaseValue ?? .null + while let (column, newDbValue) = newValueIterator.next() { + let oldDbValue = container.storage[column] ?? .null if newDbValue != oldDbValue { - return (column, oldDbValue) + return (column.rawValue, oldDbValue) } } return nil @@ -439,13 +436,26 @@ public struct PersistenceContainer { } } +extension PersistenceContainer: RandomAccessCollection { + public typealias Index = Int + + public var startIndex: Int { storage.startIndex } + public var endIndex: Int { storage.endIndex } + + /// Returns the (column, value) pair at given index. + public subscript(position: Int) -> (String, DatabaseValue) { + let element = storage[position] + return (element.key.rawValue, element.value) + } +} + extension Row { convenience init(_ record: Record) throws { try self.init(PersistenceContainer(record)) } convenience init(_ container: PersistenceContainer) { - self.init(Dictionary(container.storage)) + self.init(impl: ArrayRowImpl(columns: container.lazy.map { ($0, $1) })) } } @@ -460,13 +470,15 @@ extension Row { /// /// ```swift /// struct Player: EncodableRecord, Encodable { -/// static let databaseDataEncodingStrategy = DatabaseDataEncodingStrategy.text +/// static func databaseDataEncodingStrategy(for column: Column) -> DatabaseDataEncodingStrategy { +/// .text +/// } /// /// // Encoded as SQL text. Data must contain valid UTF8 bytes. /// var jsonData: Data /// } /// ``` -public enum DatabaseDataEncodingStrategy { +public enum DatabaseDataEncodingStrategy: Sendable { /// Encodes `Data` columns as SQL blob. case deferredToData @@ -474,15 +486,17 @@ public enum DatabaseDataEncodingStrategy { case text /// Encodes `Data` column as the result of the user-provided function. - case custom((Data) -> (any DatabaseValueConvertible)?) + case custom(@Sendable (Data) -> (any DatabaseValueConvertible)?) - func encode(_ data: Data) -> DatabaseValue { + func encode(_ data: Data) throws -> DatabaseValue { switch self { case .deferredToData: return data.databaseValue case .text: guard let string = String(data: data, encoding: .utf8) else { - fatalError("Invalid UTF8 data") + throw EncodingError.invalidValue(data, EncodingError.Context( + codingPath: [], + debugDescription: "Non-UTF8 data can't be encoded as text in the database")) } return string.databaseValue case .custom(let format): @@ -502,13 +516,20 @@ public enum DatabaseDataEncodingStrategy { /// /// ```swift /// struct Player: EncodableRecord, Encodable { -/// static let databaseDateEncodingStrategy = DatabaseDateEncodingStrategy.timeIntervalSince1970 +/// static func databaseDateEncodingStrategy(for column: String) -> DatabaseDateEncodingStrategy {` +/// .timeIntervalSince1970 +/// } /// /// // Encoded as an epoch timestamp /// var creationDate: Date /// } /// ``` -public enum DatabaseDateEncodingStrategy { +public enum DatabaseDateEncodingStrategy: @unchecked Sendable { + // @unchecked Sendable because of `DateFormatter`, which lost its + // `Sendable` conformance with Xcode 16.3 beta. See + // . + // 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 @@ -538,9 +559,10 @@ public enum DatabaseDateEncodingStrategy { case formatted(DateFormatter) /// Encodes the result of the user-provided function - case custom((Date) -> (any DatabaseValueConvertible)?) + case custom(@Sendable (Date) -> (any DatabaseValueConvertible)?) - private static let iso8601Formatter: ISO8601DateFormatter = { + // Assume this non-Sendable instance can be used from multiple threads concurrently. + nonisolated(unsafe) private static let iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter @@ -579,7 +601,9 @@ public enum DatabaseDateEncodingStrategy { /// /// ```swift /// struct Player: EncodableRecord, Encodable { -/// static let databaseUUIDEncodingStrategy = DatabaseUUIDEncodingStrategy.uppercaseString +/// static func databaseUUIDEncodingStrategy(for column: String) -> DatabaseUUIDEncodingStrategy {` +/// .uppercaseString +/// } /// /// // Encoded in a string like "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" /// var uuid: UUID @@ -626,7 +650,7 @@ public enum DatabaseUUIDEncodingStrategy: Sendable { /// var playerID: String /// } /// ``` -public enum DatabaseColumnEncodingStrategy { +public enum DatabaseColumnEncodingStrategy: Sendable { /// A key encoding strategy that doesn’t change key names during encoding. case useDefaultKeys @@ -634,7 +658,7 @@ public enum DatabaseColumnEncodingStrategy { case convertToSnakeCase /// A key encoding strategy defined by the closure you supply. - case custom((any CodingKey) -> String) + case custom(@Sendable (any CodingKey) -> String) func column(forKey key: some CodingKey) -> String { switch self { diff --git a/GRDB/Record/FetchableRecord+Decodable.swift b/GRDB/Record/FetchableRecord+Decodable.swift index f89a12a5c..a4c6e423b 100644 --- a/GRDB/Record/FetchableRecord+Decodable.swift +++ b/GRDB/Record/FetchableRecord+Decodable.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation extension FetchableRecord where Self: Decodable { @@ -52,8 +61,8 @@ extension FetchableRecord where Self: Decodable { /// The behavior of the decoder depends on the decoded type. See: /// /// - ``FetchableRecord/databaseColumnDecodingStrategy-6uefz`` -/// - ``FetchableRecord/databaseDataDecodingStrategy-71bh1`` -/// - ``FetchableRecord/databaseDateDecodingStrategy-78y03`` +/// - ``FetchableRecord/databaseDataDecodingStrategy(for:)`` +/// - ``FetchableRecord/databaseDateDecodingStrategy(for:)`` /// - ``FetchableRecord/databaseDecodingUserInfo-77jim`` /// - ``FetchableRecord/databaseJSONDecoder(for:)-7lmxd`` public class FetchableRecordDecoder { @@ -276,13 +285,13 @@ private struct _RowDecoder: Decoder { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Data.self { - return try R.databaseDataDecodingStrategy.decodeIfPresent( - fromRow: row, - atUncheckedIndex: index) as! T? + return try R + .databaseDataDecodingStrategy(for: column) + .decodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T? } else if type == Date.self { - return try R.databaseDateDecodingStrategy.decodeIfPresent( - fromRow: row, - atUncheckedIndex: index) as! T? + return try R + .databaseDateDecodingStrategy(for: column) + .decodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T? } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { return try type.fastDecodeIfPresent(fromRow: row, atUncheckedIndex: index) as! T? } else if let type = T.self as? any DatabaseValueConvertible.Type { @@ -325,9 +334,13 @@ private struct _RowDecoder: Decoder { // Prefer DatabaseValueConvertible decoding over Decodable. // This allows decoding Date from String, or DatabaseValue from NULL. if type == Data.self { - return try R.databaseDataDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T + return try R + .databaseDataDecodingStrategy(for: column) + .decode(fromRow: row, atUncheckedIndex: index) as! T } else if type == Date.self { - return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: index) as! T + return try R + .databaseDateDecodingStrategy(for: column) + .decode(fromRow: row, atUncheckedIndex: index) as! T } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { return try type.fastDecode(fromRow: row, atUncheckedIndex: index) as! T } else if let type = T.self as? any DatabaseValueConvertible.Type { @@ -643,11 +656,16 @@ extension ColumnDecoder: SingleValueDecodingContainer { func decode(_ type: String.Type) throws -> String { try row.decode(atIndex: columnIndex) } func decode(_ type: T.Type) throws -> T where T: Decodable { - // TODO: not tested if type == Data.self { - return try R.databaseDataDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T + let columnName = row.impl.columnName(atUncheckedIndex: columnIndex) + return try R + .databaseDataDecodingStrategy(for: columnName) + .decode(fromRow: row, atUncheckedIndex: columnIndex) as! T } else if type == Date.self { - return try R.databaseDateDecodingStrategy.decode(fromRow: row, atUncheckedIndex: columnIndex) as! T + let columnName = row.impl.columnName(atUncheckedIndex: columnIndex) + return try R + .databaseDateDecodingStrategy(for: columnName) + .decode(fromRow: row, atUncheckedIndex: columnIndex) as! T } else if let type = T.self as? any (DatabaseValueConvertible & StatementColumnConvertible).Type { return try type.fastDecode(fromRow: row, atUncheckedIndex: columnIndex) as! T } else if let type = T.self as? any DatabaseValueConvertible.Type { @@ -658,7 +676,8 @@ extension ColumnDecoder: SingleValueDecodingContainer { } } -private let iso8601Formatter: ISO8601DateFormatter = { +// Assume this non-Sendable instance can be used from multiple threads concurrently. +nonisolated(unsafe) private let iso8601Formatter: ISO8601DateFormatter = { let formatter = ISO8601DateFormatter() formatter.formatOptions = .withInternetDateTime return formatter diff --git a/GRDB/Record/FetchableRecord+TableRecord.swift b/GRDB/Record/FetchableRecord+TableRecord.swift index 97178adeb..b75511064 100644 --- a/GRDB/Record/FetchableRecord+TableRecord.swift +++ b/GRDB/Record/FetchableRecord+TableRecord.swift @@ -128,10 +128,10 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, keys: Keys) - throws -> RecordCursor - where Keys: Sequence, Keys.Element: DatabaseValueConvertible - { + public static func fetchCursor( + _ db: Database, + keys: some Collection + ) throws -> RecordCursor { try filter(keys: keys).fetchCursor(db) } @@ -154,11 +154,10 @@ extension FetchableRecord where Self: TableRecord { /// - keys: A sequence of primary keys. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, keys: Keys) - throws -> [Self] - where Keys: Sequence, Keys.Element: DatabaseValueConvertible - { - let keys = Array(keys) + public static func fetchAll( + _ db: Database, + keys: some Collection + ) throws -> [Self] { if keys.isEmpty { // Avoid hitting the database return [] @@ -217,7 +216,6 @@ extension FetchableRecord where Self: TableRecord { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseValueConvertible { // MARK: Fetching by Single-Column Primary Key @@ -249,10 +247,10 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// - ids: A collection of primary keys. /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchCursor(_ db: Database, ids: IDS) - throws -> RecordCursor - where IDS: Collection, IDS.Element == ID - { + public static func fetchCursor( + _ db: Database, + ids: some Collection + ) throws -> RecordCursor { try filter(ids: ids).fetchCursor(db) } @@ -275,9 +273,10 @@ extension FetchableRecord where Self: TableRecord & Identifiable, ID: DatabaseVa /// - ids: A collection of primary keys. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchAll(_ db: Database, ids: IDS) throws -> [Self] - where IDS: Collection, IDS.Element == ID - { + public static func fetchAll( + _ db: Database, + ids: some Collection + ) throws -> [Self] { if ids.isEmpty { // Avoid hitting the database return [] @@ -346,11 +345,10 @@ extension FetchableRecord where Self: TableRecord & Hashable { /// - keys: A sequence of primary keys. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, keys: Keys) - throws -> Set - where Keys: Sequence, Keys.Element: DatabaseValueConvertible - { - let keys = Array(keys) + public static func fetchSet( + _ db: Database, + keys: some Collection + ) throws -> Set { if keys.isEmpty { // Avoid hitting the database return [] @@ -359,7 +357,6 @@ extension FetchableRecord where Self: TableRecord & Hashable { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID: DatabaseValueConvertible { /// Returns a set of records identified by their primary keys. /// @@ -377,9 +374,10 @@ extension FetchableRecord where Self: TableRecord & Hashable & Identifiable, ID: /// - ids: A collection of primary keys. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. - public static func fetchSet(_ db: Database, ids: IDS) throws -> Set - where IDS: Collection, IDS.Element == ID - { + public static func fetchSet( + _ db: Database, + ids: some Collection + ) throws -> Set { if ids.isEmpty { // Avoid hitting the database return [] diff --git a/GRDB/Record/FetchableRecord.swift b/GRDB/Record/FetchableRecord.swift index 609279560..5cb2b0b58 100644 --- a/GRDB/Record/FetchableRecord.swift +++ b/GRDB/Record/FetchableRecord.swift @@ -26,10 +26,16 @@ import Foundation /// struct Player: FetchableRecord, TableRecord, Decodable { /// var name: String /// var score: Int +/// +/// enum Columns { +/// static let name = Column("name") +/// static let score = Column("score") +/// } /// } /// /// let players = try Player.fetchAll(db) -/// let players = try Player.order(Column("score")).fetchAll(db) +/// let player = try Player.filter { $0.name == "O'Brien" }.fetchOne(db) +/// let players = try Player.order(\.score).fetchAll(db) /// ``` /// /// ## Topics @@ -71,9 +77,9 @@ import Foundation /// - ``fetchAll(_:ids:)`` /// - ``fetchSet(_:ids:)`` /// - ``fetchOne(_:id:)`` -/// - ``fetchCursor(_:keys:)-2jrm1`` -/// - ``fetchAll(_:keys:)-4c8no`` -/// - ``fetchSet(_:keys:)-e6uy`` +/// - ``fetchCursor(_:keys:)-1x4ja`` +/// - ``fetchAll(_:keys:)-60fah`` +/// - ``fetchSet(_:keys:)-7lhcn`` /// - ``fetchOne(_:key:)-3f3hc`` /// - ``find(_:id:)`` /// - ``find(_:key:)-4kry5`` @@ -89,10 +95,10 @@ import Foundation /// ### Configuring Row Decoding for the Standard Decodable Protocol /// /// - ``databaseColumnDecodingStrategy-6uefz`` -/// - ``databaseDataDecodingStrategy-71bh1`` -/// - ``databaseDateDecodingStrategy-78y03`` -/// - ``databaseDecodingUserInfo-77jim`` +/// - ``databaseDataDecodingStrategy(for:)`` +/// - ``databaseDateDecodingStrategy(for:)`` /// - ``databaseJSONDecoder(for:)-7lmxd`` +/// - ``databaseDecodingUserInfo-77jim`` /// - ``DatabaseColumnDecodingStrategy`` /// - ``DatabaseDataDecodingStrategy`` /// - ``DatabaseDateDecodingStrategy`` @@ -129,7 +135,9 @@ public protocol FetchableRecord { /// // A FetchableRecord + Decodable record /// struct Player: FetchableRecord, Decodable { /// // Customize the decoder name when decoding a database row - /// static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "Database"] + /// static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { + /// [decoderName: "Database"] + /// } /// /// init(from decoder: Decoder) throws { /// // Print the decoder name @@ -146,6 +154,23 @@ public protocol FetchableRecord { /// decoder.userInfo = [decoderName: "JSON"] /// let player = try decoder.decode(Player.self, from: ...) /// ``` + /// + /// > Important: Make sure the `databaseDecodingUserInfo` property is + /// > explicitly declared as `[CodingUserInfoKey: Any]`. If it is not, + /// > the Swift compiler may silently miss the protocol requirement. + /// + /// > Important: Make sure the property is declared as a computed + /// > property (`static var`), instead of a stored property + /// > (`static let`). Computed properties avoid a compiler diagnostic + /// > with stored properties: + /// > + /// > ```swift + /// > // static property 'databaseDecodingUserInfo' is not + /// > // concurrency-safe because non-'Sendable' type + /// > // '[CodingUserInfoKey: Any]' may have shared + /// > // mutable state. + /// > static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "Database"] + /// > ``` static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { get } /// Returns the `JSONDecoder` that decodes the value for a given column. @@ -165,18 +190,20 @@ public protocol FetchableRecord { /// /// ```swift /// struct Player: FetchableRecord, Decodable { - /// static let databaseDataDecodingStrategy = DatabaseDataDecodingStrategy.custom { dbValue - /// guard let base64Data = Data.fromDatabaseValue(dbValue) else { - /// return nil + /// static func databaseDataDecodingStrategy(for column: String) -> DatabaseDataDecodingStrategy { + /// .custom { dbValue + /// guard let base64Data = Data.fromDatabaseValue(dbValue) else { + /// return nil + /// } + /// return Data(base64Encoded: base64Data) /// } - /// return Data(base64Encoded: base64Data) /// } /// /// // Decoded from both database base64 strings and blobs /// var myData: Data /// } /// ``` - static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { get } + static func databaseDataDecodingStrategy(for column: String) -> DatabaseDataDecodingStrategy /// The strategy for decoding `Date` columns. /// @@ -188,13 +215,15 @@ public protocol FetchableRecord { /// /// ```swift /// struct Player: FetchableRecord, Decodable { - /// static let databaseDateDecodingStrategy = DatabaseDateDecodingStrategy.timeIntervalSince1970 + /// static func databaseDateDecodingStrategy(for column: String) -> DatabaseDateDecodingStrategy { + /// .timeIntervalSince1970 + /// } /// /// // Decoded from an epoch timestamp /// var creationDate: Date /// } /// ``` - static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get } + static func databaseDateDecodingStrategy(for column: String) -> DatabaseDateDecodingStrategy /// The strategy for converting column names to coding keys. /// @@ -243,13 +272,13 @@ extension FetchableRecord { /// The default strategy for decoding `Data` columns is /// ``DatabaseDataDecodingStrategy/deferredToData``. - public static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { + public static func databaseDataDecodingStrategy(for column: String) -> DatabaseDataDecodingStrategy { .deferredToData } /// The default strategy for decoding `Date` columns is /// ``DatabaseDateDecodingStrategy/deferredToDate``. - public static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { + public static func databaseDateDecodingStrategy(for column: String) -> DatabaseDateDecodingStrategy { .deferredToDate } @@ -529,20 +558,32 @@ extension FetchableRecord { /// For example: /// /// ```swift + /// struct Player: FetchableRecord, TableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// + /// enum Columns { + /// static let id = Column(CodingKeys.id) + /// static let name = Column(CodingKeys.name) + /// static let score = Column(CodingKeys.score) + /// } + /// } + /// /// try dbQueue.read { db in - /// let lastName = "O'Reilly" + /// let name = "O'Reilly" /// /// // Query interface request - /// let request = Player.filter(Column("lastName") == lastName) + /// let request = Player.filter { $0.name == name } /// /// // SQL request /// let request: SQLRequest = """ - /// SELECT * FROM player WHERE lastName = \(lastName) + /// SELECT * FROM player WHERE name = \(name) /// """ /// /// let players = try Player.fetchCursor(db, request) /// while let player = try players.next() { - /// print(player.name) + /// print(player.score) /// } /// } /// ``` @@ -555,7 +596,7 @@ extension FetchableRecord { /// /// - parameters: /// - db: A database connection. - /// - sql: a FetchRequest. + /// - request: a fetch request. /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchCursor(_ db: Database, _ request: some FetchRequest) throws -> RecordCursor { @@ -569,15 +610,27 @@ extension FetchableRecord { /// For example: /// /// ```swift + /// struct Player: FetchableRecord, TableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// + /// enum Columns { + /// static let id = Column(CodingKeys.id) + /// static let name = Column(CodingKeys.name) + /// static let score = Column(CodingKeys.score) + /// } + /// } + /// /// try dbQueue.read { db in - /// let lastName = "O'Reilly" + /// let name = "O'Reilly" /// /// // Query interface request - /// let request = Player.filter(Column("lastName") == lastName) + /// let request = Player.filter { $0.name == name } /// /// // SQL request /// let request: SQLRequest = """ - /// SELECT * FROM player WHERE lastName = \(lastName) + /// SELECT * FROM player WHERE name = \(name) /// """ /// /// let players = try Player.fetchAll(db, request) @@ -586,7 +639,7 @@ extension FetchableRecord { /// /// - parameters: /// - db: A database connection. - /// - sql: a FetchRequest. + /// - request: a fetch request. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchAll(_ db: Database, _ request: some FetchRequest) throws -> [Self] { @@ -605,15 +658,27 @@ extension FetchableRecord { /// For example: /// /// ```swift + /// struct Player: FetchableRecord, TableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// + /// enum Columns { + /// static let id = Column(CodingKeys.id) + /// static let name = Column(CodingKeys.name) + /// static let score = Column(CodingKeys.score) + /// } + /// } + /// /// try dbQueue.read { db in - /// let lastName = "O'Reilly" + /// let name = "O'Reilly" /// /// // Query interface request - /// let request = Player.filter(Column("lastName") == lastName) + /// let request = Player.filter { $0.name == name } /// /// // SQL request /// let request: SQLRequest = """ - /// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1 + /// SELECT * FROM player WHERE name = \(name) LIMIT 1 /// """ /// /// let player = try Player.fetchOne(db, request) @@ -621,7 +686,7 @@ extension FetchableRecord { /// ``` /// - parameters: /// - db: A database connection. - /// - sql: a FetchRequest. + /// - request: a fetch request. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchOne(_ db: Database, _ request: some FetchRequest) throws -> Self? { @@ -644,15 +709,27 @@ extension FetchableRecord where Self: Hashable { /// For example: /// /// ```swift + /// struct Player: FetchableRecord, TableRecord, Hashable { + /// var id: Int64 + /// var name: String + /// var score: Int + /// + /// enum Columns { + /// static let id = Column(CodingKeys.id) + /// static let name = Column(CodingKeys.name) + /// static let score = Column(CodingKeys.score) + /// } + /// } + /// /// try dbQueue.read { db in - /// let lastName = "O'Reilly" + /// let name = "O'Reilly" /// /// // Query interface request - /// let request = Player.filter(Column("lastName") == lastName) + /// let request = Player.filter { $0.name == name } /// /// // SQL request /// let request: SQLRequest = """ - /// SELECT * FROM player WHERE lastName = \(lastName) + /// SELECT * FROM player WHERE name = \(name) /// """ /// /// let players = try Player.fetchSet(db, request) @@ -661,7 +738,7 @@ extension FetchableRecord where Self: Hashable { /// /// - parameters: /// - db: A database connection. - /// - sql: a FetchRequest. + /// - request: a fetch request. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public static func fetchSet(_ db: Database, _ request: some FetchRequest) throws -> Set { @@ -688,15 +765,27 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// For example: /// /// ```swift + /// struct Player: FetchableRecord, TableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// + /// enum Columns { + /// static let id = Column(CodingKeys.id) + /// static let name = Column(CodingKeys.name) + /// static let score = Column(CodingKeys.score) + /// } + /// } + /// /// try dbQueue.read { db in - /// let lastName = "O'Reilly" + /// let name = "O'Reilly" /// /// // Query interface request - /// let request = Player.filter(Column("lastName") == lastName) + /// let request = Player.filter { $0.name == name } /// /// // SQL request /// let request: SQLRequest = """ - /// SELECT * FROM player WHERE lastName = \(lastName) + /// SELECT * FROM player WHERE name = \(name) /// """ /// /// let players = try request.fetchCursor(db) @@ -714,7 +803,6 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// /// - parameters: /// - db: A database connection. - /// - sql: a FetchRequest. /// - returns: A ``RecordCursor`` over fetched records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchCursor(_ db: Database) throws -> RecordCursor { @@ -726,15 +814,27 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// For example: /// /// ```swift + /// struct Player: FetchableRecord, TableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// + /// enum Columns { + /// static let id = Column(CodingKeys.id) + /// static let name = Column(CodingKeys.name) + /// static let score = Column(CodingKeys.score) + /// } + /// } + /// /// try dbQueue.read { db in - /// let lastName = "O'Reilly" + /// let name = "O'Reilly" /// /// // Query interface request - /// let request = Player.filter(Column("lastName") == lastName) + /// let request = Player.filter { $0.name == name } /// /// // SQL request /// let request: SQLRequest = """ - /// SELECT * FROM player WHERE lastName = \(lastName) + /// SELECT * FROM player WHERE name = \(name) /// """ /// /// let players = try request.fetchAll(db) @@ -743,7 +843,6 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// /// - parameters: /// - db: A database connection. - /// - sql: a FetchRequest. /// - returns: An array of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchAll(_ db: Database) throws -> [RowDecoder] { @@ -755,15 +854,27 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// For example: /// /// ```swift + /// struct Player: FetchableRecord, TableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// + /// enum Columns { + /// static let id = Column(CodingKeys.id) + /// static let name = Column(CodingKeys.name) + /// static let score = Column(CodingKeys.score) + /// } + /// } + /// /// try dbQueue.read { db in - /// let lastName = "O'Reilly" + /// let name = "O'Reilly" /// /// // Query interface request - /// let request = Player.filter(Column("lastName") == lastName) + /// let request = Player.filter { $0.name == name } /// /// // SQL request /// let request: SQLRequest = """ - /// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1 + /// SELECT * FROM player WHERE name = \(name) LIMIT 1 /// """ /// /// let player = try request.fetchOne(db) @@ -771,7 +882,6 @@ extension FetchRequest where RowDecoder: FetchableRecord { /// ``` /// - parameters: /// - db: A database connection. - /// - sql: a FetchRequest. /// - returns: An optional record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchOne(_ db: Database) throws -> RowDecoder? { @@ -785,15 +895,27 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable { /// For example: /// /// ```swift + /// struct Player: FetchableRecord, TableRecord, Hashable { + /// var id: Int64 + /// var name: String + /// var score: Int + /// + /// enum Columns { + /// static let id = Column(CodingKeys.id) + /// static let name = Column(CodingKeys.name) + /// static let score = Column(CodingKeys.score) + /// } + /// } + /// /// try dbQueue.read { db in - /// let lastName = "O'Reilly" + /// let name = "O'Reilly" /// /// // Query interface request - /// let request = Player.filter(Column("lastName") == lastName) + /// let request = Player.filter { $0.name == name } /// /// // SQL request /// let request: SQLRequest = """ - /// SELECT * FROM player WHERE lastName = \(lastName) + /// SELECT * FROM player WHERE name = \(name) /// """ /// /// let players = try request.fetchSet(db) @@ -802,7 +924,6 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable { /// /// - parameters: /// - db: A database connection. - /// - sql: a FetchRequest. /// - returns: A set of records. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func fetchSet(_ db: Database) throws -> Set { @@ -869,18 +990,20 @@ extension RecordCursor: Sendable { } /// /// ```swift /// struct Player: FetchableRecord, Decodable { -/// static let databaseDataDecodingStrategy = DatabaseDataDecodingStrategy.custom { dbValue -/// guard let base64Data = Data.fromDatabaseValue(dbValue) else { -/// return nil +/// static func databaseDataDecodingStrategy(for column: String) -> DatabaseDataDecodingStrategy { +/// .custom { dbValue +/// guard let base64Data = Data.fromDatabaseValue(dbValue) else { +/// return nil +/// } +/// return Data(base64Encoded: base64Data) /// } -/// return Data(base64Encoded: base64Data) /// } /// /// // Decoded from both database base64 strings and blobs /// var myData: Data /// } /// ``` -public enum DatabaseDataDecodingStrategy { +public enum DatabaseDataDecodingStrategy: Sendable { /// Decodes `Data` columns from SQL blobs and UTF8 text. case deferredToData @@ -889,7 +1012,7 @@ public enum DatabaseDataDecodingStrategy { /// If the database value does not contain a suitable value, the function /// must return nil (GRDB will interpret this nil result as a conversion /// error, and react accordingly). - case custom((DatabaseValue) -> Data?) + case custom(@Sendable (DatabaseValue) -> Data?) } // MARK: - DatabaseDateDecodingStrategy @@ -901,12 +1024,19 @@ public enum DatabaseDataDecodingStrategy { /// For example: /// /// struct Player: FetchableRecord, Decodable { -/// static let databaseDateDecodingStrategy = DatabaseDateDecodingStrategy.timeIntervalSince1970 +/// static func databaseDateDecodingStrategy(for column: String) -> DatabaseDateDecodingStrategy { +/// .timeIntervalSince1970 +/// } /// /// var name: String /// var registrationDate: Date // decoded from epoch timestamp /// } -public enum DatabaseDateDecodingStrategy { +public enum DatabaseDateDecodingStrategy: @unchecked Sendable { + // @unchecked Sendable because of `DateFormatter`, which lost its + // `Sendable` conformance with Xcode 16.3 beta. See + // . + // 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 @@ -947,7 +1077,7 @@ public enum DatabaseDateDecodingStrategy { /// If the database value does not contain a suitable value, the function /// must return nil (GRDB will interpret this nil result as a conversion /// error, and react accordingly). - case custom((DatabaseValue) -> Date?) + case custom(@Sendable (DatabaseValue) -> Date?) } // MARK: - DatabaseColumnDecodingStrategy @@ -964,7 +1094,7 @@ public enum DatabaseDateDecodingStrategy { /// // Decoded from the player_id column /// var playerID: Int /// } -public enum DatabaseColumnDecodingStrategy { +public enum DatabaseColumnDecodingStrategy: Sendable { /// A key decoding strategy that doesn’t change key names during decoding. case useDefaultKeys @@ -972,7 +1102,7 @@ public enum DatabaseColumnDecodingStrategy { case convertFromSnakeCase /// A key decoding strategy defined by the closure you supply. - case custom((String) -> CodingKey) + case custom(@Sendable (String) -> CodingKey) func key(forColumn column: String) -> K? { switch self { diff --git a/GRDB/Record/MutablePersistableRecord+DAO.swift b/GRDB/Record/MutablePersistableRecord+DAO.swift index 48b9025c8..de15f6e87 100644 --- a/GRDB/Record/MutablePersistableRecord+DAO.swift +++ b/GRDB/Record/MutablePersistableRecord+DAO.swift @@ -42,8 +42,11 @@ final class DAO { func upsertStatement( _ db: Database, onConflict conflictTargetColumns: [String], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, - updateCondition: ((_ existing: TableAlias, _ excluded: TableAlias) -> any SQLExpressible)? = nil, + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, + updateCondition: (( + _ existing: TableAlias, + _ excluded: TableAlias + ) -> any SQLExpressible)? = nil, returning selection: [any SQLSelectable]) throws -> Statement { @@ -73,7 +76,7 @@ final class DAO { // that no information stored in the record is lost, unless explicitly // requested by the user. sql += " DO UPDATE SET " - let excluded = TableAlias(name: "excluded") + let excluded = TableAlias(name: "excluded") var assignments = assignments?(excluded) ?? [] let lowercaseExcludedColumns = Set(primaryKey.columns.map { $0.lowercased() }) .union(conflictTargetColumns.map { $0.lowercased() }) @@ -119,7 +122,7 @@ final class DAO { } // WHERE - let existing = TableAlias(name: databaseTableName) + let existing = TableAlias(name: databaseTableName) if let condition = updateCondition?(existing, excluded) { let context = SQLGenerationContext(db) sql += try " WHERE " + condition.sqlExpression.sql(context) @@ -142,7 +145,7 @@ final class DAO { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { - persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null + persistenceContainer.databaseValue(at: $0) } if primaryKeyValues.allSatisfy({ $0.isNull }) { return nil @@ -173,7 +176,7 @@ final class DAO { } let updatedValues = updatedColumns.map { - persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null + persistenceContainer.databaseValue(at: $0) } let query = UpdateQuery( @@ -193,7 +196,7 @@ final class DAO { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { - persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null + persistenceContainer.databaseValue(at: $0) } if primaryKeyValues.allSatisfy({ $0.isNull }) { return nil @@ -212,7 +215,7 @@ final class DAO { // Fail early if primary key does not resolve to a database row. let primaryKeyColumns = primaryKey.columns let primaryKeyValues = primaryKeyColumns.map { - persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null + persistenceContainer.databaseValue(at: $0) } if primaryKeyValues.allSatisfy({ $0.isNull }) { return nil @@ -229,7 +232,7 @@ final class DAO { /// Throws a RecordError.recordNotFound error func recordNotFound() throws -> Never { let key = Dictionary(uniqueKeysWithValues: primaryKey.columns.map { - ($0, persistenceContainer[caseInsensitive: $0]?.databaseValue ?? .null) + ($0, persistenceContainer.databaseValue(at: $0)) }) throw RecordError.recordNotFound( databaseTableName: databaseTableName, @@ -249,12 +252,17 @@ final class DAO { 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 = TableAliasBase(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) @@ -273,29 +281,33 @@ private struct InsertQuery: Hashable { } extension InsertQuery { - @ReadWriteBox private static var sqlCache: [InsertQuery: String] = [:] + private static let cacheLock: ReadWriteLock<[InsertQuery: String]> = ReadWriteLock([:]) var sql: String { - if let sql = Self.sqlCache[self] { + if let sql = Self.cacheLock.read({ $0[self] }) { return sql } - let columnsSQL = insertedColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ") - let valuesSQL = databaseQuestionMarks(count: insertedColumns.count) - let sql: String - switch onConflict { - case .abort: - sql = """ - INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ - VALUES (\(valuesSQL)) - """ - default: - sql = """ - INSERT OR \(onConflict.rawValue) \ - INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ - VALUES (\(valuesSQL)) - """ + + return Self.cacheLock.withLock { cache in + let columnsSQL = insertedColumns.map(\.quotedDatabaseIdentifier).joined(separator: ", ") + let valuesSQL = databaseQuestionMarks(count: insertedColumns.count) + let sql: String + switch onConflict { + case .abort: + sql = """ + INSERT INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ + VALUES (\(valuesSQL)) + """ + default: + sql = """ + INSERT OR \(onConflict.rawValue) \ + INTO \(tableName.quotedDatabaseIdentifier) (\(columnsSQL)) \ + VALUES (\(valuesSQL)) + """ + } + + cache[self] = sql + return sql } - Self.sqlCache[self] = sql - return sql } } @@ -309,30 +321,34 @@ private struct UpdateQuery: Hashable { } extension UpdateQuery { - @ReadWriteBox private static var sqlCache: [UpdateQuery: String] = [:] + private static let cacheLock: ReadWriteLock<[UpdateQuery: String]> = ReadWriteLock([:]) var sql: String { - if let sql = Self.sqlCache[self] { + if let sql = Self.cacheLock.read({ $0[self] }) { return sql } - let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ") - let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ") - let sql: String - switch onConflict { - case .abort: - sql = """ - UPDATE \(tableName.quotedDatabaseIdentifier) \ - SET \(updateSQL) \ - WHERE \(whereSQL) - """ - default: - sql = """ - UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) \ - SET \(updateSQL) \ - WHERE \(whereSQL) - """ + + return Self.cacheLock.withLock { cache in + let updateSQL = updatedColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: ", ") + let whereSQL = conditionColumns.map { "\($0.quotedDatabaseIdentifier)=?" }.joined(separator: " AND ") + let sql: String + switch onConflict { + case .abort: + sql = """ + UPDATE \(tableName.quotedDatabaseIdentifier) \ + SET \(updateSQL) \ + WHERE \(whereSQL) + """ + default: + sql = """ + UPDATE OR \(onConflict.rawValue) \(tableName.quotedDatabaseIdentifier) \ + SET \(updateSQL) \ + WHERE \(whereSQL) + """ + } + + cache[self] = sql + return sql } - Self.sqlCache[self] = sql - return sql } } diff --git a/GRDB/Record/MutablePersistableRecord+Insert.swift b/GRDB/Record/MutablePersistableRecord+Insert.swift index 4b2b1e1d0..59eaae110 100644 --- a/GRDB/Record/MutablePersistableRecord+Insert.swift +++ b/GRDB/Record/MutablePersistableRecord+Insert.swift @@ -91,7 +91,6 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER - // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` statement, and returns a new record built /// from the inserted row. /// @@ -108,22 +107,22 @@ extension MutablePersistableRecord { /// - parameter conflictResolution: A policy for conflict resolution. If /// nil, /// is used. - /// - returns: The inserted record, if any. The result can be nil when the - /// conflict policy is `IGNORE`. + /// - returns: The inserted record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the insertion failed due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public func insertAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil) - throws -> Self? + throws -> Self where Self: FetchableRecord { var result = self return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self) } - // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` statement, and returns a new record built /// from the inserted row. /// @@ -161,11 +160,10 @@ extension MutablePersistableRecord { /// var partialPlayer = PartialPlayer(name: "Alice") /// /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * - /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { - /// print(player.id) // The inserted id - /// print(player.name) // The inserted name - /// print(player.score) // The default score - /// } + /// let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) + /// print(player.id) // The inserted id + /// print(player.name) // The inserted name + /// print(player.score) // The default score /// } /// ``` /// @@ -174,19 +172,24 @@ extension MutablePersistableRecord { /// nil, /// is used. /// - parameter returnedType: The type of the returned record. - /// - returns: A record of type `returnedType`, if any. The result can be - /// nil when the conflict policy is `IGNORE`. + /// - returns: A record of type `returnedType`. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the insertion failed due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public mutating func insertAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, as returnedType: T.Type) - throws -> T? + throws -> T { - try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { - try T.fetchOne($0) + let record = self + return try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { + if let result = try T.fetchOne($0) { + return result + } + throw record.recordNotFound(db) } } @@ -265,8 +268,74 @@ extension MutablePersistableRecord { didSave(PersistenceSuccess(success.inserted)) return success.returned } + + /// Executes an `INSERT RETURNING` statement, and returns the selected + /// columns from the inserted row. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// ```swift + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } + /// + /// // A player with partial database information + /// struct PartialPlayer: MutablePersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// // Insert a partial player, get the inserted score + /// try dbQueue.write { db in + /// var partialPlayer = PartialPlayer(name: "Alice") + /// + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score + /// let score = try partialPlayer.insertAndFetch(db) { statement in + /// try Int.fetchOne(statement) + /// } select: { + /// [$0.score] + /// } + /// print(score) // The inserted score + /// } + /// ``` + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. + /// - parameter fetch: A closure that executes its ``Statement`` argument. + /// If the conflict policy is `IGNORE`, the statement may return no row. + /// - parameter select: A closure that returns the returned columns + /// (must not be empty). + /// - returns: The result of the `fetch` function. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. + /// - precondition: The result of `select` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + public mutating func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + fetch: (Statement) throws -> T, + select: (DatabaseComponents) throws -> [any SQLSelectable] + ) throws -> T + where Self: TableRecord + { + try insertAndFetch(db, onConflict: conflictResolution, selection: select(Self.databaseComponents), fetch: fetch) + } #else - // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` statement, and returns a new record built /// from the inserted row. /// @@ -283,23 +352,23 @@ extension MutablePersistableRecord { /// - parameter conflictResolution: A policy for conflict resolution. If /// nil, /// is used. - /// - returns: The inserted record, if any. The result can be nil when the - /// conflict policy is `IGNORE`. + /// - returns: The inserted record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the insertion failed due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func insertAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil) - throws -> Self? + throws -> Self where Self: FetchableRecord { var result = self return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self) } - // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` statement, and returns a new record built /// from the inserted row. /// @@ -337,11 +406,10 @@ extension MutablePersistableRecord { /// var partialPlayer = PartialPlayer(name: "Alice") /// /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * - /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { - /// print(player.id) // The inserted id - /// print(player.name) // The inserted name - /// print(player.score) // The default score - /// } + /// let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) + /// print(player.id) // The inserted id + /// print(player.name) // The inserted name + /// print(player.score) // The default score /// } /// ``` /// @@ -350,20 +418,25 @@ extension MutablePersistableRecord { /// nil, /// is used. /// - parameter returnedType: The type of the returned record. - /// - returns: A record of type `returnedType`, if any. The result can be - /// nil when the conflict policy is `IGNORE`. + /// - returns: A record of type `returnedType`. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the insertion failed due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func insertAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, as returnedType: T.Type) - throws -> T? + throws -> T { - try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { - try T.fetchOne($0) + let record = self + return try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { + if let result = try T.fetchOne($0) { + return result + } + throw record.recordNotFound(db) } } @@ -443,6 +516,78 @@ extension MutablePersistableRecord { didSave(PersistenceSuccess(success.inserted)) return success.returned } + + /// Executes an `INSERT RETURNING` statement, and returns the selected + /// columns from the inserted row. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// ```swift + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } + /// + /// // A player with partial database information + /// struct PartialPlayer: MutablePersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// // Insert a partial player, get the inserted score + /// try dbQueue.write { db in + /// var partialPlayer = PartialPlayer(name: "Alice") + /// + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score + /// let score = try partialPlayer.insertAndFetch(db) { statement in + /// try Int.fetchOne(statement) + /// } select: { + /// [$0.score] + /// } + /// print(score) // The inserted score + /// } + /// ``` + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. + /// - parameter fetch: A closure that executes its ``Statement`` argument. + /// If the conflict policy is `IGNORE`, the statement may return no row. + /// - parameter select: A closure that returns the returned columns + /// (must not be empty). + /// - returns: The result of the `fetch` function. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. + /// - precondition: The result of `select` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ + public mutating func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + fetch: (Statement) throws -> T, + select: (DatabaseComponents) throws -> [any SQLSelectable] + ) throws -> T + where Self: TableRecord + { + try insertAndFetch( + db, + onConflict: conflictResolution, + selection: select(Self.databaseComponents), + fetch: fetch) + } #endif } @@ -519,7 +664,7 @@ extension MutablePersistableRecord { // to false in its `aroundInsert` callback. var persistenceContainer = dao.persistenceContainer if let rowIDColumn { - persistenceContainer[caseInsensitive: rowIDColumn] = rowid + persistenceContainer[rowIDColumn] = rowid } let inserted = InsertionSuccess( diff --git a/GRDB/Record/MutablePersistableRecord+Save.swift b/GRDB/Record/MutablePersistableRecord+Save.swift index a9776cc82..a57988433 100644 --- a/GRDB/Record/MutablePersistableRecord+Save.swift +++ b/GRDB/Record/MutablePersistableRecord+Save.swift @@ -87,7 +87,6 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER - // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and /// returns a new record built from the saved row. /// @@ -107,22 +106,22 @@ extension MutablePersistableRecord { /// - parameter conflictResolution: A policy for conflict resolution. If /// nil, /// is used. - /// - returns: The saved record. The result can be nil when the - /// conflict policy is `IGNORE`. + /// - returns: The saved record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the database changes fail due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public func saveAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil) - throws -> Self? + throws -> Self where Self: FetchableRecord { var result = self return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self) } - // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and /// returns a new record built from the saved row. /// @@ -135,26 +134,31 @@ extension MutablePersistableRecord { /// nil, /// is used. /// - parameter returnedType: The type of the returned record. - /// - returns: A record of type `returnedType`. The result can be nil when - /// the conflict policy is `IGNORE`. + /// - returns: A record of type `returnedType`. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the database changes fail due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public mutating func saveAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, as returnedType: T.Type) - throws -> T? + throws -> T { try willSave(db) - var success: (saved: PersistenceSuccess, returned: T?)? + var success: (saved: PersistenceSuccess, returned: T)? try aroundSave(db) { + let record = self success = try updateOrInsertAndFetchWithCallbacks( db, onConflict: conflictResolution, selection: T.databaseSelection, fetch: { - try T.fetchOne($0) + if let result = try T.fetchOne($0) { + return result + } + throw record.recordNotFound(db) }) return success!.saved } @@ -211,7 +215,6 @@ extension MutablePersistableRecord { return success.returned } #else - // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and /// returns a new record built from the saved row. /// @@ -231,23 +234,23 @@ extension MutablePersistableRecord { /// - parameter conflictResolution: A policy for conflict resolution. If /// nil, /// is used. - /// - returns: The saved record. The result can be nil when the - /// conflict policy is `IGNORE`. + /// - returns: The saved record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the database changes fail due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func saveAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil) - throws -> Self? + throws -> Self where Self: FetchableRecord { var result = self return try result.saveAndFetch(db, onConflict: conflictResolution, as: Self.self) } - // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and /// returns a new record built from the saved row. /// @@ -260,27 +263,32 @@ extension MutablePersistableRecord { /// nil, /// is used. /// - parameter returnedType: The type of the returned record. - /// - returns: A record of type `returnedType`. The result can be nil when - /// the conflict policy is `IGNORE`. + /// - returns: A record of type `returnedType`. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the database changes fail due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func saveAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, as returnedType: T.Type) - throws -> T? + throws -> T { try willSave(db) - var success: (saved: PersistenceSuccess, returned: T?)? + var success: (saved: PersistenceSuccess, returned: T)? try aroundSave(db) { + let record = self success = try updateOrInsertAndFetchWithCallbacks( db, onConflict: conflictResolution, selection: T.databaseSelection, fetch: { - try T.fetchOne($0) + if let result = try T.fetchOne($0) { + return result + } + throw record.recordNotFound(db) }) return success!.saved } @@ -401,7 +409,7 @@ extension MutablePersistableRecord { let primaryKeyInfo = try db.primaryKey(databaseTableName) let container = try PersistenceContainer(db, self) let primaryKey = Dictionary(uniqueKeysWithValues: primaryKeyInfo.columns.map { - ($0, container[caseInsensitive: $0]?.databaseValue ?? .null) + ($0, container.databaseValue(at: $0)) }) if primaryKey.allSatisfy({ $0.value.isNull }) { return nil diff --git a/GRDB/Record/MutablePersistableRecord+Update.swift b/GRDB/Record/MutablePersistableRecord+Update.swift index 691d77d8d..89d81d817 100644 --- a/GRDB/Record/MutablePersistableRecord+Update.swift +++ b/GRDB/Record/MutablePersistableRecord+Update.swift @@ -41,13 +41,11 @@ extension MutablePersistableRecord { /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed - public func update( + public func update( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, - columns: Columns) - throws - where Columns: Sequence, Columns.Element == String - { + columns: some Collection + ) throws { try willSave(db) var updated: PersistenceSuccess? @@ -84,13 +82,11 @@ extension MutablePersistableRecord { /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. @inlinable // allow specialization so that empty callbacks are removed - public func update( + public func update( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, - columns: Columns) - throws - where Columns: Sequence, Columns.Element: ColumnExpression - { + columns: some Collection + ) throws { try update(db, onConflict: conflictResolution, columns: columns.map(\.name)) } @@ -218,7 +214,6 @@ extension MutablePersistableRecord { extension MutablePersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER - // TODO: GRDB7 make it unable to return an optional /// Executes an `UPDATE RETURNING` statement on all columns, and returns a /// new record built from the updated row. /// @@ -226,23 +221,23 @@ extension MutablePersistableRecord { /// - parameter conflictResolution: A policy for conflict resolution. If /// nil, /// is used. - /// - returns: The updated record. The result can be nil when the - /// conflict policy is `IGNORE`. + /// - returns: The updated record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type, /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the update fails due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil) - throws -> Self? + throws -> Self where Self: FetchableRecord { try updateAndFetch(db, onConflict: conflictResolution, as: Self.self) } - // TODO: GRDB7 make it unable to return an optional /// Executes an `UPDATE RETURNING` statement on all columns, and returns a /// new record built from the updated row. /// @@ -251,25 +246,28 @@ extension MutablePersistableRecord { /// nil, /// is used. /// - parameter returnedType: The type of the returned record. - /// - returns: A record of type `returnedType`. The result can be nil when - /// the conflict policy is `IGNORE`. + /// - returns: A record of type `returnedType`. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type, /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the update fails due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, as returnedType: T.Type) - throws -> T? + throws -> T { try updateAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { - try T.fetchOne($0) + if let result = try T.fetchOne($0) { + return result + } + throw recordNotFound(db) } } - // TODO: GRDB7 make it unable to return an optional /// Modifies the record according to the provided `modify` closure, and /// executes an `UPDATE RETURNING` statement that updates the modified /// columns, if and only if the record was modified. The method returns a @@ -280,12 +278,13 @@ extension MutablePersistableRecord { /// nil, /// is used. /// - parameter modify: A closure that modifies the record. - /// - returns: An updated record, or nil if the record has no change, or - /// in case of a failed update due to the `IGNORE` conflict policy. + /// - returns: An updated record, or nil if the record has no change. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type, /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the update fails due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public mutating func updateChangesAndFetch( _ db: Database, @@ -297,7 +296,6 @@ extension MutablePersistableRecord { try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify) } - // TODO: GRDB7 make it unable to return an optional /// Modifies the record according to the provided `modify` closure, and /// executes an `UPDATE RETURNING` statement that updates the modified /// columns, if and only if the record was modified. The method returns a @@ -310,12 +308,13 @@ extension MutablePersistableRecord { /// - parameter returnedType: The type of the returned record. /// - parameter modify: A closure that modifies the record. /// - returns: A record of type `returnedType`, or nil if the record has - /// no change, or in case of a failed update due to the `IGNORE` - /// conflict policy. + /// no change. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type, /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the update fails due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public mutating func updateChangesAndFetch( _ db: Database, @@ -324,10 +323,16 @@ extension MutablePersistableRecord { modify: (inout Self) throws -> Void) throws -> T? { - try updateChangesAndFetch( + let record = self + return try updateChangesAndFetch( db, onConflict: conflictResolution, selection: T.databaseSelection, - fetch: { try T.fetchOne($0) }, + fetch: { + if let result = try T.fetchOne($0) { + return result + } + throw record.recordNotFound(db) + }, modify: modify) } @@ -362,15 +367,13 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - public func updateAndFetch( + public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, - columns: Columns, + columns: some Collection, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) - throws -> T - where Columns: Sequence, Columns.Element == String - { + fetch: (Statement) throws -> T + ) throws -> T { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") try willSave(db) @@ -423,15 +426,13 @@ extension MutablePersistableRecord { /// primary key does not match any row in the database. /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed - public func updateAndFetch( + public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, - columns: Columns, + columns: some Collection, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) - throws -> T - where Columns: Sequence, Columns.Element: ColumnExpression - { + fetch: (Statement) throws -> T + ) throws -> T { try updateAndFetch( db, onConflict: conflictResolution, columns: columns.map(\.name), @@ -482,7 +483,6 @@ extension MutablePersistableRecord { fetch: fetch) } - // TODO: GRDB7 make it unable to return an optional /// Modifies the record according to the provided `modify` closure, and /// executes an `UPDATE RETURNING` statement that updates the modified /// columns, if and only if the record was modified. The method returns a @@ -495,7 +495,8 @@ extension MutablePersistableRecord { /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - parameter modify: A closure that modifies the record. - /// - returns: The result of the `fetch` function. + /// - returns: The result of the `fetch` function, or nil if the record + /// has no change. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type, /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the @@ -506,7 +507,7 @@ extension MutablePersistableRecord { _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T?, + fetch: (Statement) throws -> T, modify: (inout Self) throws -> Void) throws -> T? { @@ -519,7 +520,6 @@ extension MutablePersistableRecord { fetch: fetch) } #else - // TODO: GRDB7 make it unable to return an optional /// Executes an `UPDATE RETURNING` statement on all columns, and returns a /// new record built from the updated row. /// @@ -527,18 +527,19 @@ extension MutablePersistableRecord { /// - parameter conflictResolution: A policy for conflict resolution. If /// nil, /// is used. - /// - returns: The updated record. The result can be nil when the - /// conflict policy is `IGNORE`. + /// - returns: The updated record. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type, /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the update fails due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil) - throws -> Self? + throws -> Self where Self: FetchableRecord { try updateAndFetch(db, onConflict: conflictResolution, as: Self.self) @@ -552,26 +553,29 @@ extension MutablePersistableRecord { /// nil, /// is used. /// - parameter returnedType: The type of the returned record. - /// - returns: A record of type `returnedType`. The result can be nil when - /// the conflict policy is `IGNORE`. + /// - returns: A record of type `returnedType`. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type, /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the update fails due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, as returnedType: T.Type) - throws -> T? + throws -> T { try updateAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { - try T.fetchOne($0) + if let result = try T.fetchOne($0) { + return result + } + throw recordNotFound(db) } } - // TODO: GRDB7 make it unable to return an optional /// Modifies the record according to the provided `modify` closure, and /// executes an `UPDATE RETURNING` statement that updates the modified /// columns, if and only if the record was modified. The method returns a @@ -582,12 +586,13 @@ extension MutablePersistableRecord { /// nil, /// is used. /// - parameter modify: A closure that modifies the record. - /// - returns: An updated record, or nil if the record has no change, or - /// in case of a failed update due to the `IGNORE` conflict policy. + /// - returns: An updated record, or nil if the record has no change. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type, /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the update fails due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func updateChangesAndFetch( @@ -600,7 +605,6 @@ extension MutablePersistableRecord { try updateChangesAndFetch(db, onConflict: conflictResolution, as: Self.self, modify: modify) } - // TODO: GRDB7 make it unable to return an optional /// Modifies the record according to the provided `modify` closure, and /// executes an `UPDATE RETURNING` statement that updates the modified /// columns, if and only if the record was modified. The method returns a @@ -613,12 +617,13 @@ extension MutablePersistableRecord { /// - parameter returnedType: The type of the returned record. /// - parameter modify: A closure that modifies the record. /// - returns: A record of type `returnedType`, or nil if the record has - /// no change, or in case of a failed update due to the `IGNORE` - /// conflict policy. + /// no change. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type, /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the /// primary key does not match any row in the database. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the update fails due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public mutating func updateChangesAndFetch( @@ -628,10 +633,16 @@ extension MutablePersistableRecord { modify: (inout Self) throws -> Void) throws -> T? { - try updateChangesAndFetch( + let record = self + return try updateChangesAndFetch( db, onConflict: conflictResolution, selection: T.databaseSelection, - fetch: { try T.fetchOne($0) }, + fetch: { + if let result = try T.fetchOne($0) { + return result + } + throw record.recordNotFound(db) + }, modify: modify) } @@ -667,15 +678,13 @@ extension MutablePersistableRecord { /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func updateAndFetch( + public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, - columns: Columns, + columns: some Collection, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) - throws -> T - where Columns: Sequence, Columns.Element == String - { + fetch: (Statement) throws -> T + ) throws -> T { GRDBPrecondition(!selection.isEmpty, "Invalid empty selection") try willSave(db) @@ -729,15 +738,13 @@ extension MutablePersistableRecord { /// - precondition: `selection` is not empty. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ - public func updateAndFetch( + public func updateAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, - columns: Columns, + columns: some Collection, selection: [any SQLSelectable], - fetch: (Statement) throws -> T) - throws -> T - where Columns: Sequence, Columns.Element: ColumnExpression - { + fetch: (Statement) throws -> T + ) throws -> T { try updateAndFetch( db, onConflict: conflictResolution, columns: columns.map(\.name), @@ -789,7 +796,6 @@ extension MutablePersistableRecord { fetch: fetch) } - // TODO: GRDB7 make it unable to return an optional /// Modifies the record according to the provided `modify` closure, and /// executes an `UPDATE RETURNING` statement that updates the modified /// columns, if and only if the record was modified. The method returns a @@ -802,7 +808,8 @@ extension MutablePersistableRecord { /// - parameter selection: The returned columns (must not be empty). /// - parameter fetch: A function that executes it ``Statement`` argument. /// - parameter modify: A closure that modifies the record. - /// - returns: The result of the `fetch` function. + /// - returns: The result of the `fetch` function, or nil if the record + /// has no change. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type, /// or ``RecordError/recordNotFound(databaseTableName:key:)`` if the @@ -814,7 +821,7 @@ extension MutablePersistableRecord { _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, selection: [any SQLSelectable], - fetch: (Statement) throws -> T?, + fetch: (Statement) throws -> T, modify: (inout Self) throws -> Void) throws -> T? { @@ -839,7 +846,7 @@ extension MutablePersistableRecord { onConflict conflictResolution: Database.ConflictResolution?, from container: PersistenceContainer, selection: [any SQLSelectable], - fetch: (Statement) throws -> T?) + fetch: (Statement) throws -> T) throws -> T? { let changes = try PersistenceContainer(db, self).changesIterator(from: container) @@ -861,7 +868,7 @@ extension MutablePersistableRecord { onConflict conflictResolution: Database.ConflictResolution?, from container: PersistenceContainer, selection: [any SQLSelectable], - fetch: (Statement) throws -> T?) + fetch: (Statement) throws -> T) throws -> T? { let changes = try PersistenceContainer(db, self).changesIterator(from: container) diff --git a/GRDB/Record/MutablePersistableRecord+Upsert.swift b/GRDB/Record/MutablePersistableRecord+Upsert.swift index 4374c1960..335eea04e 100644 --- a/GRDB/Record/MutablePersistableRecord+Upsert.swift +++ b/GRDB/Record/MutablePersistableRecord+Upsert.swift @@ -47,6 +47,7 @@ extension MutablePersistableRecord { didSave(saved) } + // TODO: Make it possible to build assignments from $0.columnName /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and /// returns the upserted record. /// @@ -128,7 +129,7 @@ extension MutablePersistableRecord { public mutating func upsertAndFetch( _ db: Database, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self where Self: FetchableRecord { @@ -156,7 +157,7 @@ extension MutablePersistableRecord { _ db: Database, as returnedType: T.Type, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> T { try willSave(db) @@ -306,7 +307,7 @@ extension MutablePersistableRecord { public mutating func upsertAndFetch( _ db: Database, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self where Self: FetchableRecord { @@ -335,7 +336,7 @@ extension MutablePersistableRecord { _ db: Database, as returnedType: T.Type, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> T { try willSave(db) @@ -378,7 +379,7 @@ extension MutablePersistableRecord { mutating func upsertAndFetchWithCallbacks( _ db: Database, onConflict conflictTarget: [String], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, selection: [any SQLSelectable], decode: (Row) throws -> T) throws -> (InsertionSuccess, T) @@ -408,7 +409,7 @@ extension MutablePersistableRecord { func upsertAndFetchWithoutCallbacks( _ db: Database, onConflict conflictTarget: [String], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, selection: [any SQLSelectable], decode: (Row) throws -> T) throws -> (InsertionSuccess, T) @@ -452,7 +453,7 @@ extension MutablePersistableRecord { var persistenceContainer = dao.persistenceContainer let rowIDColumn = dao.primaryKey.rowIDColumn if let rowIDColumn { - persistenceContainer[caseInsensitive: rowIDColumn] = rowid + persistenceContainer[rowIDColumn] = rowid } let inserted = InsertionSuccess( diff --git a/GRDB/Record/MutablePersistableRecord.swift b/GRDB/Record/MutablePersistableRecord.swift index d26cb1cbc..2b7db54d1 100644 --- a/GRDB/Record/MutablePersistableRecord.swift +++ b/GRDB/Record/MutablePersistableRecord.swift @@ -61,6 +61,7 @@ /// - ``insertAndFetch(_:onConflict:)`` /// - ``insertAndFetch(_:onConflict:as:)`` /// - ``insertAndFetch(_:onConflict:selection:fetch:)`` +/// - ``insertAndFetch(_:onConflict:fetch:select:)`` /// - ``upsertAndFetch(_:onConflict:doUpdate:)`` /// - ``upsertAndFetch(_:as:onConflict:doUpdate:)`` /// @@ -69,8 +70,8 @@ /// See inherited ``TableRecord`` methods for batch updates. /// /// - ``update(_:onConflict:)`` -/// - ``update(_:onConflict:columns:)-4foo1`` -/// - ``update(_:onConflict:columns:)-5hxyx`` +/// - ``update(_:onConflict:columns:)-5qfk`` +/// - ``update(_:onConflict:columns:)-9fip4`` /// - ``updateChanges(_:onConflict:from:)`` /// - ``updateChanges(_:onConflict:modify:)`` /// @@ -78,8 +79,8 @@ /// /// - ``updateAndFetch(_:onConflict:)`` /// - ``updateAndFetch(_:onConflict:as:)`` -/// - ``updateAndFetch(_:onConflict:columns:selection:fetch:)-7s7y1`` -/// - ``updateAndFetch(_:onConflict:columns:selection:fetch:)-30d2v`` +/// - ``updateAndFetch(_:onConflict:columns:selection:fetch:)-98dtr`` +/// - ``updateAndFetch(_:onConflict:columns:selection:fetch:)-9npht`` /// - ``updateAndFetch(_:onConflict:selection:fetch:)`` /// - ``updateChangesAndFetch(_:onConflict:modify:)`` /// - ``updateChangesAndFetch(_:onConflict:as:modify:)`` @@ -193,6 +194,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// Default implementation does nothing. /// /// - parameter db: A database connection. + /// - parameter columns: The updated columns. func willUpdate(_ db: Database, columns: Set) throws /// Persistence callback called around the record update. @@ -253,7 +255,7 @@ public protocol MutablePersistableRecord: EncodableRecord, TableRecord { /// ``` /// /// - parameter db: A database connection. - /// - parameter update: A function that updates the record. Its result is + /// - parameter save: A function that saves the record. Its result is /// reserved for GRDB usage. func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws diff --git a/GRDB/Record/PersistableRecord+Insert.swift b/GRDB/Record/PersistableRecord+Insert.swift index b44f3f432..be7f5a9fe 100644 --- a/GRDB/Record/PersistableRecord+Insert.swift +++ b/GRDB/Record/PersistableRecord+Insert.swift @@ -56,7 +56,6 @@ extension PersistableRecord { extension PersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER - // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` statement, and returns a new record built /// from the inserted row. /// @@ -94,11 +93,10 @@ extension PersistableRecord { /// let partialPlayer = PartialPlayer(name: "Alice") /// /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * - /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { - /// print(player.id) // The inserted id - /// print(player.name) // The inserted name - /// print(player.score) // The default score - /// } + /// let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) + /// print(player.id) // The inserted id + /// print(player.name) // The inserted name + /// print(player.score) // The default score /// } /// ``` /// @@ -107,19 +105,23 @@ extension PersistableRecord { /// nil, /// is used. /// - parameter returnedType: The type of the returned record. - /// - returns: A record of type `returnedType`, if any. The result can be - /// nil when the conflict policy is `IGNORE`. + /// - returns: A record of type `returnedType`. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the insertion failed due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public func insertAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, as returnedType: T.Type) - throws -> T? + throws -> T { try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { - try T.fetchOne($0) + if let result = try T.fetchOne($0) { + return result + } + throw recordNotFound(db) } } @@ -198,8 +200,74 @@ extension PersistableRecord { didSave(PersistenceSuccess(success.inserted)) return success.returned } + + /// Executes an `INSERT RETURNING` statement, and returns the selected + /// columns from the inserted row. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// ```swift + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } + /// + /// // A player with partial database information + /// struct PartialPlayer: PersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// // Insert a partial player, get the inserted score + /// try dbQueue.write { db in + /// let partialPlayer = PartialPlayer(name: "Alice") + /// + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score + /// let score = try partialPlayer.insertAndFetch(db) { statement in + /// try Int.fetchOne(statement) + /// } select: { + /// [$0.score] + /// } + /// print(score) // The inserted score + /// } + /// ``` + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. + /// - parameter fetch: A closure that executes its ``Statement`` argument. + /// If the conflict policy is `IGNORE`, the statement may return no row. + /// - parameter select: A closure that returns the returned columns + /// (must not be empty). + /// - returns: The result of the `fetch` function. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. + /// - precondition: The result of `select` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + public func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + fetch: (Statement) throws -> T, + select: (DatabaseComponents) throws -> [any SQLSelectable] + ) throws -> T + where Self: TableRecord + { + try insertAndFetch(db, onConflict: conflictResolution, selection: select(Self.databaseComponents), fetch: fetch) + } #else - // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` statement, and returns a new record built /// from the inserted row. /// @@ -237,11 +305,10 @@ extension PersistableRecord { /// let partialPlayer = PartialPlayer(name: "Alice") /// /// // INSERT INTO player (name) VALUES ('Alice') RETURNING * - /// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) { - /// print(player.id) // The inserted id - /// print(player.name) // The inserted name - /// print(player.score) // The default score - /// } + /// let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) + /// print(player.id) // The inserted id + /// print(player.name) // The inserted name + /// print(player.score) // The default score /// } /// ``` /// @@ -250,20 +317,24 @@ extension PersistableRecord { /// nil, /// is used. /// - parameter returnedType: The type of the returned record. - /// - returns: A record of type `returnedType`, if any. The result can be - /// nil when the conflict policy is `IGNORE`. + /// - returns: A record of type `returnedType`. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the insertion failed due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func insertAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, as returnedType: T.Type) - throws -> T? + throws -> T { try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) { - try T.fetchOne($0) + if let result = try T.fetchOne($0) { + return result + } + throw recordNotFound(db) } } @@ -343,6 +414,78 @@ extension PersistableRecord { didSave(PersistenceSuccess(success.inserted)) return success.returned } + + /// Executes an `INSERT RETURNING` statement, and returns the selected + /// columns from the inserted row. + /// + /// This method helps dealing with default column values and + /// generated columns. + /// + /// For example: + /// + /// ```swift + /// // A table with an auto-incremented primary key and a default value + /// try dbQueue.write { db in + /// try db.execute(sql: """ + /// CREATE TABLE player( + /// id INTEGER PRIMARY KEY AUTOINCREMENT, + /// name TEXT, + /// score INTEGER DEFAULT 1000) + /// """) + /// } + /// + /// // A player with partial database information + /// struct PartialPlayer: PersistableRecord { + /// static let databaseTableName = "player" + /// var name: String + /// + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// // Insert a partial player, get the inserted score + /// try dbQueue.write { db in + /// let partialPlayer = PartialPlayer(name: "Alice") + /// + /// // INSERT INTO player (name) VALUES ('Alice') RETURNING score + /// let score = try partialPlayer.insertAndFetch(db) { statement in + /// try Int.fetchOne(statement) + /// } select: { + /// [$0.score] + /// } + /// print(score) // The inserted score + /// } + /// ``` + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution. If + /// nil, + /// is used. + /// - parameter fetch: A closure that executes its ``Statement`` argument. + /// If the conflict policy is `IGNORE`, the statement may return no row. + /// - parameter select: A closure that returns the returned columns + /// (must not be empty). + /// - returns: The result of the `fetch` function. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any + /// error thrown by the persistence callbacks defined by the record type. + /// - precondition: The result of `select` is not empty. + @inlinable // allow specialization so that empty callbacks are removed + @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ + public func insertAndFetch( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + fetch: (Statement) throws -> T, + select: (DatabaseComponents) throws -> [any SQLSelectable] + ) throws -> T + where Self: TableRecord + { + try insertAndFetch( + db, + onConflict: conflictResolution, + selection: select(Self.databaseComponents), + fetch: fetch) + } #endif } diff --git a/GRDB/Record/PersistableRecord+Save.swift b/GRDB/Record/PersistableRecord+Save.swift index 9ba55346b..80a9f3f81 100644 --- a/GRDB/Record/PersistableRecord+Save.swift +++ b/GRDB/Record/PersistableRecord+Save.swift @@ -39,7 +39,6 @@ extension PersistableRecord { extension PersistableRecord { #if GRDBCUSTOMSQLITE || GRDBCIPHER - // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and /// returns a new record built from the saved row. /// @@ -52,26 +51,30 @@ extension PersistableRecord { /// nil, /// is used. /// - parameter returnedType: The type of the returned record. - /// - returns: A record of type `returnedType`. The result can be nil when - /// the conflict policy is `IGNORE`. + /// - returns: A record of type `returnedType`. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the database changes fail due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed public func saveAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, as returnedType: T.Type) - throws -> T? + throws -> T { try willSave(db) - var success: (saved: PersistenceSuccess, returned: T?)? + var success: (saved: PersistenceSuccess, returned: T)? try aroundSave(db) { success = try updateOrInsertAndFetchWithCallbacks( db, onConflict: conflictResolution, selection: T.databaseSelection, fetch: { - try T.fetchOne($0) + if let result = try T.fetchOne($0) { + return result + } + throw recordNotFound(db) }) return success!.saved } @@ -128,7 +131,6 @@ extension PersistableRecord { return success.returned } #else - // TODO: GRDB7 make it unable to return an optional /// Executes an `INSERT RETURNING` or `UPDATE RETURNING` statement, and /// returns a new record built from the saved row. /// @@ -141,27 +143,31 @@ extension PersistableRecord { /// nil, /// is used. /// - parameter returnedType: The type of the returned record. - /// - returns: A record of type `returnedType`. The result can be nil when - /// the conflict policy is `IGNORE`. + /// - returns: A record of type `returnedType`. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any /// error thrown by the persistence callbacks defined by the record type. + /// ``RecordError/recordNotFound(databaseTableName:key:)`` can be + /// thrown if the database changes fail due to the IGNORE conflict policy. @inlinable // allow specialization so that empty callbacks are removed @available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+ public func saveAndFetch( _ db: Database, onConflict conflictResolution: Database.ConflictResolution? = nil, as returnedType: T.Type) - throws -> T? + throws -> T { try willSave(db) - var success: (saved: PersistenceSuccess, returned: T?)? + var success: (saved: PersistenceSuccess, returned: T)? try aroundSave(db) { success = try updateOrInsertAndFetchWithCallbacks( db, onConflict: conflictResolution, selection: T.databaseSelection, fetch: { - try T.fetchOne($0) + if let result = try T.fetchOne($0) { + return result + } + throw recordNotFound(db) }) return success!.saved } diff --git a/GRDB/Record/PersistableRecord+Upsert.swift b/GRDB/Record/PersistableRecord+Upsert.swift index af1a68807..fa7e42975 100644 --- a/GRDB/Record/PersistableRecord+Upsert.swift +++ b/GRDB/Record/PersistableRecord+Upsert.swift @@ -47,6 +47,7 @@ extension PersistableRecord { didSave(saved) } + // TODO: Make it possible to build assignments from $0.columnName /// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and /// returns the upserted record. /// @@ -128,7 +129,7 @@ extension PersistableRecord { public func upsertAndFetch( _ db: Database, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self where Self: FetchableRecord { @@ -156,7 +157,7 @@ extension PersistableRecord { _ db: Database, as returnedType: T.Type, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> T { try willSave(db) @@ -306,7 +307,7 @@ extension PersistableRecord { public func upsertAndFetch( _ db: Database, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> Self where Self: FetchableRecord { @@ -335,7 +336,7 @@ extension PersistableRecord { _ db: Database, as returnedType: T.Type, onConflict conflictTarget: [String] = [], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil) throws -> T { try willSave(db) @@ -378,7 +379,7 @@ extension PersistableRecord { func upsertAndFetchWithCallbacks( _ db: Database, onConflict conflictTarget: [String], - doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, + doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?, selection: [any SQLSelectable], decode: (Row) throws -> T) throws -> (InsertionSuccess, T) diff --git a/GRDB/Record/PersistableRecord.swift b/GRDB/Record/PersistableRecord.swift index d41535b5d..e769284ed 100644 --- a/GRDB/Record/PersistableRecord.swift +++ b/GRDB/Record/PersistableRecord.swift @@ -23,6 +23,7 @@ /// /// - ``insertAndFetch(_:onConflict:as:)`` /// - ``insertAndFetch(_:onConflict:selection:fetch:)`` +/// - ``insertAndFetch(_:onConflict:fetch:select:)`` /// - ``upsertAndFetch(_:onConflict:doUpdate:)`` /// - ``upsertAndFetch(_:as:onConflict:doUpdate:)`` /// diff --git a/GRDB/Record/Record.swift b/GRDB/Record/Record.swift index 47f37d742..443ddf728 100644 --- a/GRDB/Record/Record.swift +++ b/GRDB/Record/Record.swift @@ -2,6 +2,12 @@ /// A base class for types that can be fetched and persisted in the database. /// +/// ## Overview +/// +/// - warning: `Record` is a legacy GRDB type. Since GRDB 7, it is not +/// recommended to define record types by subclassing the `Record` class. +/// See for more information. +/// /// ## Topics /// /// ### Creating Record Instances @@ -101,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. @@ -201,8 +207,7 @@ open class Record { var newValueIterator = try PersistenceContainer(self).makeIterator() return AnyIterator { // Loop until we find a change, or exhaust columns: - while let (column, newValue) = newValueIterator.next() { - let newDbValue = newValue?.databaseValue ?? .null + while let (column, newDbValue) = newValueIterator.next() { guard let oldRow, let oldDbValue: DatabaseValue = oldRow[column] else { return (column, nil) } @@ -281,6 +286,7 @@ open class Record { /// your implementation. /// /// - parameter db: A database connection. + /// - parameter columns: The updated columns. open func willUpdate(_ db: Database, columns: Set) throws { } /// Called around the record update. @@ -348,7 +354,7 @@ open class Record { /// ``` /// /// - parameter db: A database connection. - /// - parameter update: A function that updates the record. Its result is + /// - parameter save: A function that saves the recordsave: A function that saves the record. Its result is /// reserved for GRDB usage. open func aroundSave(_ db: Database, save: () throws -> PersistenceSuccess) throws { _ = try save() @@ -431,3 +437,9 @@ open class Record { extension Record: TableRecord { } extension Record: PersistableRecord { } extension Record: FetchableRecord { } + +// Explicit non-conformance to Sendable, because persistence methods mutate +// the instance (`referenceRow`). Nothing prevents a single Record instance +// from being concurrencly persisted in two distinct database connections. +@available(*, unavailable) +extension Record: Sendable { } diff --git a/GRDB/Record/TableRecord.swift b/GRDB/Record/TableRecord.swift index 4e8d8b1b4..c3a98756b 100644 --- a/GRDB/Record/TableRecord.swift +++ b/GRDB/Record/TableRecord.swift @@ -29,6 +29,7 @@ import Foundation /// - ``exists(_:id:)`` /// - ``exists(_:key:)-60hf2`` /// - ``exists(_:key:)-6ha6`` +/// - ``recordNotFound(_:)`` /// /// ### Throwing Record Not Found Errors /// @@ -40,7 +41,7 @@ import Foundation /// /// - ``deleteAll(_:)`` /// - ``deleteAll(_:ids:)`` -/// - ``deleteAll(_:keys:)-jbkm`` +/// - ``deleteAll(_:keys:)-5l3ih`` /// - ``deleteAll(_:keys:)-5s1jg`` /// - ``deleteOne(_:id:)`` /// - ``deleteOne(_:key:)-413u8`` @@ -48,29 +49,29 @@ import Foundation /// /// ### Updating Records /// -/// - ``updateAll(_:onConflict:_:)-7vv9x`` -/// - ``updateAll(_:onConflict:_:)-7atfw`` +/// - ``updateAll(_:onConflict:assignment:)`` +/// - ``updateAll(_:onConflict:assignments:)`` /// /// ### Building Query Interface Requests /// /// `TableRecord` provide convenience access to most ``DerivableRequest`` and /// ``QueryInterfaceRequest`` methods as static methods on the type itself. /// -/// - ``aliased(_:)`` +/// - ``aliased(_:)-sdcd`` /// - ``all()`` -/// - ``annotated(with:)-3zi1n`` /// - ``annotated(with:)-4xoen`` /// - ``annotated(with:)-8ce7u`` -/// - ``annotated(with:)-79389`` +/// - ``annotated(with:)-58am5`` +/// - ``annotated(with:)-12jwq`` /// - ``annotated(withOptional:)`` /// - ``annotated(withRequired:)`` -/// - ``filter(_:)`` +/// - ``filter(_:)-4xvdh`` /// - ``filter(id:)`` /// - ``filter(ids:)`` /// - ``filter(key:)-9ey53`` /// - ``filter(key:)-34lau`` /// - ``filter(keys:)-4hq8y`` -/// - ``filter(keys:)-7skw1`` +/// - ``filter(keys:)-s1q0`` /// - ``filter(literal:)`` /// - ``filter(sql:arguments:)`` /// - ``having(_:)`` @@ -83,22 +84,25 @@ import Foundation /// - ``matching(_:)-22m4o`` /// - ``matching(_:)-1t8ph`` /// - ``none()`` -/// - ``order(_:)-9rc11`` -/// - ``order(_:)-2033k`` +/// - ``order(_:)-4j3ej`` +/// - ``order(_:)-53dja`` /// - ``order(literal:)`` /// - ``order(sql:arguments:)`` /// - ``orderByPrimaryKey()`` /// - ``request(for:)`` -/// - ``select(_:)-1gvtj`` -/// - ``select(_:)-5oylt`` -/// - ``select(_:as:)-1puz3`` -/// - ``select(_:as:)-tjh0`` +/// - ``select(_:)-1bgd1`` +/// - ``select(_:)-8yqls`` +/// - ``select(_:as:)-7zz91`` /// - ``select(literal:)`` /// - ``select(literal:as:)`` /// - ``select(sql:arguments:)`` /// - ``select(sql:arguments:as:)`` +/// - ``selectID()`` /// - ``selectPrimaryKey(as:)`` /// - ``with(_:)`` +/// - ``databaseComponents`` +/// - ``Columns`` +/// - ``DatabaseComponents`` /// /// ### Defining Associations /// @@ -112,7 +116,87 @@ import Foundation /// - ``hasOne(_:key:using:)-4g9tm`` /// - ``hasOne(_:key:using:)-4v5xa`` /// - ``hasOne(_:through:using:key:)`` +/// +/// ### Legacy APIs +/// +/// It is recommended to prefer the closure-based apis defined above, as +/// well as record aliases over anonymous aliases. +/// +/// - ``aliased(_:)-py77`` +/// - ``annotated(with:)-3zi1n`` +/// - ``annotated(with:)-79389`` +/// - ``filter(_:)-5u85w`` +/// - ``order(_:)-9rc11`` +/// - ``order(_:)-2033k`` +/// - ``select(_:)-1gvtj`` +/// - ``select(_:)-5oylt`` +/// - ``select(_:as:)-1puz3`` +/// - ``select(_:as:)-tjh0`` +/// - ``updateAll(_:onConflict:_:)-7vv9x`` +/// - ``updateAll(_:onConflict:_:)-7atfw`` public protocol TableRecord { + /// A type that defines columns. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// var id: Int64 + /// var name: String + /// var score: Int + /// + /// enum Columns { + /// static let id = Column("id") + /// static let name = Column("name") + /// static let score = Column("score") + /// } + /// } + /// ``` + /// + /// `Codable` types can define their columns from their coding keys: + /// + /// ```swift + /// struct Player: TableRecord, Codable { + /// var id: Int64 + /// var name: String + /// var score: Int + /// + /// enum Columns { + /// static let id = Column(CodingKeys.id) + /// static let name = Column(CodingKeys.name) + /// static let score = Column(CodingKeys.score) + /// } + /// } + /// ``` + associatedtype Columns = Never + + /// A type that provides database components to the query interface. + /// + /// By default, it is `Columns.Type`. This default definition might + /// change in future GRDB versions. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord, Codable { + /// var id: Int64 + /// var name: String + /// var score: Int + /// + /// enum Columns { + /// static let id = Column(CodingKeys.id) + /// static let name = Column(CodingKeys.name) + /// static let score = Column(CodingKeys.score) + /// } + /// } + /// + /// Player.DatabaseComponents // Player.Columns.Type by default + /// Player.databaseComponents // Instance of Player.DatabaseComponents + /// Player.databaseComponents.score // A Column + /// let request = Player.order(\.score.desc) + /// ``` + associatedtype DatabaseComponents = Columns.Type + /// The name of the database table used to build SQL queries. /// /// For example: @@ -133,15 +217,28 @@ public protocol TableRecord { /// /// ```swift /// struct Player: TableRecord { - /// static let databaseSelection: [any SQLSelectable] = [AllColumns()] + /// // This is the default + /// static var databaseSelection: [any SQLSelectable] { + /// [.allColumns] + /// } /// } /// /// struct PartialPlayer: TableRecord { /// static let databaseTableName = "player" - /// static let databaseSelection: [any SQLSelectable] = [ - /// Column("id"), - /// Column("name"), - /// ] + /// static var databaseSelection: [any SQLSelectable] { + /// [Columns.id, Columns.name] + /// } + /// + /// enum Columns { + /// static let id = Column("id") + /// static let name = Column("name") + /// } + /// } + /// + /// struct Team: TableRecord { + /// static var databaseSelection: [any SQLSelectable] { + /// [.allColumns(excluding: ["generatedColumn"])] + /// } /// } /// /// // SELECT * FROM player @@ -149,13 +246,54 @@ public protocol TableRecord { /// /// // 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 /// > explicitly declared as `[any SQLSelectable]`. If it is not, the /// > Swift compiler may silently miss the protocol requirement, /// > resulting in sticky `SELECT *` requests. + /// + /// > Important: Make sure the property is declared as a computed + /// > property (`static var`), instead of a stored property + /// > (`static let`). Computed properties avoid a compiler diagnostic + /// > with stored properties: + /// > + /// > ```swift + /// > // static property 'databaseSelection' is not + /// > // concurrency-safe because non-'Sendable' type + /// > // '[any SQLSelectable]' may have shared + /// > // mutable state. + /// > static let databaseSelection: [any SQLSelectable] = [.allColumns] + /// > ``` static var databaseSelection: [any SQLSelectable] { get } + + /// The value that provides database components to the query interface. + /// + /// By default, it is `Columns.self`. This default definition might + /// change in future GRDB versions. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord, Codable { + /// var id: Int64 + /// var name: String + /// var score: Int + /// + /// enum Columns { + /// static let id = Column(CodingKeys.id) + /// static let name = Column(CodingKeys.name) + /// static let score = Column(CodingKeys.score) + /// } + /// } + /// + /// Player.databaseComponents.score // A Column + /// let request = Player.order(\.score.desc) + /// ``` + static var databaseComponents: DatabaseComponents { get } } extension TableRecord { @@ -200,9 +338,15 @@ 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] + } +} + +extension TableRecord where DatabaseComponents == Columns.Type { + public static var databaseComponents: DatabaseComponents { + Columns.self } } @@ -242,7 +386,14 @@ extension TableRecord { /// /// struct PartialPlayer: TableRecord { /// static let databaseTableName = "player" - /// static let databaseSelection = [Column("id"), Column("name")] + /// static var databaseSelection: [any SQLSelectable] { + /// [Columns.id, Columns.name] + /// } + /// + /// enum Columns { + /// static let id = Column("id") + /// static let name = Column("name") + /// } /// } /// /// try dbQueue.write { db in @@ -318,7 +469,6 @@ extension TableRecord { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// Returns whether a record exists for this primary key. /// @@ -410,11 +560,10 @@ extension TableRecord { /// - keys: A sequence of primary keys. /// - returns: The number of deleted records. @discardableResult - public static func deleteAll(_ db: Database, keys: Keys) - throws -> Int - where Keys: Sequence, Keys.Element: DatabaseValueConvertible - { - let keys = Array(keys) + public static func deleteAll( + _ db: Database, + keys: some Collection + ) throws -> Int { if keys.isEmpty { // Avoid hitting the database return 0 @@ -454,7 +603,6 @@ extension TableRecord { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// Deletes records identified by their primary keys, and returns the number /// of deleted records. @@ -483,9 +631,10 @@ extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// - ids: A collection of primary keys. /// - returns: The number of deleted records. @discardableResult - public static func deleteAll(_ db: Database, ids: IDS) throws -> Int - where IDS: Collection, IDS.Element == ID - { + public static func deleteAll( + _ db: Database, + ids: some Collection + ) throws -> Int { if ids.isEmpty { // Avoid hitting the database return 0 @@ -606,6 +755,70 @@ extension TableRecord { // MARK: - Batch Update extension TableRecord { + /// Updates all records, and returns the number of updated records. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Player.updateAll(db) { $0.score.set(to: 0) } + /// } + /// ``` + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution, + /// defaulting to the record's persistenceConflictPolicy. + /// - parameter assignments: A closure that returns an array of + /// column assignments. + /// - returns: The number of updated records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + @discardableResult + public static func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignments: (DatabaseComponents) throws -> [ColumnAssignment] + ) throws -> Int { + try updateAll(db, onConflict: conflictResolution, assignments(databaseComponents)) + } + + /// Updates all records, and returns the number of updated records. + /// + /// For example: + /// + /// ```swift + /// struct Player: TableRecord { + /// enum Columns { + /// static let score = Column("score") + /// } + /// } + /// + /// try dbQueue.write { db in + /// // UPDATE player SET score = 0 + /// try Player.updateAll(db) { $0.score.set(to: 0) } + /// } + /// ``` + /// + /// - parameter db: A database connection. + /// - parameter conflictResolution: A policy for conflict resolution, + /// defaulting to the record's persistenceConflictPolicy. + /// - parameter assignment: A closure that returns an assignment. + /// - returns: The number of updated records. + /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. + @discardableResult + public static func updateAll( + _ db: Database, + onConflict conflictResolution: Database.ConflictResolution? = nil, + assignment: (DatabaseComponents) throws -> ColumnAssignment + ) throws -> Int { + try updateAll(db, onConflict: conflictResolution, [assignment(databaseComponents)]) + } /// Updates all records, and returns the number of updated records. /// @@ -697,6 +910,15 @@ extension TableRecord { public enum RecordError: Error { /// A record does not exist in the database. /// + /// This error can be thrown from methods that update, such as + /// ``MutablePersistableRecord/update(_:onConflict:)``. In this case, + /// the error means that the database was not changed. + /// + /// It can also be thrown from methods that inserts or update with a + /// `RETURNING` clause, and the `IGNORE` conflict policy. In this case, + /// the error notifies that a conflict has prevented the change from + /// being applied. + /// /// - parameters: /// - databaseTableName: The table of the missing record. /// - key: The key of the missing record (column and values). @@ -720,13 +942,10 @@ extension TableRecord { /// any error that prevented the `RecordError` from being constructed. public static func recordNotFound(_ db: Database, key: some DatabaseValueConvertible) -> any Error { do { - let primaryKey = try db.primaryKey(databaseTableName) - GRDBPrecondition( - primaryKey.columns.count == 1, - "Requesting by key requires a single-column primary key in the table \(databaseTableName)") + let column = try db.filteringPrimaryKeyColumn(databaseTableName) return RecordError.recordNotFound( databaseTableName: databaseTableName, - key: [primaryKey.columns[0]: key.databaseValue]) + key: [column: key.databaseValue]) } catch { return error } @@ -740,7 +959,30 @@ extension TableRecord { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) +extension TableRecord where Self: EncodableRecord { + /// Returns an error that tells that the record does not exist in + /// the database. + /// + /// - returns: ``RecordError/recordNotFound(databaseTableName:key:)``, or + /// any error that prevented the `RecordError` from being constructed. + public func recordNotFound(_ db: Database) -> any Error { + do { + let databaseTableName = type(of: self).databaseTableName + let primaryKey = try db.primaryKey(databaseTableName) + + let container = try PersistenceContainer(db, self) + let key = Dictionary(uniqueKeysWithValues: primaryKey.columns.map { + ($0, container.databaseValue(at: $0)) + }) + return RecordError.recordNotFound( + databaseTableName: databaseTableName, + key: key) + } catch { + return error + } + } +} + extension TableRecord where Self: Identifiable, ID: DatabaseValueConvertible { /// Returns an error for a record that does not exist in the database. /// @@ -757,4 +999,10 @@ public typealias PersistenceError = RecordError /// Calculating `defaultDatabaseTableName` is somewhat expensive due to the regular expression evaluation /// /// This cache mitigates the cost of the calculation by storing the name for later retrieval -private let defaultDatabaseTableNameCache = NSCache() +/// +/// Assume this non-Sendable cache of strings can be used from multiple +/// threads concurrently, because the NSCache documentation says: +/// +/// > You can add, remove, and query items in the cache from different +/// > threads without having to lock the cache yourself. +nonisolated(unsafe) private let defaultDatabaseTableNameCache = NSCache() diff --git a/GRDB/Utils/CaseInsensitiveIdentifier.swift b/GRDB/Utils/CaseInsensitiveIdentifier.swift index f1fd12c5d..9e80a36e2 100644 --- a/GRDB/Utils/CaseInsensitiveIdentifier.swift +++ b/GRDB/Utils/CaseInsensitiveIdentifier.swift @@ -1,5 +1,5 @@ /// A case-preserving, case-insensitive identifier -/// that matches the ASCII version of sqlite3_stricmp +/// that intends to match the ASCII version of sqlite3_stricmp. struct CaseInsensitiveIdentifier: Hashable { private let lowercased: String let rawValue: String diff --git a/GRDB/Utils/Inflections+English.swift b/GRDB/Utils/Inflections+English.swift index 58338ec4f..46fba00c7 100644 --- a/GRDB/Utils/Inflections+English.swift +++ b/GRDB/Utils/Inflections+English.swift @@ -43,8 +43,12 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. extension Inflections { - /// The default inflections - public static var `default`: Inflections = { + /// The default inflections. + /// + /// This global variable is not concurrency-safe. If you modify the + /// default inflections, do it once, early in the lifetime of your + /// application, before you access query interface methods. + nonisolated(unsafe) public static var `default`: Inflections = { // Defines the standard inflection rules. These are the starting point // for new projects and are not considered complete. The current set of // inflection rules is frozen. This means, we do not change them to @@ -59,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") @@ -98,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", diff --git a/GRDB/Utils/LockedBox.swift b/GRDB/Utils/LockedBox.swift deleted file mode 100644 index aef512604..000000000 --- a/GRDB/Utils/LockedBox.swift +++ /dev/null @@ -1,72 +0,0 @@ -import Foundation - -/// A LockedBox protects a value with an NSLock. -@propertyWrapper -final class LockedBox { - private var _wrappedValue: T - private var lock = NSLock() - - var wrappedValue: T { - get { read { $0 } } - set { update { $0 = newValue } } - } - - var projectedValue: LockedBox { self } - - init(wrappedValue: T) { - _wrappedValue = wrappedValue - } - - /// Runs the provided closure while holding a lock on the value. - /// - /// For example: - /// - /// // Prints "0" - /// @LockedBox var count = 0 - /// $count.read { print($0) } - /// - /// - parameter block: A closure that accepts the value. - @inline(__always) - @usableFromInline - func read(_ block: (T) throws -> U) rethrows -> U { - lock.lock() - defer { lock.unlock() } - return try block(_wrappedValue) - } - - /// Runs the provided closure while holding a lock on the value. - /// - /// For example: - /// - /// // Prints "1" - /// @LockedBox var count = 0 - /// $count.update { $0 += 1 } - /// print(count) - /// - /// - parameter block: A closure that can modify the value. - func update(_ block: (inout T) throws -> U) rethrows -> U { - lock.lock() - defer { lock.unlock() } - return try block(&_wrappedValue) - } -} - -extension LockedBox where T: Numeric { - @discardableResult - func increment() -> T { - update { n in - n += 1 - return n - } - } - - @discardableResult - func decrement() -> T { - update { n in - n -= 1 - return n - } - } -} - -extension LockedBox: @unchecked Sendable where T: Sendable { } diff --git a/GRDB/Utils/Mutex.swift b/GRDB/Utils/Mutex.swift new file mode 100644 index 000000000..771a57a4a --- /dev/null +++ b/GRDB/Utils/Mutex.swift @@ -0,0 +1,83 @@ +import Foundation + +/// A Mutex protects a value with an NSLock. +/// +/// We'll replace it with the SE-0433 Mutex when it is available. +/// +final class Mutex { + private var _value: T + private var lock = NSLock() + + init(_ value: T) { + _value = value + } + + /// Runs the provided closure while holding a lock on the value. + /// + /// - parameter body: A closure that can modify the value. + func withLock(_ body: (inout T) throws -> U) rethrows -> U { + lock.lock() + defer { lock.unlock() } + return try body(&_value) + } +} + +// Inspired by +extension Mutex { + func load() -> T { + withLock { $0 } + } + + func store(_ value: T) { + withLock { $0 = value } + } +} + +extension Mutex where T: Numeric { + @discardableResult + func increment() -> T { + withLock { n in + n += 1 + return n + } + } + + @discardableResult + func decrement() -> T { + withLock { n in + n -= 1 + return n + } + } +} + +extension Mutex: @unchecked Sendable where T: Sendable { } + +// MARK: - UnsafeSendableMutex + +/// `UnsafeSendableMutex` is a Mutex that is always Sendable. It is unsafe, +/// because it does not guarantee that its value won't escape from the +/// critical section. +/// +/// We'll replace it with the SE-0433 Mutex when it is available. +/// +/// +/// For a longer discussion about Sendable and mutexes, see +/// +final class UnsafeSendableMutex: @unchecked Sendable { + private var _value: T + private var lock = NSLock() + + init(_ value: sending T) { + _value = value + } + + /// Runs the provided closure while holding a lock on the value. + /// + /// - parameter body: A closure that can modify the value. + func withLock(_ body: (inout T) throws -> U) rethrows -> U { + lock.lock() + defer { lock.unlock() } + return try body(&_value) + } +} diff --git a/GRDB/Utils/OnDemandFuture.swift b/GRDB/Utils/OnDemandFuture.swift index 6826014a4..938750d4a 100644 --- a/GRDB/Utils/OnDemandFuture.swift +++ b/GRDB/Utils/OnDemandFuture.swift @@ -14,14 +14,16 @@ import Foundation /// Both two extra scheduling guarantees are used by GRDB in order to be /// able to spawn concurrent database reads right from the database writer /// queue, and fulfill GRDB preconditions. -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) +/// +/// OnDemandFuture also adds Sendable requirements that avoid +/// compiler warnings. struct OnDemandFuture: Publisher { - typealias Promise = (Result) -> Void + typealias Promise = @Sendable (Result) -> Void typealias Output = Output typealias Failure = Failure - fileprivate let attemptToFulfill: (@escaping Promise) -> Void + fileprivate let attemptToFulfill: @Sendable (@escaping Promise) -> Void - init(_ attemptToFulfill: @escaping (@escaping Promise) -> Void) { + init(_ attemptToFulfill: @escaping @Sendable (@escaping Promise) -> Void) { self.attemptToFulfill = attemptToFulfill } @@ -33,9 +35,9 @@ struct OnDemandFuture: Publisher { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) -private class OnDemandFutureSubscription: Subscription { - typealias Promise = (Result) -> Void +private class OnDemandFutureSubscription: Subscription, @unchecked Sendable { + // @unchecked because `state` is protected with `lock`. + typealias Promise = @Sendable (Result) -> Void private enum State { case waitingForDemand(downstream: Downstream, attemptToFulfill: (@escaping Promise) -> Void) @@ -47,7 +49,7 @@ private class OnDemandFutureSubscription: Subscription { private let lock = NSRecursiveLock() // Allow re-entrancy init( - attemptToFulfill: @escaping (@escaping Promise) -> Void, + attemptToFulfill: @escaping @Sendable (@escaping Promise) -> Void, downstream: Downstream) { self.state = .waitingForDemand(downstream: downstream, attemptToFulfill: attemptToFulfill) diff --git a/GRDB/Utils/OrderedDictionary.swift b/GRDB/Utils/OrderedDictionary.swift index 4f7d5242b..ad40174e6 100644 --- a/GRDB/Utils/OrderedDictionary.swift +++ b/GRDB/Utils/OrderedDictionary.swift @@ -114,12 +114,10 @@ struct OrderedDictionary { return OrderedDictionary(keys: keys, dictionary: dictionary) } - mutating func merge( - _ other: S, - uniquingKeysWith combine: (Value, Value) throws -> Value) - rethrows - where S: Sequence, S.Element == (Key, Value) - { + mutating func merge( + _ other: some Sequence<(Key, Value)>, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows { for (key, value) in other { if let current = self[key] { self[key] = try combine(current, value) @@ -129,12 +127,10 @@ struct OrderedDictionary { } } - mutating func merge( - _ other: S, - uniquingKeysWith combine: (Value, Value) throws -> Value) - rethrows - where S: Sequence, S.Element == (key: Key, value: Value) - { + mutating func merge( + _ other: some Sequence<(key: Key, value: Value)>, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows { for (key, value) in other { if let current = self[key] { self[key] = try combine(current, value) @@ -144,23 +140,19 @@ struct OrderedDictionary { } } - func merging( - _ other: S, - uniquingKeysWith combine: (Value, Value) throws -> Value) - rethrows -> OrderedDictionary - where S: Sequence, S.Element == (Key, Value) - { + func merging( + _ other: some Sequence<(Key, Value)>, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows -> OrderedDictionary { var result = self try result.merge(other, uniquingKeysWith: combine) return result } - func merging( - _ other: S, - uniquingKeysWith combine: (Value, Value) throws -> Value) - rethrows -> OrderedDictionary - where S: Sequence, S.Element == (key: Key, value: Value) - { + func merging( + _ other: some Sequence<(key: Key, value: Value)>, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows -> OrderedDictionary { var result = self try result.merge(other, uniquingKeysWith: combine) return result @@ -207,6 +199,8 @@ extension OrderedDictionary: CustomStringConvertible { } } +extension OrderedDictionary: Sendable where Key: Sendable, Value: Sendable { } + extension Dictionary { init(_ orderedDictionary: OrderedDictionary) { self = orderedDictionary.dictionary diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index 6e1014c75..661c9c4d9 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -35,8 +35,9 @@ import Dispatch /// got 2 /// got 1 /// got 3 -final class Pool { - private class Item { +final class Pool: Sendable { + private class Item: @unchecked Sendable { + // @unchecked Sendable because `isAvailable` is protected by `contentLock`. let element: T var isAvailable: Bool @@ -46,8 +47,19 @@ final class Pool { } } - private let makeElement: () throws -> T - @ReadWriteBox private var items: [Item] = [] + private struct Content { + var items: [Item] + + /// The number of created items. May become greater than the number + /// of elements in items, as some items are destroyed and other + /// are created. + var createdCount = 0 + } + + typealias ElementAndRelease = (element: T, release: @Sendable (PoolCompletion) -> Void) + + private let makeElement: @Sendable (Int) throws -> T + private let contentLock = ReadWriteLock(Content(items: [], createdCount: 0)) private let itemsSemaphore: DispatchSemaphore // limits the number of elements private let itemsGroup: DispatchGroup // knows when no element is used private let barrierQueue: DispatchQueue @@ -59,11 +71,12 @@ final class Pool { /// - maximumCount: The maximum number of elements. /// - qos: The quality of service of asynchronous accesses. /// - makeElement: A function that creates an element. It is called - /// on demand. + /// on demand. Its argument is the index of the created elements + /// (1, then 2, etc). init( maximumCount: Int, qos: DispatchQoS = .unspecified, - makeElement: @escaping () throws -> T) + makeElement: @escaping @Sendable (_ index: Int) throws -> T) { GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1") self.makeElement = makeElement @@ -75,19 +88,20 @@ final class Pool { /// Returns a tuple (element, release) /// Client must call release(), only once, after the element has been used. - func get() throws -> (element: T, release: (PoolCompletion) -> Void) { + func get() throws -> ElementAndRelease { try barrierQueue.sync { itemsSemaphore.wait() itemsGroup.enter() do { - let item = try $items.update { items -> Item in - if let item = items.first(where: \.isAvailable) { + let item = try contentLock.withLock { content -> Item in + if let item = content.items.first(where: \.isAvailable) { item.isAvailable = false return item } else { - let element = try makeElement() + content.createdCount += 1 + let element = try makeElement(content.createdCount) let item = Item(element: element, isAvailable: false) - items.append(item) + content.items.append(item) return item } } @@ -107,7 +121,7 @@ final class Pool { /// /// - important: The `execute` argument is executed in a serial dispatch /// queue, so make sure you use the element asynchronously. - func asyncGet(_ execute: @escaping (Result<(element: T, release: (PoolCompletion) -> Void), Error>) -> Void) { + func asyncGet(_ execute: @escaping @Sendable (Result) -> Void) { // Inspired by https://khanlou.com/2016/04/the-GCD-handbook/ // > We wait on the semaphore in the serial queue, which means that // > we’ll have at most one blocked thread when we reach maximum @@ -128,7 +142,7 @@ final class Pool { } private func release(_ item: Item, completion: PoolCompletion) { - $items.update { items in + contentLock.withLock { content in switch completion { case .reuse: // This is why Item is a class, not a struct: so that we can @@ -136,8 +150,8 @@ final class Pool { item.isAvailable = true case .discard: // Discard should be rare: perform lookup. - if let index = items.firstIndex(where: { $0 === item }) { - items.remove(at: index) + if let index = content.items.firstIndex(where: { $0 === item }) { + content.items.remove(at: index) } } } @@ -148,8 +162,8 @@ final class Pool { /// Performs a block on each pool element, available or not. /// The block is run is some arbitrary dispatch queue. func forEach(_ body: (T) throws -> Void) rethrows { - try $items.read { items in - for item in items { + try contentLock.read { content in + for item in content.items { try body(item.element) } } @@ -158,7 +172,7 @@ final class Pool { /// Removes all elements from the pool. /// Currently used elements won't be reused. func removeAll() { - items = [] + contentLock.withLock { $0.items.removeAll() } } /// Blocks until no element is used, and runs the `barrier` function before @@ -172,7 +186,7 @@ final class Pool { /// Asynchronously runs the `barrier` function when no element is used, and /// before any other element is dequeued. - func asyncBarrier(execute barrier: @escaping () -> Void) { + func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) { barrierQueue.async(flags: [.barrier]) { self.itemsGroup.wait() barrier() diff --git a/GRDB/Utils/ReadWriteBox.swift b/GRDB/Utils/ReadWriteBox.swift deleted file mode 100644 index 1037ef8b3..000000000 --- a/GRDB/Utils/ReadWriteBox.swift +++ /dev/null @@ -1,51 +0,0 @@ -import Dispatch - -/// A ReadWriteBox grants multiple readers and single-writer guarantees on a -/// value. It is backed by a concurrent DispatchQueue. -@propertyWrapper -final class ReadWriteBox { - private var _wrappedValue: T - private var queue: DispatchQueue - - var wrappedValue: T { - get { read { $0 } } - set { update { $0 = newValue } } - } - - var projectedValue: ReadWriteBox { self } - - init(wrappedValue: T) { - _wrappedValue = wrappedValue - queue = DispatchQueue(label: "GRDB.ReadWriteBox", attributes: [.concurrent]) - } - - func read(_ block: (T) throws -> U) rethrows -> U { - try queue.sync { - try block(_wrappedValue) - } - } - - func update(_ block: (inout T) throws -> U) rethrows -> U { - try queue.sync(flags: [.barrier]) { - try block(&_wrappedValue) - } - } -} - -extension ReadWriteBox where T: Numeric { - @discardableResult - func increment() -> T { - update { n in - n += 1 - return n - } - } - - @discardableResult - func decrement() -> T { - update { n in - n -= 1 - return n - } - } -} diff --git a/GRDB/Utils/ReadWriteLock.swift b/GRDB/Utils/ReadWriteLock.swift new file mode 100644 index 000000000..85f191efb --- /dev/null +++ b/GRDB/Utils/ReadWriteLock.swift @@ -0,0 +1,32 @@ +import Dispatch + +/// A ReadWriteLock grants multiple readers and single-writer guarantees on +/// a value. It is backed by a concurrent DispatchQueue. +final class ReadWriteLock { + private var _value: T + private var queue: DispatchQueue + + init(_ value: T) { + _value = value + queue = DispatchQueue(label: "GRDB.ReadWriteLock", attributes: [.concurrent]) + } + + /// Reads the value. + func read(_ body: (T) throws -> U) rethrows -> U { + try queue.sync { + try body(_value) + } + } + + /// Runs the provided closure while holding a lock on the value. + /// + /// - parameter body: A closure that can modify the value. + func withLock(_ body: (inout T) throws -> U) rethrows -> U { + try queue.sync(flags: [.barrier]) { + try body(&_value) + } + } +} + +// @unchecked because `_value` is protected by `queue` +extension ReadWriteLock: @unchecked Sendable where T: Sendable { } diff --git a/GRDB/Utils/ReceiveValuesOn.swift b/GRDB/Utils/ReceiveValuesOn.swift index abc688f78..2df87fc46 100644 --- a/GRDB/Utils/ReceiveValuesOn.swift +++ b/GRDB/Utils/ReceiveValuesOn.swift @@ -11,7 +11,6 @@ import Foundation /// This scheduling guarantee is used by GRDB in order to be able /// to make promises on the scheduling of database values without surprising /// the users as in . -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) struct ReceiveValuesOn: Publisher { typealias Output = Upstream.Output typealias Failure = Upstream.Failure @@ -30,7 +29,6 @@ struct ReceiveValuesOn: Publisher { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) private class ReceiveValuesOnSubscription: Subscription, Subscriber where Upstream: Publisher, @@ -211,7 +209,6 @@ where } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Publisher { /// Specifies the scheduler on which to receive values from the publisher /// diff --git a/GRDB/Utils/Utils.swift b/GRDB/Utils/Utils.swift index 90e3ca557..d690b9eec 100644 --- a/GRDB/Utils/Utils.swift +++ b/GRDB/Utils/Utils.swift @@ -1,3 +1,6 @@ +#if !canImport(Darwin) +@preconcurrency import Dispatch +#endif import Foundation // MARK: - Public @@ -67,8 +70,8 @@ extension Dictionary { } extension DispatchQueue { - private static var mainKey: DispatchSpecificKey<()> = { - let key = DispatchSpecificKey<()>() + private static let mainKey: DispatchSpecificKey = { + let key = DispatchSpecificKey() DispatchQueue.main.setSpecific(key: key, value: ()) return key }() @@ -118,14 +121,29 @@ func throwingFirstError(execute: () throws -> T, finally: () throws -> Void) return result! } -struct PrintOutputStream: TextOutputStream { +struct PrintOutputStream: TextOutputStream, Sendable { func write(_ string: String) { Swift.print(string) } } +/// A Sendable strong reference to an object. +/// +/// This type hides its retained object in order to provide the +/// Sendable guarantee. +final class StrongReference: @unchecked Sendable { + private let value: Value + + init(_ value: Value) { + self.value = value + } +} + /// Concatenates two functions -func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? { +func concat( + _ rhs: (@Sendable () -> Void)?, + _ lhs: (@Sendable () -> Void)? +) -> (@Sendable () -> Void)? { switch (rhs, lhs) { case let (rhs, nil): return rhs @@ -140,7 +158,10 @@ func concat(_ rhs: (() -> Void)?, _ lhs: (() -> Void)?) -> (() -> Void)? { } /// Concatenates two functions -func concat(_ rhs: ((T) -> Void)?, _ lhs: ((T) -> Void)?) -> ((T) -> Void)? { +func concat( + _ rhs: (@Sendable (T) -> Void)?, + _ lhs: (@Sendable (T) -> Void)? +) -> (@Sendable (T) -> Void)? { switch (rhs, lhs) { case let (rhs, nil): return rhs diff --git a/GRDB/ValueObservation/DatabaseCancellable.swift b/GRDB/ValueObservation/DatabaseCancellable.swift index de6298791..fc904892f 100644 --- a/GRDB/ValueObservation/DatabaseCancellable.swift +++ b/GRDB/ValueObservation/DatabaseCancellable.swift @@ -5,7 +5,7 @@ /// ### Supporting Types /// /// - ``AnyDatabaseCancellable`` -public protocol DatabaseCancellable { +public protocol DatabaseCancellable: Sendable { /// Cancel the activity. func cancel() } @@ -15,31 +15,39 @@ public protocol DatabaseCancellable { /// /// An `AnyDatabaseCancellable` instance automatically calls ``cancel()`` /// when deinitialized. -public class AnyDatabaseCancellable: DatabaseCancellable { - private var _cancel: (() -> Void)? +public final class AnyDatabaseCancellable: DatabaseCancellable { + private let cancelMutex: Mutex<(@Sendable () -> Void)?> + + var isCancelled: Bool { + cancelMutex.withLock { $0 == nil } + } + + convenience init() { + self.init(cancel: { }) + } /// Initializes the cancellable object with the given cancel-time closure. - public init(cancel: @escaping () -> Void) { - _cancel = cancel + public init(cancel: @escaping @Sendable () -> Void) { + cancelMutex = Mutex(cancel) } /// Creates a cancellable object that forwards cancellation to `base`. public convenience init(_ base: some DatabaseCancellable) { - var cancellable = Optional.some(base) self.init { - cancellable?.cancel() - cancellable = nil // Release memory + base.cancel() } } deinit { - _cancel?() + cancel() } public func cancel() { - // Don't prevent multiple concurrent calls to _cancel, because it is - // pointless. But release memory! - _cancel?() - _cancel = nil + let cancel = cancelMutex.withLock { + let cancel = $0 + $0 = nil + return cancel + } + cancel?() } } diff --git a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift index a287a3767..9cc507ddf 100644 --- a/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueConcurrentObserver.swift @@ -18,7 +18,10 @@ import Foundation /// reducing stage. /// /// **Notify** is calling user callbacks, in case of database change or error. -final class ValueConcurrentObserver { +final class ValueConcurrentObserver: @unchecked Sendable +where Reducer: ValueReducer, + Scheduler: ValueObservationScheduler +{ // MARK: - Configuration // // Configuration is not mutable. @@ -76,25 +79,25 @@ final class ValueConcurrentObserver Reducer.Fetched { + func fetch(_ db: Database) throws -> Reducer.Fetcher.Value { try db.isolated(readOnly: true) { - try reducer._fetch(db) + try fetcher.fetch(db) } } - func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetched, DatabaseRegion) { + func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetcher.Value, DatabaseRegion) { var region = DatabaseRegion() let fetchedValue = try db.isolated(readOnly: true) { try db.recordingSelection(®ion) { - try reducer._fetch(db) + try fetcher.fetch(db) } } return try (fetchedValue, region.observableRegion(db)) @@ -146,7 +149,7 @@ final class ValueConcurrentObserver Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) { // Configuration self.scheduler = scheduler @@ -170,9 +173,9 @@ final class ValueConcurrentObserver=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) extension ValueConcurrentObserver { /// Synchronously starts the observation, and returns the initial value. /// @@ -299,7 +301,9 @@ extension ValueConcurrentObserver { return try syncStartWithoutWALSnapshot(from: databaseAccess) } - let (fetchedValue, initialRegion): (Reducer.Fetched, DatabaseRegion) = try initialFetchTransaction.read { db in + let fetchedValue: Reducer.Fetcher.Value + let initialRegion: DatabaseRegion + (fetchedValue, initialRegion) = try initialFetchTransaction.read { db in switch trackingMode { case let .constantRegion(regions): let fetchedValue = try databaseAccess.fetch(db) @@ -353,10 +357,12 @@ extension ValueConcurrentObserver { let initialFetchTransaction = try result.get() // Second async jump because that's how // `DatabasePool.asyncWALSnapshotTransaction` has to be used. - initialFetchTransaction.asyncRead { db in + initialFetchTransaction.asyncRead { dbResult in do { - let fetchedValue: Reducer.Fetched + // Assume this value can safely be sent to the reduce queue. + nonisolated(unsafe) let fetchedValue: Reducer.Fetcher.Value let initialRegion: DatabaseRegion + let db = try dbResult.get() switch self.trackingMode { case let .constantRegion(regions): @@ -430,11 +436,9 @@ extension ValueConcurrentObserver { // checkpointed. That's why we'll keep `initialFetchTransaction` // alive until the comparison is done. // - // However, we want to release `initialFetchTransaction` as soon as + // However, we want to close `initialFetchTransaction` as soon as // possible, so that the reader connection it holds becomes - // available for other reads. It will be released when this optional - // is set to nil: - var initialFetchTransaction: WALSnapshotTransaction? = initialFetchTransaction + // available for other reads. databaseAccess.dbPool.asyncWriteWithoutTransaction { writerDB in let events = self.lock.synchronized { self.notificationCallbacks?.events } @@ -447,7 +451,7 @@ extension ValueConcurrentObserver { // Was the database modified since the initial fetch? let isModified: Bool if let currentWALSnapshot = try? WALSnapshot(writerDB) { - let ordering = initialFetchTransaction!.walSnapshot.compare(currentWALSnapshot) + let ordering = initialFetchTransaction.walSnapshot.compare(currentWALSnapshot) assert(ordering <= 0, "Unexpected snapshot ordering") isModified = ordering < 0 } else { @@ -455,15 +459,16 @@ extension ValueConcurrentObserver { isModified = true } - // Comparison done: end the WAL snapshot transaction + // Comparison done: close the WAL snapshot transaction // and release its reader connection. - initialFetchTransaction = nil + initialFetchTransaction.close() if isModified { events.databaseDidChange?() // Fetch - let fetchedValue: Reducer.Fetched + // Assume this value can safely be sent to the reduce queue. + nonisolated(unsafe) let fetchedValue: Reducer.Fetcher.Value switch self.trackingMode { case .constantRegion: @@ -540,7 +545,9 @@ extension ValueConcurrentObserver { // for observing the database is to be able to fetch the initial value // without having to wait for an eventual long-running write // transaction to complete. - let (fetchedValue, initialRegion) = try databaseAccess.dbPool.read { db -> (Reducer.Fetched, DatabaseRegion) in + let fetchedValue: Reducer.Fetcher.Value + let initialRegion: DatabaseRegion + (fetchedValue, initialRegion) = try databaseAccess.dbPool.read { db in switch trackingMode { case let .constantRegion(regions): let fetchedValue = try databaseAccess.fetch(db) @@ -585,7 +592,8 @@ extension ValueConcurrentObserver { do { // Fetch - let fetchedValue: Reducer.Fetched + // Assume this value can safely be sent to the reduce queue. + nonisolated(unsafe) let fetchedValue: Reducer.Fetcher.Value let initialRegion: DatabaseRegion let db = try dbResult.get() switch self.trackingMode { @@ -645,7 +653,8 @@ extension ValueConcurrentObserver { do { try writerDB.isolated(readOnly: true) { // Fetch - let fetchedValue: Reducer.Fetched + // Assume this value can safely be sent to the reduce queue. + nonisolated(unsafe) let fetchedValue: Reducer.Fetcher.Value let observedRegion: DatabaseRegion switch self.trackingMode { case .constantRegion: @@ -775,13 +784,12 @@ extension ValueConcurrentObserver: TransactionObserver { } catch { stopDatabaseObservation(writerDB) notifyError(error) - return } } } private func setNeedsFetching(databaseAccess: DatabaseAccess) { - $fetchingState.update { state in + fetchingStateMutex.withLock { state in switch state { case .idle: state = .fetching @@ -807,7 +815,7 @@ extension ValueConcurrentObserver: TransactionObserver { self.reduce(fetchResult) - $fetchingState.update { state in + fetchingStateMutex.withLock { state in switch state { case .idle: // GRDB bug @@ -824,7 +832,10 @@ extension ValueConcurrentObserver: TransactionObserver { } } - private func reduce(_ fetchResult: Result) { + private func reduce(_ fetchResult: Result) { + // Assume this value can safely be sent to the reduce queue. + nonisolated(unsafe) let fetchResult = fetchResult + reduceQueue.async { do { let fetchedValue = try fetchResult.get() diff --git a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift index e7dc67bda..67d915bf0 100644 --- a/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift +++ b/GRDB/ValueObservation/Observers/ValueWriteOnlyObserver.swift @@ -18,10 +18,10 @@ import Foundation /// reducing stage. /// /// **Notify** is calling user callbacks, in case of database change or error. -final class ValueWriteOnlyObserver< - Writer: DatabaseWriter, - Reducer: ValueReducer, - Scheduler: ValueObservationScheduler> +final class ValueWriteOnlyObserver: @unchecked Sendable +where Writer: DatabaseWriter, + Reducer: ValueReducer, + Scheduler: ValueObservationScheduler { // MARK: - Configuration // @@ -83,26 +83,26 @@ final class ValueWriteOnlyObserver< /// If true, database values are fetched from a read-only access. private let readOnly: Bool - /// A reducer that fetches database values. - private let reducer: Reducer + /// The fetcher that fetches database values. + private let fetcher: Reducer.Fetcher - init(writer: Writer, readOnly: Bool, reducer: Reducer) { + init(writer: Writer, readOnly: Bool, fetcher: Reducer.Fetcher) { self.writer = writer self.readOnly = readOnly - self.reducer = reducer + self.fetcher = fetcher } - func fetch(_ db: Database) throws -> Reducer.Fetched { + func fetch(_ db: Database) throws -> Reducer.Fetcher.Value { try db.isolated(readOnly: readOnly) { - try reducer._fetch(db) + try fetcher.fetch(db) } } - func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetched, DatabaseRegion) { + func fetchRecordingObservedRegion(_ db: Database) throws -> (Reducer.Fetcher.Value, DatabaseRegion) { var region = DatabaseRegion() let fetchedValue = try db.isolated(readOnly: readOnly) { try db.recordingSelection(®ion) { - try reducer._fetch(db) + try fetcher.fetch(db) } } return try (fetchedValue, region.observableRegion(db)) @@ -150,7 +150,7 @@ final class ValueWriteOnlyObserver< trackingMode: ValueObservationTrackingMode, reducer: Reducer, events: ValueObservationEvents, - onChange: @escaping (Reducer.Value) -> Void) + onChange: @escaping @Sendable (Reducer.Value) -> Void) { // Configuration self.scheduler = scheduler @@ -160,9 +160,9 @@ final class ValueWriteOnlyObserver< self.databaseAccess = DatabaseAccess( writer: writer, readOnly: readOnly, - // ValueReducer semantics guarantees that reducer._fetch + // ValueReducer semantics guarantees that the fetcher // is independent from the reducer state - reducer: reducer) + fetcher: reducer._makeFetcher()) self.notificationCallbacks = NotificationCallbacks(events: events, onChange: onChange) self.reducer = reducer self.reduceQueue = DispatchQueue( @@ -252,9 +252,11 @@ extension ValueWriteOnlyObserver { writer.asyncWriteWithoutTransaction { db in do { // Fetch & Start observing the database - guard let fetchedValue = try self.fetchAndStartObservation(db) else { + guard let _fetchedValue = try self.fetchAndStartObservation(db) else { return /* Cancelled */ } + // Assume this value can safely be sent to the reduce queue. + nonisolated(unsafe) let fetchedValue = _fetchedValue // Reduce // @@ -301,7 +303,7 @@ extension ValueWriteOnlyObserver { /// By grouping the initial fetch and the beginning of observation in a /// single database access, we are sure that no concurrent write can happen /// during the initial fetch, and that we won't miss any future change. - private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetched? { + private func fetchAndStartObservation(_ db: Database) throws -> Reducer.Fetcher.Value? { let (events, databaseAccess) = lock.synchronized { (notificationCallbacks?.events, self.databaseAccess) } @@ -380,7 +382,8 @@ extension ValueWriteOnlyObserver: TransactionObserver { do { // Fetch - let fetchedValue: Reducer.Fetched + // Assume this value can safely be sent to the reduce queue. + nonisolated(unsafe) let fetchedValue: Reducer.Fetcher.Value switch trackingMode { case .constantRegion, .constantRegionRecordedFromSelection: diff --git a/GRDB/ValueObservation/Reducers/Fetch.swift b/GRDB/ValueObservation/Reducers/Fetch.swift index 4f9b16c88..693c934bb 100644 --- a/GRDB/ValueObservation/Reducers/Fetch.swift +++ b/GRDB/ValueObservation/Reducers/Fetch.swift @@ -1,16 +1,24 @@ extension ValueReducers { /// A `ValueReducer` that perform database fetches. - public struct Fetch: ValueReducer { - private let __fetch: (Database) throws -> Value - - /// Creates a reducer which passes raw fetched values through. - init(fetch: @escaping (Database) throws -> Value) { - self.__fetch = fetch + public struct Fetch: ValueReducer { + public struct _Fetcher: _ValueReducerFetcher { + let _fetch: @Sendable (Database) throws -> Value + + public func fetch(_ db: Database) throws -> Value { + assert(db.isInsideTransaction, "Fetching in a non-isolated way is illegal") + return try _fetch(db) + } } - public func _fetch(_ db: Database) throws -> Value { - assert(db.isInsideTransaction, "Fetching in a non-isolated way is illegal") - return try __fetch(db) + private let _fetch: @Sendable (Database) throws -> Value + + /// Creates a reducer which passes raw fetched values through. + init(fetch: @escaping @Sendable (Database) throws -> Value) { + self._fetch = fetch + } + + public func _makeFetcher() -> _Fetcher { + _Fetcher(_fetch: _fetch) } public func _value(_ fetched: Value) -> Value? { diff --git a/GRDB/ValueObservation/Reducers/Map.swift b/GRDB/ValueObservation/Reducers/Map.swift index b69984b24..ba6f1ec67 100644 --- a/GRDB/ValueObservation/Reducers/Map.swift +++ b/GRDB/ValueObservation/Reducers/Map.swift @@ -18,7 +18,7 @@ extension ValueObservation { /// /// - parameter transform: A closure that takes one value as its parameter /// and returns a new value. - public func map(_ transform: @escaping (Reducer.Value) throws -> T) + public func map(_ transform: @escaping @Sendable (Reducer.Value) throws -> T) -> ValueObservation> { mapReducer { ValueReducers.Map($0, transform) } @@ -26,28 +26,26 @@ extension ValueObservation { } extension ValueReducers { - /// A `ValueReducer` whose values consist of those in a `Base` reduced + /// A `ValueReducer` whose values consist of those in a `Base` reducer /// passed through a transform function. /// /// See ``ValueObservation/map(_:)``. - public struct Map: _ValueReducer { + public struct Map: ValueReducer { private var base: Base private let transform: (Base.Value) throws -> Value - init(_ base: Base, _ transform: @escaping (Base.Value) throws -> Value) { + init(_ base: Base, _ transform: @escaping @Sendable (Base.Value) throws -> Value) { self.base = base self.transform = transform } - public mutating func _value(_ fetched: Base.Fetched) throws -> Value? { + public func _makeFetcher() -> Base.Fetcher { + base._makeFetcher() + } + + public mutating func _value(_ fetched: Base.Fetcher.Value) throws -> Value? { guard let value = try base._value(fetched) else { return nil } return try transform(value) } } } - -extension ValueReducers.Map: ValueReducer where Base: ValueReducer { - public func _fetch(_ db: Database) throws -> Base.Fetched { - try base._fetch(db) - } -} diff --git a/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift index 6d2e64e53..07ec82f59 100644 --- a/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift +++ b/GRDB/ValueObservation/Reducers/RemoveDuplicates.swift @@ -5,10 +5,22 @@ extension ValueObservation { /// - parameter predicate: A closure to evaluate whether two values are /// equivalent, for purposes of filtering. Return true from this closure /// to indicate that the second element is a duplicate of the first. - public func removeDuplicates(by predicate: @escaping (Reducer.Value, Reducer.Value) -> Bool) - -> ValueObservation> - { - mapReducer { ValueReducers.RemoveDuplicates($0, predicate: predicate) } + public func removeDuplicates( + by predicate: sending @escaping (Reducer.Value, Reducer.Value) -> Bool + ) -> ValueObservation> { + // The predicate is marked `sending`, which allows us to statically + // determine that it will have no other uses after this call. + // (according to ) + // + // And because `predicate` will only be used serially, in the + // reducer queue of `ValueObservation` observers, we can say that + // this is safe. + // + // Anyway if we would not accept non-sendable closures, we could + // not deal with `Equatable.==`... + nonisolated(unsafe) let predicate = predicate + + return mapReducer { ValueReducers.RemoveDuplicates($0, predicate: predicate) } } } @@ -67,7 +79,7 @@ extension ValueReducers { /// previously observed value. /// /// See ``ValueObservation/removeDuplicates()``. - public struct RemoveDuplicates: _ValueReducer { + public struct RemoveDuplicates: ValueReducer { private var base: Base private var previousValue: Base.Value? private var predicate: (Base.Value, Base.Value) -> Bool @@ -77,7 +89,11 @@ extension ValueReducers { self.predicate = predicate } - public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? { + public func _makeFetcher() -> Base.Fetcher { + base._makeFetcher() + } + + public mutating func _value(_ fetched: Base.Fetcher.Value) throws -> Base.Value? { guard let value = try base._value(fetched) else { return nil } @@ -90,9 +106,3 @@ extension ValueReducers { } } } - -extension ValueReducers.RemoveDuplicates: ValueReducer where Base: ValueReducer { - public func _fetch(_ db: Database) throws -> Base.Fetched { - try base._fetch(db) - } -} diff --git a/GRDB/ValueObservation/Reducers/Trace.swift b/GRDB/ValueObservation/Reducers/Trace.swift index bb2db4f62..107d80de7 100644 --- a/GRDB/ValueObservation/Reducers/Trace.swift +++ b/GRDB/ValueObservation/Reducers/Trace.swift @@ -4,12 +4,26 @@ extension ValueReducers { /// /// See ``ValueObservation/handleEvents(willStart:willFetch:willTrackRegion:databaseDidChange:didReceiveValue:didFail:didCancel:)`` /// and ``ValueObservation/print(_:to:)``. - public struct Trace: _ValueReducer { + public struct Trace: ValueReducer { + public struct _Fetcher: _ValueReducerFetcher { + let base: Base.Fetcher + let willFetch: @Sendable () -> Void + + public func fetch(_ db: Database) throws -> Base.Fetcher.Value { + willFetch() + return try base.fetch(db) + } + } + var base: Base - let willFetch: () -> Void + let willFetch: @Sendable () -> Void let didReceiveValue: (Base.Value) -> Void - public mutating func _value(_ fetched: Base.Fetched) throws -> Base.Value? { + public func _makeFetcher() -> _Fetcher { + _Fetcher(base: base._makeFetcher(), willFetch: willFetch) + } + + public mutating func _value(_ fetched: Base.Fetcher.Value) throws -> Base.Value? { guard let value = try base._value(fetched) else { return nil } @@ -19,10 +33,3 @@ extension ValueReducers { } // swiftlint:enable line_length } - -extension ValueReducers.Trace: ValueReducer where Base: ValueReducer { - public func _fetch(_ db: Database) throws -> Base.Fetched { - willFetch() - return try base._fetch(db) - } -} diff --git a/GRDB/ValueObservation/Reducers/ValueReducer.swift b/GRDB/ValueObservation/Reducers/ValueReducer.swift index 0a4706057..8c7386693 100644 --- a/GRDB/ValueObservation/Reducers/ValueReducer.swift +++ b/GRDB/ValueObservation/Reducers/ValueReducer.swift @@ -1,10 +1,27 @@ +// A `ValueReducer` fetches and transforms the database values +// observed by a ``ValueObservation``. +// +// It is NOT Sendable, because we need `ValueReducers.RemoveDuplicates` to +// be able to call `Equatable.==`, which IS not a Sendable function. +// Thread-safety will be assured by `ValueObservation`, which will make sure +// it does not invoke the reducer concurrently. +// +// However, we need to be able to fetch from any database dispatch queue, +// and maybe concurrently. That's why a `ValueReducer` has a Sendable facet, +// which is its `Fetcher`. + /// Implementation details of `ValueReducer`. public protocol _ValueReducer { - /// The type of fetched database values - associatedtype Fetched + /// The Sendable type that fetches database values + associatedtype Fetcher: _ValueReducerFetcher /// The type of observed values - associatedtype Value + associatedtype Value: Sendable + + /// Returns a value that fetches database values upon changes in an + /// observed database region. The returned value method must not depend + /// on the state of the reducer. + func _makeFetcher() -> Fetcher /// Transforms a fetched value into an eventual observed value. Returns nil /// when observer should not be notified. @@ -18,7 +35,14 @@ public protocol _ValueReducer { /// reducer._value(...) // MUST NOT be nil /// reducer._value(...) // MAY be nil /// reducer._value(...) // MAY be nil - mutating func _value(_ fetched: Fetched) throws -> Value? + mutating func _value(_ fetched: Fetcher.Value) throws -> Value? +} + +public protocol _ValueReducerFetcher: Sendable { + /// The type of fetched database values + associatedtype Value + + func fetch(_ db: Database) throws -> Value } /// `ValueReducer` supports ``ValueObservation``. @@ -26,17 +50,15 @@ public protocol _ValueReducer { /// A `ValueReducer` fetches and transforms the database values /// observed by a ``ValueObservation``. /// +/// Do not declare new conformances to `ValueReducer`. Only the built-in +/// conforming types are valid. +/// /// ## Topics /// -/// ### Support +/// ### Supporting Types /// /// - ``ValueReducers`` -public protocol ValueReducer: _ValueReducer { - /// Fetches database values upon changes in an observed database region. - /// - /// This method must does not depend on the state of the reducer. - func _fetch(_ db: Database) throws -> Fetched -} +public protocol ValueReducer: _ValueReducer { } /// A namespace for concrete types that adopt the ``ValueReducer`` protocol. public enum ValueReducers { } diff --git a/GRDB/ValueObservation/SharedValueObservation.swift b/GRDB/ValueObservation/SharedValueObservation.swift index 0a0e742ae..0bc78496c 100644 --- a/GRDB/ValueObservation/SharedValueObservation.swift +++ b/GRDB/ValueObservation/SharedValueObservation.swift @@ -87,9 +87,9 @@ extension ValueObservation { /// main dispatch queue. You can change this behavior by providing a /// scheduler. /// - /// For example, the ``ValueObservationScheduler/immediate`` scheduler - /// notifies all values on the main dispatch queue, and notifies the first - /// one immediately when the + /// For example, the ``ValueObservationMainActorScheduler/immediate`` + /// scheduler notifies all values on the main dispatch queue, and + /// notifies the first one immediately when the /// ``SharedValueObservation/start(onError:onChange:)`` method is called. /// The `immediate` scheduling requires that the observation starts from the /// main thread (a fatal error is raised otherwise): @@ -111,16 +111,13 @@ extension ValueObservation { /// // <- here "Fresh players" is already printed. /// ``` /// - /// Note that the `.immediate` scheduler requires that the observation is - /// subscribed from the main thread. It raises a fatal error otherwise. - /// /// - parameter reader: A DatabaseReader. /// - parameter scheduler: A Scheduler. By default, fresh values are /// dispatched asynchronously on the main queue. /// - parameter extent: The extent of the shared database observation. /// - returns: A `SharedValueObservation` public func shared( - in reader: some DatabaseReader, + in reader: any DatabaseReader, scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main), extent: SharedValueObservationExtent = .whileObserved) -> SharedValueObservation @@ -167,7 +164,8 @@ extension ValueObservation { /// let cancellable1 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) /// let cancellable2 = ValueObservation.tracking { db in ... }.shared(in: dbQueue).start(...) /// ``` -public final class SharedValueObservation { +public final class SharedValueObservation: @unchecked Sendable { + // @unchecked Sendable because state is protected by `lock`. private let scheduler: any ValueObservationScheduler private let extent: SharedValueObservationExtent private let startObservation: ValueObservationStart @@ -179,11 +177,14 @@ public final class SharedValueObservation { private var cancellable: AnyDatabaseCancellable? private var lastResult: Result? - private final class Client { - var onError: (Error) -> Void - var onChange: (Element) -> Void + private final class Client: Sendable { + let onError: @Sendable (Error) -> Void + let onChange: @Sendable (Element) -> Void - init(onError: @escaping (Error) -> Void, onChange: @escaping (Element) -> Void) { + init( + onError: @escaping @Sendable (Error) -> Void, + onChange: @escaping @Sendable (Element) -> Void + ) { self.onError = onError self.onChange = onChange } @@ -223,12 +224,12 @@ public final class SharedValueObservation { /// - parameter onChange: The closure to execute on receipt of a /// fresh value. /// - returns: A DatabaseCancellable that can stop the observation. - public func start( - onError: @escaping (Error) -> Void, - onChange: @escaping (Element) -> Void) + @preconcurrency public func start( + onError: @escaping @Sendable (Error) -> Void, + onChange: @escaping @Sendable (Element) -> Void) -> AnyDatabaseCancellable { - synchronized { + withLock { // Support for reentrancy: a shared immediate observation is // started from the first value notification of that same shared // immediate observation. Yeah, users are nasty. @@ -291,7 +292,6 @@ public final class SharedValueObservation { /// print("fresh players: \(players)") /// } /// ``` - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func publisher() -> DatabasePublishers.Value { DatabasePublishers.Value { onError, onChange in self.start(onError: onError, onChange: onChange) @@ -300,7 +300,7 @@ public final class SharedValueObservation { #endif private func handleError(_ error: Error) { - synchronized { + withLock { let notifiedClients = clients // State change @@ -321,7 +321,7 @@ public final class SharedValueObservation { } private func handleChange(_ value: Element) { - synchronized { + withLock { // State change lastResult = .success(value) @@ -333,7 +333,7 @@ public final class SharedValueObservation { } private func handleCancel(_ client: Client) { - synchronized { + withLock { // State change clients.removeFirst(where: { $0 === client }) if clients.isEmpty && extent == .whileObserved { @@ -344,7 +344,7 @@ public final class SharedValueObservation { } } - private func synchronized(_ execute: () throws -> T) rethrows -> T { + private func withLock(_ execute: () throws -> T) rethrows -> T { lock.lock() defer { lock.unlock() } return try execute() @@ -355,8 +355,6 @@ extension SharedValueObservation { // MARK: - Asynchronous Observation /// Returns an asynchronous sequence of observed values. /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// /// For example: /// /// ```swift @@ -368,7 +366,6 @@ extension SharedValueObservation { /// print("Fresh players: \(players)") /// } /// ``` - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func values(bufferingPolicy: AsyncValueObservation.BufferingPolicy = .unbounded) -> AsyncValueObservation { diff --git a/GRDB/ValueObservation/ValueObservation.swift b/GRDB/ValueObservation/ValueObservation.swift index 37c313b20..92cfe9864 100644 --- a/GRDB/ValueObservation/ValueObservation.swift +++ b/GRDB/ValueObservation/ValueObservation.swift @@ -4,7 +4,7 @@ import Combine import Dispatch import Foundation -public struct ValueObservation { +public struct ValueObservation: Sendable { var events = ValueObservationEvents() /// A boolean value indicating whether the observation requires write access @@ -30,10 +30,10 @@ public struct ValueObservation { /// The reducer is created when observation starts, and is triggered upon /// each database change. - var makeReducer: () -> Reducer + var makeReducer: @Sendable () -> Reducer /// Returns a ValueObservation with a transformed reducer. - func mapReducer(_ transform: @escaping (Reducer) -> R) -> ValueObservation { + func mapReducer(_ transform: @escaping @Sendable (Reducer) -> R) -> ValueObservation { let makeReducer = self.makeReducer return ValueObservation( events: events, @@ -74,16 +74,16 @@ enum ValueObservationTrackingMode { } struct ValueObservationEvents: Refinable { - var willStart: (() -> Void)? - var willTrackRegion: ((DatabaseRegion) -> Void)? - var databaseDidChange: (() -> Void)? - var didFail: ((Error) -> Void)? - var didCancel: (() -> Void)? + var willStart: (@Sendable () -> Void)? + var willTrackRegion: (@Sendable (DatabaseRegion) -> Void)? + var databaseDidChange: (@Sendable () -> Void)? + var didFail: (@Sendable (Error) -> Void)? + var didCancel: (@Sendable () -> Void)? } -typealias ValueObservationStart = ( - _ onError: @escaping (Error) -> Void, - _ onChange: @escaping (T) -> Void) +typealias ValueObservationStart = @Sendable ( + _ onError: @escaping @Sendable (Error) -> Void, + _ onChange: @escaping @Sendable (T) -> Void) -> AnyDatabaseCancellable extension ValueObservation: Refinable { @@ -102,6 +102,54 @@ extension ValueObservation: Refinable { /// try Player.fetchAll(db) /// } /// + /// let cancellable = try observation.start( + /// in: dbQueue, + /// scheduling: .async(onQueue: .main)) + /// { error in + /// // handle error + /// } onChange: { (players: [Player]) in + /// print("Fresh players: \(players)") + /// } + /// ``` + /// + /// - parameter reader: A DatabaseReader. + /// - parameter scheduler: A ValueObservationScheduler. + /// - parameter onError: The closure to execute when the + /// observation fails. + /// - parameter onChange: The closure to execute on receipt of a + /// fresh value. + /// - returns: A DatabaseCancellable that can stop the observation. + @preconcurrency public func start( + in reader: any DatabaseReader, + scheduling scheduler: some ValueObservationScheduler, + onError: @escaping @Sendable (Error) -> Void, + onChange: @escaping @Sendable (Reducer.Value) -> Void) + -> AnyDatabaseCancellable + where Reducer: ValueReducer + { + let observation = self.with { + $0.events.didFail = concat($0.events.didFail, onError) + } + observation.events.willStart?() + return reader._add( + observation: observation, + scheduling: scheduler, + onChange: onChange) + } + + /// Starts observing the database and notifies fresh values on the + /// main actor. + /// + /// The observation lasts until the returned cancellable is cancelled + /// or deallocated. + /// + /// For example: + /// + /// ```swift + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// /// let cancellable = try observation.start(in: dbQueue) { error in /// // handle error /// } onChange: { (players: [Player]) in @@ -110,14 +158,8 @@ extension ValueObservation: Refinable { /// ``` /// /// By default, fresh values are dispatched asynchronously on the - /// main dispatch queue. You can change this behavior by providing a - /// scheduler. - /// - /// For example, the ``ValueObservationScheduler/immediate`` scheduler - /// notifies all values on the main dispatch queue, and notifies the first - /// one immediately when the observation starts. The `immediate` scheduling - /// requires that the observation starts from the main dispatch queue (a - /// fatal error is raised otherwise): + /// main actor. Pass `.immediate` if the first value shoud be notified + /// immediately when the observation starts: /// /// ```swift /// let cancellable = try observation.start(in: dbQueue, scheduling: .immediate) { error in @@ -129,28 +171,36 @@ extension ValueObservation: Refinable { /// ``` /// /// - parameter reader: A DatabaseReader. - /// - parameter scheduler: A ValueObservationScheduler. By default, fresh - /// values are dispatched asynchronously on the main queue. - /// - parameter onError: The closure to execute when the observation fails. + /// - parameter scheduler: A ValueObservationMainActorScheduler. + /// By default, fresh values are dispatched asynchronously on the + /// main actor. + /// - parameter onError: The closure to execute when the + /// observation fails. /// - parameter onChange: The closure to execute on receipt of a /// fresh value. /// - returns: A DatabaseCancellable that can stop the observation. - public func start( - in reader: some DatabaseReader, - scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main), - onError: @escaping (Error) -> Void, - onChange: @escaping (Reducer.Value) -> Void) + @preconcurrency @MainActor public func start( + in reader: any DatabaseReader, + scheduling scheduler: some ValueObservationMainActorScheduler = .mainActor, + onError: @escaping @MainActor (Error) -> Void, + onChange: @escaping @MainActor (Reducer.Value) -> Void) -> AnyDatabaseCancellable where Reducer: ValueReducer { - let observation = self.with { - $0.events.didFail = concat($0.events.didFail, onError) - } - observation.events.willStart?() - return reader._add( - observation: observation, - scheduling: scheduler, - onChange: onChange) + let regularScheduler: some ValueObservationScheduler = scheduler + return start( + in: reader, + scheduling: regularScheduler, + onError: { error in + MainActor.assumeIsolated { + onError(error) + } + }, + onChange: { value in + MainActor.assumeIsolated { + onChange(value) + } + }) } // MARK: - Debugging @@ -175,13 +225,13 @@ extension ValueObservation: Refinable { /// - returns: A `ValueObservation` that performs the specified closures /// when ValueObservation events occur. public func handleEvents( - willStart: (() -> Void)? = nil, - willFetch: (() -> Void)? = nil, - willTrackRegion: ((DatabaseRegion) -> Void)? = nil, - databaseDidChange: (() -> Void)? = nil, - didReceiveValue: ((Reducer.Value) -> Void)? = nil, - didFail: ((Error) -> Void)? = nil, - didCancel: (() -> Void)? = nil) + willStart: (@Sendable () -> Void)? = nil, + willFetch: (@Sendable () -> Void)? = nil, + willTrackRegion: (@Sendable (DatabaseRegion) -> Void)? = nil, + databaseDidChange: (@Sendable () -> Void)? = nil, + didReceiveValue: (@Sendable (Reducer.Value) -> Void)? = nil, + didFail: (@Sendable (Error) -> Void)? = nil, + didCancel: (@Sendable () -> Void)? = nil) -> ValueObservation> { self @@ -231,34 +281,33 @@ extension ValueObservation: Refinable { /// used to log messages to other destinations. public func print( _ prefix: String = "", - to stream: TextOutputStream? = nil) + to stream: sending TextOutputStream? = nil) -> ValueObservation> { - let lock = NSLock() + let streamMutex = UnsafeSendableMutex(stream ?? PrintOutputStream()) let prefix = prefix.isEmpty ? "" : "\(prefix): " - var stream = stream ?? PrintOutputStream() return handleEvents( willStart: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)start") }, + streamMutex.withLock { $0.write("\(prefix)start") } + }, willFetch: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)fetch") }, - willTrackRegion: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)tracked region: \($0)") }, + streamMutex.withLock { $0.write("\(prefix)fetch") } + }, + willTrackRegion: { region in + streamMutex.withLock { $0.write("\(prefix)tracked region: \(region)") } + }, databaseDidChange: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)database did change") }, - didReceiveValue: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)value: \($0)") }, - didFail: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)failure: \($0)") }, + streamMutex.withLock { $0.write("\(prefix)database did change") } + }, + didReceiveValue: { value in + streamMutex.withLock { $0.write("\(prefix)value: \(value)") } + }, + didFail: { error in + streamMutex.withLock { $0.write("\(prefix)failure: \(error)") } + }, didCancel: { - lock.lock(); defer { lock.unlock() } - stream.write("\(prefix)cancel") }) + streamMutex.withLock { $0.write("\(prefix)cancel") } + }) } // MARK: - Fetching Values @@ -268,7 +317,9 @@ extension ValueObservation: Refinable { where Reducer: ValueReducer { var reducer = makeReducer() - guard let value = try reducer._value(reducer._fetch(db)) else { + let fetcher = reducer._makeFetcher() + let fetchedValue = try fetcher.fetch(db) + guard let value = try reducer._value(fetchedValue) else { fatalError("Broken contract: reducer has no initial value") } return value @@ -279,8 +330,6 @@ extension ValueObservation { // MARK: - Asynchronous Observation /// Returns an asynchronous sequence of observed values. /// - /// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) - /// /// For example: /// /// ```swift @@ -294,12 +343,13 @@ extension ValueObservation { /// ``` /// /// - parameter reader: A DatabaseReader. - /// - parameter scheduler: A ValueObservationScheduler. By default, fresh - /// values are dispatched asynchronously on the main dispatch queue. - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) + /// - parameter scheduler: A ValueObservationScheduler. By default, + /// fresh values are dispatched on the cooperative thread pool. + /// - parameter bufferingPolicy: see the documntation + /// of `AsyncThrowingStream`. public func values( - in reader: some DatabaseReader, - scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main), + in reader: any DatabaseReader, + scheduling scheduler: some ValueObservationScheduler = .task, bufferingPolicy: AsyncValueObservation.BufferingPolicy = .unbounded) -> AsyncValueObservation where Reducer: ValueReducer @@ -310,11 +360,8 @@ extension ValueObservation { } } -// TODO: [GRDB7] Make it Sendable for easier integration with AsyncAlgorithms /// An asynchronous sequence of values observed by a ``ValueObservation``. /// -/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features) -/// /// An `AsyncValueObservation` sequence produces a fresh value whenever the /// results of database requests change. /// @@ -332,12 +379,13 @@ extension ValueObservation { /// /// You build an `AsyncValueObservation` from ``ValueObservation`` or /// ``SharedValueObservation``. -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) -public struct AsyncValueObservation: AsyncSequence { +public struct AsyncValueObservation: AsyncSequence, Sendable { public typealias BufferingPolicy = AsyncThrowingStream.Continuation.BufferingPolicy public typealias AsyncIterator = Iterator - var bufferingPolicy: BufferingPolicy + // AsyncThrowingStream.Continuation.BufferingPolicy is obviously + // Sendable, but lacks Sendable conformance. + nonisolated(unsafe) var bufferingPolicy: BufferingPolicy var start: ValueObservationStart public func makeAsyncIterator() -> Iterator { @@ -413,11 +461,11 @@ extension ValueObservation { /// main dispatch queue. You can change this behavior by providing a /// scheduler. /// - /// For example, the ``ValueObservationScheduler/immediate`` scheduler - /// notifies all values on the main dispatch queue, and notifies the first - /// one immediately when the observation starts. The `immediate` scheduling - /// requires that the observation starts from the main dispatch queue (a - /// fatal error is raised otherwise): + /// For example, the ``ValueObservationMainActorScheduler/immediate`` + /// scheduler notifies all values on the main dispatch queue, and + /// notifies the first one immediately when the observation starts. The + /// `immediate` scheduling requires that the observation starts from the + /// main dispatch queue (a fatal error is raised otherwise): /// /// ```swift /// let publisher = observation.publisher(in: dbQueue, scheduling: .immediate) @@ -434,9 +482,8 @@ extension ValueObservation { /// - parameter scheduler: A ValueObservationScheduler. By default, fresh /// values are dispatched asynchronously on the main dispatch queue. /// - returns: A Combine publisher - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func publisher( - in reader: some DatabaseReader, + in reader: any DatabaseReader, scheduling scheduler: some ValueObservationScheduler = .async(onQueue: .main)) -> DatabasePublishers.Value where Reducer: ValueReducer @@ -451,7 +498,6 @@ extension ValueObservation { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension DatabasePublishers { /// A publisher that publishes the values of a ``ValueObservation``. /// @@ -473,9 +519,13 @@ extension DatabasePublishers { } } - private class ValueSubscription: Subscription - where Downstream.Failure == Error + private class ValueSubscription: + Subscription, @unchecked Sendable + where Downstream: Subscriber, + Downstream.Failure == Error { + // @unchecked Sendable because `cancellable` and `state` are + // protected by `lock`. private struct WaitingForDemand { let downstream: Downstream let start: ValueObservationStart @@ -729,8 +779,8 @@ extension ValueObservation { /// ``` /// /// - parameter fetch: The closure that fetches the observed value. - public static func trackingConstantRegion( - _ fetch: @escaping (Database) throws -> Value) + @preconcurrency public static func trackingConstantRegion( + _ fetch: @escaping @Sendable (Database) throws -> Value) -> Self where Reducer == ValueReducers.Fetch { @@ -770,7 +820,7 @@ extension ValueObservation { /// /// // Tracks the 'score' column in the 'player' table /// let observation = ValueObservation.tracking( - /// region: Player.select(Column("score"), + /// region: Player.select(\.score), /// fetch: { db in ... }) /// /// // Tracks the 'score' column in the 'player' table @@ -801,10 +851,10 @@ extension ValueObservation { /// - parameter otherRegions: A list of supplementary regions /// to observe. /// - parameter fetch: The closure that fetches the observed value. - public static func tracking( + @preconcurrency public static func tracking( region: any DatabaseRegionConvertible, _ otherRegions: any DatabaseRegionConvertible..., - fetch: @escaping (Database) throws -> Value) + fetch: @escaping @Sendable (Database) throws -> Value) -> Self where Reducer == ValueReducers.Fetch { @@ -842,7 +892,7 @@ extension ValueObservation { /// /// // Tracks the 'score' column in the 'player' table /// let observation = ValueObservation.tracking( - /// regions: [Player.select(Column("score")], + /// regions: [Player.select(\.score)], /// fetch: { db in ... }) /// /// // Tracks the 'score' column in the 'player' table @@ -871,9 +921,9 @@ extension ValueObservation { /// /// - parameter regions: An array of observed regions. /// - parameter fetch: The closure that fetches the observed value. - public static func tracking( + @preconcurrency public static func tracking( regions: [any DatabaseRegionConvertible], - fetch: @escaping (Database) throws -> Value) + fetch: @escaping @Sendable (Database) throws -> Value) -> Self where Reducer == ValueReducers.Fetch { @@ -913,7 +963,7 @@ extension ValueObservation { /// let totalPlayerCount = try Player.fetchCount(db) /// /// let bestPlayers = try Player - /// .order(Column("score").desc) + /// .order(\.score.desc) /// .limit(10) /// .fetchAll(db) /// @@ -929,8 +979,8 @@ extension ValueObservation { /// ``` /// /// - parameter fetch: The closure that fetches the observed value. - public static func tracking( - _ fetch: @escaping (Database) throws -> Value) + @preconcurrency public static func tracking( + _ fetch: @escaping @Sendable (Database) throws -> Value) -> Self where Reducer == ValueReducers.Fetch { diff --git a/GRDB/ValueObservation/ValueObservationScheduler.swift b/GRDB/ValueObservation/ValueObservationScheduler.swift index d43cad7dc..168c7c706 100644 --- a/GRDB/ValueObservation/ValueObservationScheduler.swift +++ b/GRDB/ValueObservation/ValueObservationScheduler.swift @@ -9,19 +9,22 @@ import Foundation /// /// - ``async(onQueue:)`` /// - ``immediate`` +/// - ``mainActor`` +/// - ``task`` +/// - ``task(priority:)`` /// - ``AsyncValueObservationScheduler`` -/// - ``ImmediateValueObservationScheduler`` -public protocol ValueObservationScheduler { +/// - ``TaskValueObservationScheduler`` +public protocol ValueObservationScheduler: Sendable { /// Returns whether the initial value should be immediately notified. /// /// If the result is true, then this method was called on the main thread. func immediateInitialValue() -> Bool - func schedule(_ action: @escaping () -> Void) + func schedule(_ action: @escaping @Sendable () -> Void) } extension ValueObservationScheduler { - func scheduleInitial(_ action: @escaping () -> Void) { + func scheduleInitial(_ action: @escaping @Sendable () -> Void) { if immediateInitialValue() { action() } else { @@ -30,6 +33,29 @@ extension ValueObservationScheduler { } } +// MARK: - ValueObservationMainActorScheduler + +/// A type that determines when `ValueObservation` notifies its fresh +/// values, on the main actor. +/// +/// ## Topics +/// +/// ### Built-In Schedulers +/// +/// - ``immediate`` +/// - ``ValueObservationScheduler/mainActor`` +/// - ``ImmediateValueObservationScheduler`` +/// - ``DelayedMainActorValueObservationScheduler`` +public protocol ValueObservationMainActorScheduler: ValueObservationScheduler { + func scheduleOnMainActor(_ action: @escaping @MainActor () -> Void) +} + +extension ValueObservationMainActorScheduler { + public func schedule(_ action: @escaping @Sendable () -> Void) { + scheduleOnMainActor(action) + } +} + // MARK: - AsyncValueObservationScheduler /// A scheduler that asynchronously notifies fresh value of a `DispatchQueue`. @@ -42,7 +68,7 @@ public struct AsyncValueObservationScheduler: ValueObservationScheduler { public func immediateInitialValue() -> Bool { false } - public func schedule(_ action: @escaping () -> Void) { + public func schedule(_ action: @escaping @Sendable () -> Void) { queue.async(execute: action) } } @@ -77,10 +103,10 @@ extension ValueObservationScheduler where Self == AsyncValueObservationScheduler // MARK: - ImmediateValueObservationScheduler -/// A scheduler that notifies all values on the main `DispatchQueue`. The +/// A scheduler that notifies all values on the main actor. The /// first value is immediately notified when the `ValueObservation` /// is started. -public struct ImmediateValueObservationScheduler: ValueObservationScheduler, Sendable { +public struct ImmediateValueObservationScheduler: ValueObservationMainActorScheduler { public init() { } public func immediateInitialValue() -> Bool { @@ -90,13 +116,13 @@ public struct ImmediateValueObservationScheduler: ValueObservationScheduler, Sen return true } - public func schedule(_ action: @escaping () -> Void) { + public func scheduleOnMainActor(_ action: @escaping @MainActor () -> Void) { DispatchQueue.main.async(execute: action) } } extension ValueObservationScheduler where Self == ImmediateValueObservationScheduler { - /// A scheduler that notifies all values on the main `DispatchQueue`. The + /// A scheduler that notifies all values on the main actor. The /// first value is immediately notified when the `ValueObservation` /// is started. /// @@ -118,8 +144,102 @@ extension ValueObservationScheduler where Self == ImmediateValueObservationSched /// ``` /// /// - important: this scheduler requires that the observation is started - /// from the main queue. A fatal error is raised otherwise. + /// from the main actor. A fatal error is raised otherwise. public static var immediate: ImmediateValueObservationScheduler { ImmediateValueObservationScheduler() } } + +extension ValueObservationMainActorScheduler where Self == ImmediateValueObservationScheduler { + /// A scheduler that notifies all values on the main actor. The + /// first value is immediately notified when the `ValueObservation` + /// is started. + /// + /// For example: + /// + /// ```swift + /// let observation = ValueObservation.tracking { db in + /// try Player.fetchAll(db) + /// } + /// + /// let cancellable = try observation.start( + /// in: dbQueue, + /// scheduling: .immediate, + /// onError: { error in ... }, + /// onChange: { (players: [Player]) in + /// print("fresh players: \(players)") + /// }) + /// // <- here "fresh players" is already printed. + /// ``` + /// + /// - important: this scheduler requires that the observation is started + /// from the main actor. A fatal error is raised otherwise. + public static var immediate: ImmediateValueObservationScheduler { + ImmediateValueObservationScheduler() + } +} + +// MARK: - TaskValueObservationScheduler + +/// A scheduler that notifies all values on the cooperative thread pool. +public final class TaskValueObservationScheduler: ValueObservationScheduler { + typealias Action = @Sendable () -> Void + let continuation: AsyncStream.Continuation + let task: Task + + init(priority: TaskPriority?) { + let (stream, continuation) = AsyncStream.makeStream(of: Action.self) + + self.continuation = continuation + self.task = Task(priority: priority) { + for await action in stream { + action() + } + } + } + + deinit { + task.cancel() + } + + public func immediateInitialValue() -> Bool { + false + } + + public func schedule(_ action: @escaping @Sendable () -> Void) { + continuation.yield(action) + } +} + +extension ValueObservationScheduler where Self == TaskValueObservationScheduler { + /// A scheduler that notifies all values from a new `Task`. + public static var task: TaskValueObservationScheduler { + TaskValueObservationScheduler(priority: nil) + } + + /// A scheduler that notifies all values from a new `Task` with the + /// given priority. + public static func task(priority: TaskPriority) -> TaskValueObservationScheduler { + TaskValueObservationScheduler(priority: priority) + } +} + +// MARK: - DelayedMainActorValueObservationScheduler + +/// A scheduler that notifies all values on the cooperative thread pool. +public final class DelayedMainActorValueObservationScheduler: ValueObservationMainActorScheduler { + public func immediateInitialValue() -> Bool { + false + } + + public func scheduleOnMainActor(_ action: @escaping @MainActor () -> Void) { + DispatchQueue.main.async(execute: action) + } +} + +extension ValueObservationScheduler where Self == DelayedMainActorValueObservationScheduler { + /// A scheduler that notifies all values on the main actor. + public static var mainActor: DelayedMainActorValueObservationScheduler { + DelayedMainActorValueObservationScheduler() + } +} diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 253e90b00..1aebd07be 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -47,6 +47,7 @@ 562205FE1E420EA2005860AC /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; }; 562205FF1E420EA2005860AC /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; }; 562206091E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; }; + 56231A462DCF3A28007676E4 /* TableAlias.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231A452DCF3A28007676E4 /* TableAlias.swift */; }; 56231E6325CEBF08001DFD2F /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */; }; 5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; }; 562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; }; @@ -80,6 +81,7 @@ 563C67B824628C0C00E94EDC /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */; }; 563CBBE42A595141008905CE /* SQLIndexGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563CBBE22A595141008905CE /* SQLIndexGenerator.swift */; }; 563DE4F8231A91F6005081B7 /* DatabaseConfigurationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */; }; + 563EA3E32C7B3A3A001BE0D4 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EA3E22C7B3A3A001BE0D4 /* Mutex.swift */; }; 563EF420215F8A76007DAACD /* OrderedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */; }; 563EF442216131F5007DAACD /* AssociationAggregateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF441216131F5007DAACD /* AssociationAggregateTests.swift */; }; 563EF44D2161F196007DAACD /* Inflections.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EF44C2161F196007DAACD /* Inflections.swift */; }; @@ -166,7 +168,7 @@ 5657AB611D108BA9006283EF /* FoundationNSURLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB341D108BA9006283EF /* FoundationNSURLTests.swift */; }; 5657AB691D108BA9006283EF /* FoundationURLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB351D108BA9006283EF /* FoundationURLTests.swift */; }; 5659F48A1EA8D94E004A4992 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F4871EA8D94E004A4992 /* Utils.swift */; }; - 5659F4921EA8D964004A4992 /* ReadWriteBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */; }; + 5659F4921EA8D964004A4992 /* ReadWriteLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F48F1EA8D964004A4992 /* ReadWriteLock.swift */; }; 5659F49A1EA8D989004A4992 /* Pool.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F4971EA8D989004A4992 /* Pool.swift */; }; 565EFAF11D0436CE00A8FA9D /* NumericOverflowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 565EFAED1D0436CE00A8FA9D /* NumericOverflowTests.swift */; }; 5665F868203EF4640084C6C0 /* ColumnInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5665F865203EF4590084C6C0 /* ColumnInfoTests.swift */; }; @@ -185,7 +187,7 @@ 566B91351FA4D3810012D5B0 /* TransactionObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */; }; 566BD7332927AFD600595649 /* ValueConcurrentObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */; }; 566BD7342927AFD600595649 /* ValueWriteOnlyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */; }; - 566BE7152342541F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7132342541F00A8254B /* LockedBox.swift */; }; + 566BE7152342541F00A8254B /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7132342541F00A8254B /* Mutex.swift */; }; 566DDE12288D76400000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE11288D76400000DCFB /* Fixits.swift */; }; 5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; }; 567071F4208A00BE006AD95A /* SQLiteDateParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */; }; @@ -254,7 +256,6 @@ 569BBA43229066CB00478429 /* InflectionsTests.json in Resources */ = {isa = PBXBuildFile; fileRef = 569BBA42229066CB00478429 /* InflectionsTests.json */; }; 569BBA4D229170B300478429 /* Inflections+English.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569BBA4B229170B300478429 /* Inflections+English.swift */; }; 569EF0E6200D37FD00A9FA45 /* DatabaseRegion.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569EF0E5200D37FC00A9FA45 /* DatabaseRegion.swift */; }; - 56A2FA3924424F4200E97D23 /* Export.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2FA3724424F4200E97D23 /* Export.swift */; }; 56A4CDB31D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; }; 56A5EF121EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */; }; 56A6EB2426076F6A00C27594 /* SQL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A6EB2226076F6A00C27594 /* SQL.swift */; }; @@ -309,6 +310,7 @@ 56DF0015228DDB8300D611F3 /* AssociationPrefetchingCodableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0013228DDB8200D611F3 /* AssociationPrefetchingCodableRecordTests.swift */; }; 56DF0017228DDB8300D611F3 /* AssociationPrefetchingRowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF0014228DDB8200D611F3 /* AssociationPrefetchingRowTests.swift */; }; 56DF37A723D77AA0009AAA05 /* Refinable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DF37A623D77AA0009AAA05 /* Refinable.swift */; }; + 56DFC3AE2C84794400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AD2C84794400DFE5DC /* AsyncSemaphore.swift */; }; 56E4F7F92392E2EE00A611F6 /* DatabaseAbortedTransactionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E4F7F72392E2EE00A611F6 /* DatabaseAbortedTransactionTests.swift */; }; 56E9FAC42210468500C703A8 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAC32210468500C703A8 /* SQLInterpolation.swift */; }; 56EA63C9209C7F1E009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C7209C7F1E009715B8 /* DerivableRequestTests.swift */; }; @@ -499,6 +501,7 @@ 561F38DA2AC8914D0051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = ""; }; 561F38F02AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = ""; }; 561F38F52AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = ""; }; + 56231A452DCF3A28007676E4 /* TableAlias.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableAlias.swift; sourceTree = ""; }; 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = ""; }; 562393171DECC02000A6B01F /* RowFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFetchTests.swift; sourceTree = ""; }; 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AnyCursorTests.swift; sourceTree = ""; }; @@ -546,6 +549,7 @@ 563C67B624628C0C00E94EDC /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = ""; }; 563CBBE22A595141008905CE /* SQLIndexGenerator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIndexGenerator.swift; sourceTree = ""; }; 563DE4F6231A91F6005081B7 /* DatabaseConfigurationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseConfigurationTests.swift; sourceTree = ""; }; + 563EA3E22C7B3A3A001BE0D4 /* Mutex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = ""; }; 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OrderedDictionary.swift; sourceTree = ""; }; 563EF441216131F5007DAACD /* AssociationAggregateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationAggregateTests.swift; sourceTree = ""; }; 563EF44C2161F196007DAACD /* Inflections.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Inflections.swift; sourceTree = ""; }; @@ -633,7 +637,7 @@ 5657AB341D108BA9006283EF /* FoundationNSURLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSURLTests.swift; sourceTree = ""; }; 5657AB351D108BA9006283EF /* FoundationURLTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationURLTests.swift; sourceTree = ""; }; 5659F4871EA8D94E004A4992 /* Utils.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Utils.swift; sourceTree = ""; }; - 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteBox.swift; sourceTree = ""; }; + 5659F48F1EA8D964004A4992 /* ReadWriteLock.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ReadWriteLock.swift; sourceTree = ""; }; 5659F4971EA8D989004A4992 /* Pool.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Pool.swift; sourceTree = ""; }; 565B0FEE1BBC7D980098DE03 /* FetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchableRecordTests.swift; sourceTree = ""; }; 565D5D701BBC694D00DC9BD4 /* Row+FoundationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Row+FoundationTests.swift"; sourceTree = ""; }; @@ -656,7 +660,7 @@ 566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = ""; }; 566BD7312927AFD600595649 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = ""; }; 566BD7322927AFD600595649 /* ValueWriteOnlyObserver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ValueWriteOnlyObserver.swift; sourceTree = ""; }; - 566BE7132342541F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = ""; }; + 566BE7132342541F00A8254B /* Mutex.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = ""; }; 566DDE11288D76400000DCFB /* Fixits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Fixits.swift; sourceTree = ""; }; 56703299212B5461007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = ""; }; 567071F2208A00BE006AD95A /* SQLiteDateParser.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLiteDateParser.swift; sourceTree = ""; }; @@ -770,7 +774,6 @@ 56A238921B9C750B0082EB20 /* DatabaseMigrator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseMigrator.swift; sourceTree = ""; }; 56A238A11B9C753B0082EB20 /* Record.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Record.swift; sourceTree = ""; }; 56A238B51B9CA2590082EB20 /* DatabaseTimestampTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseTimestampTests.swift; sourceTree = ""; }; - 56A2FA3724424F4200E97D23 /* Export.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Export.swift; sourceTree = ""; }; 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpressionLiteralTests.swift; sourceTree = ""; }; 56A5E4081BA2BCF900707640 /* RecordWithColumnNameManglingTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordWithColumnNameManglingTests.swift; sourceTree = ""; }; 56A5EF0E1EF7F20B00F03071 /* ForeignKeyInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyInfoTests.swift; sourceTree = ""; }; @@ -830,6 +833,7 @@ 56DF0013228DDB8200D611F3 /* AssociationPrefetchingCodableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingCodableRecordTests.swift; sourceTree = ""; }; 56DF0014228DDB8200D611F3 /* AssociationPrefetchingRowTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationPrefetchingRowTests.swift; sourceTree = ""; }; 56DF37A623D77AA0009AAA05 /* Refinable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Refinable.swift; sourceTree = ""; }; + 56DFC3AD2C84794400DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = ""; }; 56E4F7F72392E2EE00A611F6 /* DatabaseAbortedTransactionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAbortedTransactionTests.swift; sourceTree = ""; }; 56E8CE0C1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertibleFetchTests.swift; sourceTree = ""; }; 56E8CE0F1BB4FE5B00828BEC /* StatementColumnConvertibleFetchTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertibleFetchTests.swift; sourceTree = ""; }; @@ -1032,8 +1036,10 @@ 56176C581EACC2D8000F3F2B /* GRDBTests */ = { isa = PBXGroup; children = ( + 56DFC3AD2C84794400DFE5DC /* AsyncSemaphore.swift */, 567E4207242AB3CB00CAAD2C /* FailureTestCase.swift */, 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */, + 563EA3E22C7B3A3A001BE0D4 /* Mutex.swift */, 562EA81E1F17B26F00FA528C /* Compilation */, 56A238111B9C74A90082EB20 /* Core */, 567B5BFC2AD3285C00629622 /* Dump */, @@ -1271,6 +1277,7 @@ 5656A82A2295BD56001FF3FF /* SQLQueryGenerator.swift */, 56F89E182A585E0D002FE2AA /* SQLTableAlterationGenerator.swift */, 56F89E192A585E0D002FE2AA /* SQLTableGenerator.swift */, + 56231A452DCF3A28007676E4 /* TableAlias.swift */, ); path = SQLGeneration; sourceTree = ""; @@ -1341,11 +1348,11 @@ 564D4F91261E1D3300F55856 /* CaseInsensitiveIdentifier.swift */, 563EF44C2161F196007DAACD /* Inflections.swift */, 569BBA4B229170B300478429 /* Inflections+English.swift */, - 566BE7132342541F00A8254B /* LockedBox.swift */, + 566BE7132342541F00A8254B /* Mutex.swift */, 563B8FBC24A1D388007A48C9 /* OnDemandFuture.swift */, 563EF41E215F8A76007DAACD /* OrderedDictionary.swift */, 5659F4971EA8D989004A4992 /* Pool.swift */, - 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */, + 5659F48F1EA8D964004A4992 /* ReadWriteLock.swift */, 563B8FB924A1D036007A48C9 /* ReceiveValuesOn.swift */, 56DF37A623D77AA0009AAA05 /* Refinable.swift */, 5659F4871EA8D94E004A4992 /* Utils.swift */, @@ -1746,7 +1753,6 @@ DC37742D19C8CC90004FCF85 /* GRDB */ = { isa = PBXGroup; children = ( - 56A2FA3724424F4200E97D23 /* Export.swift */, 566DDE11288D76400000DCFB /* Fixits.swift */, 648704B82B8261070036480B /* PrivacyInfo.xcprivacy */, 56A2386F1B9C75030082EB20 /* Core */, @@ -1986,6 +1992,7 @@ buildActionMask = 2147483647; files = ( 5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */, + 56231A462DCF3A28007676E4 /* TableAlias.swift in Sources */, 56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */, 5685C1962AD52EF200DA4B7A /* ListDumpFormat.swift in Sources */, 566BD7332927AFD600595649 /* ValueConcurrentObserver.swift in Sources */, @@ -2006,7 +2013,7 @@ 56012B82257404A400B4925B /* CommonTableExpression.swift in Sources */, 5656A8972295BD56001FF3FF /* SQLRelation.swift in Sources */, 56D110FF28AFC9C600E64463 /* MutablePersistableRecord+DAO.swift in Sources */, - 5659F4921EA8D964004A4992 /* ReadWriteBox.swift in Sources */, + 5659F4921EA8D964004A4992 /* ReadWriteLock.swift in Sources */, 566A842D20413D9A00E50BFD /* DatabaseSnapshot.swift in Sources */, 56CEB4F31EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */, 5656A8512295BD56001FF3FF /* SQLInterpolation+QueryInterface.swift in Sources */, @@ -2055,7 +2062,6 @@ F3BA806F1CFB2E55003DC1BA /* DatabaseValue.swift in Sources */, 56C0539722ACEECD0029D27D /* ValueReducer.swift in Sources */, 4E13D2F82769BC230037588C /* DatabaseBackupProgress.swift in Sources */, - 56A2FA3924424F4200E97D23 /* Export.swift in Sources */, 56FA0C3728B1F2EB00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */, 56B964B31DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */, F3BA80731CFB2E55003DC1BA /* RowAdapter.swift in Sources */, @@ -2101,7 +2107,7 @@ 5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */, 5656A86D2295BD56001FF3FF /* HasManyThroughAssociation.swift in Sources */, 56894FE3260658A400268F4D /* Decimal.swift in Sources */, - 566BE7152342541F00A8254B /* LockedBox.swift in Sources */, + 566BE7152342541F00A8254B /* Mutex.swift in Sources */, F3BA806D1CFB2E55003DC1BA /* DatabaseSchemaCache.swift in Sources */, F3BA80841CFB2E67003DC1BA /* StandardLibrary.swift in Sources */, 5656A87F2295BD56001FF3FF /* SQLForeignKeyRequest.swift in Sources */, @@ -2305,6 +2311,7 @@ F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5653EB7420961FB200F46237 /* AssociationRowScopeSearchTests.swift in Sources */, 5691578E231BF2BE00E1D237 /* PoolTests.swift in Sources */, + 563EA3E32C7B3A3A001BE0D4 /* Mutex.swift in Sources */, 5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 56419C7E24A51D6E004967E1 /* DatabaseWriterWritePublisherTests.swift in Sources */, 5665FA3D2129EED8004D8612 /* DatabaseDateEncodingStrategyTests.swift in Sources */, @@ -2358,6 +2365,7 @@ 567DAF381EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */, 569BBA2B228DE53200478429 /* AssociationPrefetchingFetchableRecordTests.swift in Sources */, 56F34FBF24B094D2007513FC /* SQLExpressionIsConstantTests.swift in Sources */, + 56DFC3AE2C84794400DFE5DC /* AsyncSemaphore.swift in Sources */, 5670329B212B5462007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */, 5616B50028B5F5490052017E /* SingletonRecordTest.swift in Sources */, 56F34FC624B0A0C9007513FC /* SQLIdentifyingColumnsTests.swift in Sources */, diff --git a/LICENSE b/LICENSE index 922a3e13a..550890c89 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright (C) 2015-2024 Gwendal Roué +Copyright (C) 2015-2025 Gwendal Roué Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: diff --git a/Makefile b/Makefile index 819e8dcae..9c91521f3 100644 --- a/Makefile +++ b/Makefile @@ -19,6 +19,9 @@ XCRUN := $(shell command -v xcrun) XCODEBUILD := set -o pipefail && $(shell command -v xcodebuild) ifdef TOOLCHAIN + # Look for the toolchain identifier in the CFBundleIdentifier key of its Info.plist: + # TOOLCHAIN=org.swift.600202404221a make test + # If TOOLCHAIN is specified, add xcodebuild parameter XCODEBUILD += -toolchain $(TOOLCHAIN) @@ -78,7 +81,7 @@ test_framework_SQLCipher: test_framework_SQLCipher3 test_framework_SQLCipher3Enc test_archive: test_universal_xcframework test_install: test_install_manual test_install_SPM test_install_customSQLite test_install_GRDB_CocoaPods test_CocoaPodsLint: test_CocoaPodsLint_GRDB -test_demo_apps: test_GRDBDemoiOS test_GRDBCombineDemo test_GRDBAsyncDemo +test_demo_apps: test_GRDBDemo test_framework_GRDBOSX: $(XCODEBUILD) \ @@ -214,6 +217,7 @@ endif test_SPM: # Add sanitizers when available: https://twitter.com/simjp/status/929140877540278272 + rm -rf Tests/products $(SWIFT) package clean $(SWIFT) build $(SWIFT) build -c release @@ -267,21 +271,23 @@ test_universal_xcframework: test_install_manual: $(XCODEBUILD) \ - -project Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj \ - -scheme GRDBDemoiOS \ + -project Tests/GRDBManualInstall/GRDBManualInstall.xcodeproj \ + -scheme GRDBManualInstall \ -configuration Release \ - -destination $(MAX_IOS_DESTINATION) \ + -destination "platform=macOS" \ clean build \ $(XCPRETTY) test_install_SPM: test_install_SPM_Package test_install_SPM_Project test_install_SPM_Dynamic_Project test_install_SPM_macos_release test_install_SPM_ios_release test_install_SPM_Package: + rm -rf Tests/products cd Tests/SPM/PlainPackage && \ $(SWIFT) build && \ ./.build/debug/SPM test_install_SPM_Project: + rm -rf Tests/products $(XCODEBUILD) \ -project Tests/SPM/PlainProject/Plain.xcodeproj \ -scheme Plain \ @@ -291,6 +297,7 @@ test_install_SPM_Project: $(XCPRETTY) test_install_SPM_Dynamic_Project: + rm -rf Tests/products $(XCODEBUILD) \ -project Tests/SPM/ios-dynamic/ios-dynamic.xcodeproj \ -scheme ios-dynamic \ @@ -300,6 +307,7 @@ test_install_SPM_Dynamic_Project: $(XCPRETTY) test_install_SPM_macos_release: + rm -rf Tests/products $(XCODEBUILD) \ -project Tests/SPM/macos/macos.xcodeproj \ -scheme macos \ @@ -309,6 +317,7 @@ test_install_SPM_macos_release: $(XCPRETTY) test_install_SPM_ios_release: + rm -rf Tests/products $(XCODEBUILD) \ -project Tests/SPM/ios/ios.xcodeproj \ -scheme ios \ @@ -368,26 +377,10 @@ else @exit 1 endif -test_GRDBDemoiOS: +test_GRDBDemo: $(XCODEBUILD) \ - -project Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj \ - -scheme GRDBDemoiOS \ - -destination $(MAX_IOS_DESTINATION) \ - $(TEST_ACTIONS) \ - $(XCPRETTY) - -test_GRDBCombineDemo: - $(XCODEBUILD) \ - -project Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj \ - -scheme GRDBCombineDemo \ - -destination $(MAX_IOS_DESTINATION) \ - $(TEST_ACTIONS) \ - $(XCPRETTY) - -test_GRDBAsyncDemo: - $(XCODEBUILD) \ - -project Documentation/DemoApps/GRDBAsyncDemo/GRDBAsyncDemo.xcodeproj \ - -scheme GRDBAsyncDemo \ + -project Documentation/DemoApps/GRDBDemo/GRDBDemo.xcodeproj \ + -scheme GRDBDemo \ -destination $(MAX_IOS_DESTINATION) \ $(TEST_ACTIONS) \ $(XCPRETTY) diff --git a/Package.swift b/Package.swift index a6f51175e..36937d039 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.7 +// swift-tools-version:6.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import Foundation @@ -10,9 +10,6 @@ var swiftSettings: [SwiftSetting] = [ var cSettings: [CSetting] = [] var dependencies: [PackageDescription.Package.Dependency] = [] -// For Swift 5.8+ -//swiftSettings.append(.enableUpcomingFeature("ExistentialAny")) - // Don't rely on those environment variables. They are ONLY testing conveniences: // $ SQLITE_ENABLE_PREUPDATE_HOOK=1 make test_SPM if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" { @@ -34,24 +31,24 @@ let package = Package( name: "GRDB", defaultLocalization: "en", // for tests platforms: [ - .iOS(.v11), - .macOS(.v10_13), - .tvOS(.v11), - .watchOS(.v4), + .iOS(.v13), + .macOS(.v10_15), + .tvOS(.v13), + .watchOS(.v7), ], products: [ - .library(name: "CSQLite", targets: ["CSQLite"]), + .library(name: "GRDBSQLite", targets: ["GRDBSQLite"]), .library(name: "GRDB", targets: ["GRDB"]), .library(name: "GRDB-dynamic", type: .dynamic, targets: ["GRDB"]), ], dependencies: dependencies, targets: [ .systemLibrary( - name: "CSQLite", + name: "GRDBSQLite", providers: [.apt(["libsqlite3-dev"])]), .target( name: "GRDB", - dependencies: ["CSQLite"], + dependencies: ["GRDBSQLite"], path: "GRDB", resources: [.copy("PrivacyInfo.xcprivacy")], cSettings: cSettings, @@ -64,10 +61,12 @@ let package = Package( "CocoaPods", "Crash", "CustomSQLite", + "GRDBManualInstall", "GRDBTests/getThreadsCount.c", "Info.plist", "Performance", "SPM", + "Swift6Migration", "generatePerformanceReport.rb", "parsePerformanceTests.rb", ], @@ -77,7 +76,12 @@ let package = Package( .copy("GRDBTests/Issue1383.sqlite"), ], cSettings: cSettings, - swiftSettings: swiftSettings) + swiftSettings: swiftSettings + [ + // Tests still use the Swift 5 language mode. + .swiftLanguageMode(.v5), + .enableUpcomingFeature("InferSendableFromCaptures"), + .enableUpcomingFeature("GlobalActorIsolatedTypesUsability"), + ]) ], - swiftLanguageVersions: [.v5] + swiftLanguageModes: [.v6] ) diff --git a/README.md b/README.md index 79838cbd2..bd588afab 100644 --- a/README.md +++ b/README.md @@ -10,18 +10,18 @@

- Swift 5.7 + Swift 6 License CI Status

-**Latest release**: July 11, 2024 • [version 6.28.0](https://github.com/groue/GRDB.swift/tree/v6.28.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) +**Latest release**: May 11, 2025 • [version 7.5.0](https://github.com/groue/GRDB.swift/tree/v7.5.0) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) -**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+ +**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ • SQLite 3.20.0+ • Swift 6+ / Xcode 16+ **Contact**: -- Release announcements and usage tips: follow [@groue](http://twitter.com/groue) on Twitter, [@groue@hachyderm.io](https://hachyderm.io/@groue) on Mastodon. +- Release announcements and usage tips: follow [@groue@hachyderm.io](https://hachyderm.io/@groue) on Mastodon. - Report bugs in a [Github issue](https://github.com/groue/GRDB.swift/issues/new). Make sure you check the [existing issues](https://github.com/groue/GRDB.swift/issues?q=is%3Aopen) first. - A question? Looking for advice? Do you wonder how to contribute? Fancy a chat? Go to the [GitHub discussions](https://github.com/groue/GRDB.swift/discussions), or the [GRDB forums](https://forums.swift.org/c/related-projects/grdb). @@ -82,10 +82,15 @@ try dbQueue.write { db in } // 3. Define a record type -struct Player: Codable, FetchableRecord, PersistableRecord { +struct Player: Codable, Identifiable, FetchableRecord, PersistableRecord { var id: String var name: String var score: Int + + enum Columns { + static let name = Column(CodingKeys.name) + static let score = Column(CodingKeys.score) + } } // 4. Write and read in the database @@ -94,8 +99,13 @@ try dbQueue.write { db in try Player(id: "2", name: "Barbara", score: 1000).insert(db) } -let players: [Player] = try dbQueue.read { db in - try Player.fetchAll(db) +try dbQueue.read { db in + let player = try Player.find(db, id: "1")) + + let bestPlayers = try Player + .order(\.score.desc) + .limit(10) + .fetchAll(db) } ``` @@ -107,25 +117,24 @@ let players: [Player] = try dbQueue.read { db in ```swift try dbQueue.write { db in try db.execute(sql: """ - CREATE TABLE place ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - title TEXT NOT NULL, - favorite BOOLEAN NOT NULL DEFAULT 0, - latitude DOUBLE NOT NULL, - longitude DOUBLE NOT NULL) + CREATE TABLE player ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + score INT NOT NULL) """) try db.execute(sql: """ - INSERT INTO place (title, favorite, latitude, longitude) - VALUES (?, ?, ?, ?) - """, arguments: ["Paris", true, 48.85341, 2.3488]) - - let parisId = db.lastInsertedRowID + INSERT INTO player (id, name, score) + VALUES (?, ?, ?) + """, arguments: ["1", "Arthur", 100]) // Avoid SQL injection with SQL interpolation + let id = "2" + let name = "O'Brien" + let score = 1000 try db.execute(literal: """ - INSERT INTO place (title, favorite, latitude, longitude) - VALUES (\("King's Cross"), \(true), \(51.52151), \(-0.12763)) + INSERT INTO player (id, name, score) + VALUES (\(id), \(name), \(score)) """) } ``` @@ -140,22 +149,20 @@ See [Executing Updates](#executing-updates) ```swift try dbQueue.read { db in // Fetch database rows - let rows = try Row.fetchCursor(db, sql: "SELECT * FROM place") + let rows = try Row.fetchCursor(db, sql: "SELECT * FROM player") while let row = try rows.next() { - let title: String = row["title"] - let isFavorite: Bool = row["favorite"] - let coordinate = CLLocationCoordinate2D( - latitude: row["latitude"], - longitude: row["longitude"]) + let id: String = row["id"] + let name: String = row["name"] + let score: Int = row["score"] } // Fetch values - let placeCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! // Int - let placeTitles = try String.fetchAll(db, sql: "SELECT title FROM place") // [String] + let playerCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player")! // Int + let playerNames = try String.fetchAll(db, sql: "SELECT name FROM player") // [String] } -let placeCount = try dbQueue.read { db in - try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! +let playerCount = try dbQueue.read { db in + try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM player")! } ``` @@ -167,37 +174,37 @@ See [Fetch Queries](#fetch-queries) Database model types aka "records" ```swift -struct Place { - var id: Int64? - var title: String - var isFavorite: Bool - var coordinate: CLLocationCoordinate2D +struct Player: Codable, Identifiable, FetchableRecord, PersistableRecord { + var id: String + var name: String + var score: Int + + enum Columns { + static let name = Column(CodingKeys.name) + static let score = Column(CodingKeys.score) + } } -// snip: turn Place into a "record" by adopting the protocols that -// provide fetching and persistence methods. - try dbQueue.write { db in // Create database table - try db.create(table: "place") { t in - t.autoIncrementedPrimaryKey("id") - t.column("title", .text).notNull() - t.column("favorite", .boolean).notNull().defaults(to: false) - t.column("longitude", .double).notNull() - t.column("latitude", .double).notNull() + try db.create(table: "player") { t in + t.primaryKey("id", .text) + t.column("name", .text).notNull() + t.column("score", .integer).notNull() } - var berlin = Place( - id: nil, - title: "Berlin", - isFavorite: false, - coordinate: CLLocationCoordinate2D(latitude: 52.52437, longitude: 13.41053)) + // Insert a record + var player = Player(id: "1", name: "Arthur", score: 100) + try player.insert(db) - try berlin.insert(db) - berlin.id // some value + // Update a record + player.score += 10 + try score.update(db) - berlin.isFavorite = true - try berlin.update(db) + try player.updateChanges { $0.score += 10 } + + // Delete a record + try player.delete(db) } ``` @@ -210,23 +217,20 @@ See [Records](#records) ```swift try dbQueue.read { db in - // Place - let paris = try Place.find(db, id: 1) + // Player + let player = try Player.find(db, id: "1") - // Place? - let berlin = try Place.filter(Column("title") == "Berlin").fetchOne(db) + // Player? + let arthur = try Player.filter { $0.name == "Arthur" }.fetchOne(db) - // [Place] - let favoritePlaces = try Place - .filter(Column("favorite") == true) - .order(Column("title")) - .fetchAll(db) + // [Player] + let bestPlayers = try Player.order(\.score.desc).limit(10).fetchAll(db) // Int - let favoriteCount = try Place.filter(Column("favorite")).fetchCount(db) + let playerCount = try Player.fetchCount(db) // SQL is always welcome - let places = try Place.fetchAll(db, sql: "SELECT * FROM place") + let players = try Player.fetchAll(db, sql: "SELECT * FROM player") } ``` @@ -240,27 +244,32 @@ See the [Query Interface](#the-query-interface) ```swift // Define the observed value let observation = ValueObservation.tracking { db in - try Place.fetchAll(db) + try Player.fetchAll(db) } // Start observation let cancellable = observation.start( in: dbQueue, onError: { error in ... }, - onChange: { (places: [Place]) in print("Fresh places: \(places)") }) + onChange: { (players: [Player]) in print("Fresh players: \(players)") }) ``` Ready-made support for Combine and RxSwift: ```swift +// Swift concurrency +for try await players in observation.values(in: dbQueue) { + print("Fresh players: \(players)") +} + // Combine let cancellable = observation.publisher(in: dbQueue).sink( receiveCompletion: { completion in ... }, - receiveValue: { (places: [Place]) in print("Fresh places: \(places)") }) + receiveValue: { (players: [Player]) in print("Fresh players: \(players)") }) // RxSwift let disposable = observation.rx.observe(in: dbQueue).subscribe( - onNext: { (places: [Place]) in print("Fresh places: \(places)") }, + onNext: { (players: [Player]) in print("Fresh players: \(players)") }, onError: { error in ... }) ``` @@ -276,12 +285,12 @@ Documentation #### Demo Applications & Frequently Asked Questions -- [Demo Applications]: Three flavors: vanilla UIKit, Combine + SwiftUI, and Async/Await + SwiftUI. +- [Demo Applications] - [FAQ] #### 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 +304,7 @@ Documentation #### Records and the Query Interface - [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies -- [Query Interface](#the-query-interface): A swift way to generate SQL • [create tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) • [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md) +- [Query Interface](#the-query-interface): A swift way to generate SQL • [create tables, indexes, etc](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) • [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md) #### Application Tools @@ -315,10 +324,10 @@ Documentation - [Error Handling](#error-handling) - [Unicode](#unicode) - [Memory Management](#memory-management) -- [Data Protection](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections) -- :bulb: [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) +- [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 @@ -340,6 +349,15 @@ See [Encryption](#encryption) for the installation procedure of GRDB with SQLCip See [Custom SQLite builds](Documentation/CustomSQLiteBuilds.md) for the installation procedure of GRDB with a customized build of SQLite. +## Swift Package Manager + +The [Swift Package Manager](https://swift.org/package-manager/) automates the distribution of Swift code. To use GRDB with SPM, add a dependency to `https://github.com/groue/GRDB.swift.git` + +GRDB offers two libraries, `GRDB` and `GRDB-dynamic`. Pick only one. When in doubt, prefer `GRDB`. The `GRDB-dynamic` library can reveal useful if you are going to link it with multiple targets within your app and only wish to link to a shared, dynamic framework once. See [How to link a Swift Package as dynamic](https://forums.swift.org/t/how-to-link-a-swift-package-as-dynamic/32062) for more information. + +> **Note**: Linux support is provided by contributors. It is not automatically tested, and not officially maintained. If you notice a build or runtime failure on Linux, please open a pull request with the necessary fix, thank you! + + ## CocoaPods [CocoaPods](http://cocoapods.org/) is a dependency manager for Xcode projects. To use GRDB with CocoaPods (version 1.2 or higher), specify in your `Podfile`: @@ -350,15 +368,24 @@ pod 'GRDB.swift' GRDB can be installed as a framework, or a static library. -## Swift Package Manager +**Important Note for CocoaPods installation** -The [Swift Package Manager](https://swift.org/package-manager/) automates the distribution of Swift code. To use GRDB with SPM, add a dependency to `https://github.com/groue/GRDB.swift.git` +Due to an [issue](https://github.com/CocoaPods/CocoaPods/issues/11839) in CocoaPods, it is currently not possible to deploy new versions of GRDB to CocoaPods. The last version available on CocoaPods is 6.24.1. To install later versions of GRDB using CocoaPods, use one of the following workarounds: -GRDB offers two libraries, `GRDB` and `GRDB-dynamic`. Pick only one. When in doubt, prefer `GRDB`. The `GRDB-dynamic` library can reveal useful if you are going to link it with multiple targets within your app and only wish to link to a shared, dynamic framework once. See [How to link a Swift Package as dynamic](https://forums.swift.org/t/how-to-link-a-swift-package-as-dynamic/32062) for more information. +- Depend on the `GRDB7` branch. This is more or less equivalent to what `pod 'GRDB.swift', '~> 7.0'` would normally do, if CocoaPods would accept new GRDB versions to be published: -> **Note**: Linux is not currently supported. -> -> **Warning**: Due to an Xcode bug, you will get "No such module 'CSQLite'" errors when you want to embed the GRDB package in other targets than the main application (watch extensions, for example). UI and Unit testing targets are OK, though. See [#642](https://github.com/groue/GRDB.swift/issues/642#issuecomment-575994093) for more information. + ```ruby + # Can't use semantic versioning due to https://github.com/CocoaPods/CocoaPods/issues/11839 + pod 'GRDB.swift', git: 'https://github.com/groue/GRDB.swift.git', branch: 'GRDB7' + ``` + +- Depend on a specific version explicitly (Replace the tag with the version you want to use): + + ```ruby + # Can't use semantic versioning due to https://github.com/CocoaPods/CocoaPods/issues/11839 + # Replace the tag with the tag that you want to use. + pod 'GRDB.swift', git: 'https://github.com/groue/GRDB.swift.git', tag: 'v6.29.0' + ``` ## Carthage @@ -375,8 +402,6 @@ GRDB offers two libraries, `GRDB` and `GRDB-dynamic`. Pick only one. When in dou 4. Add the `GRDB.framework` to the **Embedded Binaries** section of the **General** tab of your application target (extension target for WatchOS). -> :bulb: **Tip**: see the [Demo Applications] for examples of such integration. - Database Connections ==================== @@ -399,7 +424,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 @@ -425,14 +450,14 @@ Advanced topics: - [Prepared Statements] - [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates) -- [Database Schema Introspection](#database-schema-introspection) -- [Row Adapters](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter) +- [Database Schema Introspection](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschemaintrospection) +- [Row Adapters](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/rowadapter) - [Raw SQLite Pointers](#raw-sqlite-pointers) ## Executing Updates -Once granted with a [database connection], the [`execute(sql:arguments:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/execute(sql:arguments:)) method executes the SQL statements that do not return any database row, such as `CREATE TABLE`, `INSERT`, `DELETE`, `ALTER`, etc. +Once granted with a [database connection], the [`execute(sql:arguments:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/database/execute(sql:arguments:)) method executes the SQL statements that do not return any database row, such as `CREATE TABLE`, `INSERT`, `DELETE`, `ALTER`, etc. For example: @@ -458,7 +483,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 @@ -510,7 +535,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( @@ -610,7 +635,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**. @@ -696,7 +721,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 @@ -737,7 +762,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 @@ -825,6 +850,13 @@ row[...] as Int? > if let int = row[...] as Int? { ... } // GOOD > ``` +> **Warning**: avoid nil-coalescing row values, and prefer the `coalesce` method instead: +> +> ```swift +> let name: String? = row["nickname"] ?? row["name"] // BAD - doesn't work +> let name: String? = row.coalesce(["nickname", "name"]) // GOOD +> ``` + Generally speaking, you can extract the type you need, provided it can be converted from the underlying SQLite value: - **Successful conversions include:** @@ -905,7 +937,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.** @@ -931,7 +963,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"] @@ -1017,7 +1049,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.). @@ -1088,7 +1120,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 = ... @@ -1132,7 +1164,7 @@ Use values in the [query interface](#the-query-interface): ```swift let url: URL = ... -let link = try Link.filter(Column("url") == url).fetchOne(db) +let link = try Link.filter { $0.url == url }.fetchOne(db) ``` @@ -1414,7 +1446,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*. @@ -1486,7 +1518,7 @@ try Double.fetchOne(db, sql: "SELECT sqrt(-1)")! ```swift // SELECT reverseString("name") FROM player -Player.select(reverseString(nameColumn)) +Player.select { reverseString($0.name) } ``` @@ -1495,7 +1527,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: @@ -1568,54 +1600,20 @@ SQLite has the opportunity to perform additional optimizations when aggregates a ```swift // SELECT maxLength("name") FROM player -let request = Player.select(maxLength.apply(nameColumn)) +let request = Player.select { maxLength($0.name) } try Int.fetchOne(db, request) // Int? ``` -## Database Schema Introspection - -GRDB comes with a set of schema introspection methods: - -```swift -try dbQueue.read { db in - // Bool, true if the table exists - try db.tableExists("player") - - // [ColumnInfo], the columns in the table - try db.columns(in: "player") - - // PrimaryKeyInfo - try db.primaryKey("player") - - // [ForeignKeyInfo], the foreign keys defined on the table - try db.foreignKeys(on: "player") - - // [IndexInfo], the indexes defined on the table - try db.indexes(on: "player") - - // Bool, true if column(s) is a unique key (primary key or unique index) - try db.table("player", hasUniqueKey: ["email"]) -} - -// Bool, true if argument is the name of an internal SQLite table -Database.isSQLiteInternalTable(...) - -// Bool, true if argument is the name of an internal GRDB table -Database.isGRDBInternalTable(...) -``` - -For more information, see [`tableExists(_:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/tableexists(_:)) and related methods. - - ## Raw SQLite Pointers **If not all SQLite APIs are exposed in GRDB, you can still use the [SQLite C Interface](https://www.sqlite.org/c3ref/intro.html) and call [SQLite C functions](https://www.sqlite.org/c3ref/funclist.html).** -Those functions are embedded right into the GRDB module, regardless of the underlying SQLite implementation (system SQLite, [SQLCipher](#encryption), or [custom SQLite build]): +To access the C SQLite functions from SQLCipher or the system SQLite, you need to perform an extra import: ```swift -import GRDB +import SQLite3 // System SQLite +import SQLCipher // SQLCipher let sqliteVersion = String(cString: sqlite3_libversion()) ``` @@ -1643,28 +1641,53 @@ try dbQueue.read { db in Records ======= -**On top of the [SQLite API](#sqlite-api), GRDB provides protocols and a class** that help manipulating database rows as regular objects named "records": +**On top of the [SQLite API](#sqlite-api), GRDB provides protocols** that help manipulating database rows as regular objects named "records": ```swift try dbQueue.write { db in - if var place = try Place.fetchOne(db, id: 1) { - place.isFavorite = true - try place.update(db) + if var place = try Player.fetchOne(db, id: 1) { + player.score += 10 + try player.update(db) } } ``` -Of course, you need to open a [database connection], and [create database tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) first. +Of course, you need to open a [database connection], and [create database tables](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) first. -To define your custom records, you subclass the ready-made `Record` class, or you extend your structs and classes with protocols that come with focused sets of features: fetching methods, persistence methods, record comparison... +To define a record type, define a type and extend it with database protocols: -Extending structs with record protocols is more "swifty". Subclassing the Record class is more "classic". You can choose either way. See some [examples of record definitions](#examples-of-record-definitions), and the [list of record methods](#list-of-record-methods) for an overview. +- `FetchableRecord` makes it possible to fetch instances from the database. +- `PersistableRecord` makes it possible to save instances into the database. +- `Codable` (not mandatory) provides ready-made serialization to and from database rows. +- `Identifiable` (not mandatory) provides extra convenience database methods. -> **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. You should read [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) for a general introduction. +To make it easier to customize database requests, also nest a `Columns` enum: + +```swift +struct Player: Codable, Identifiable { + var id: Int64 + var name: String + var score: Int + var team: String? +} + +// Add database support +extension Player: FetchableRecord, PersistableRecord { + enum Columns { + static let name = Column(CodingKeys.name) + static let score = Column(CodingKeys.score) + static let team = Column(CodingKeys.team) + } +} +``` + +See more [examples of record definitions](#examples-of-record-definitions) below. + +> 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. > -> :bulb: **Tip**: after you have read this chapter, check the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) Guide. +> Tip: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices) guide provides general guidance.. > -> :bulb: **Tip**: see the [Demo Applications] for sample apps that uses records. +> Tip: See the [Demo Applications] for sample apps that uses records. **Overview** @@ -1685,27 +1708,21 @@ Extending structs with record protocols is more "swifty". Subclassing the Record - [Persistence Callbacks] - [Identifiable Records] - [Codable Records] -- [Record Class](#record-class) - [Record Comparison] - [Record Customization Options] - [Record Timestamps and Transaction Date] -**Records in a Glance** - -- [Examples of Record Definitions](#examples-of-record-definitions) -- [List of Record Methods](#list-of-record-methods) - ### Inserting Records To insert a record in the database, call the `insert` method: ```swift -let player = Player(name: "Arthur", email: "arthur@example.com") +let player = Player(id: 1, name: "Arthur", score: 1000) try player.insert(db) ``` -:point_right: `insert` is available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. +:point_right: `insert` is available for types that adopt the [PersistableRecord] protocol. ### Fetching Records @@ -1718,7 +1735,7 @@ let arthur = try Player.fetchOne(db, // Player? arguments: ["Arthur"]) let bestPlayers = try Player // [Player] - .order(Column("score").desc) + .order(\.score.desc) .limit(10) .fetchAll(db) @@ -1726,9 +1743,9 @@ let spain = try Country.fetchOne(db, id: "ES") // Country? let italy = try Country.find(db, id: "IT") // Country ``` -:point_right: Fetching from raw SQL is available for subclasses of the [Record](#record-class) class, and types that adopt the [FetchableRecord] protocol. +:point_right: Fetching from raw SQL is available for types that adopt the [FetchableRecord] protocol. -:point_right: Fetching without SQL, using the [query interface](#the-query-interface), is available for subclasses of the [Record](#record-class) class, and types that adopt both [FetchableRecord] and [TableRecord] protocol. +:point_right: Fetching without SQL, using the [query interface](#the-query-interface), is available for types that adopt both [FetchableRecord] and [TableRecord] protocol. ### Updating Records @@ -1754,11 +1771,11 @@ See the [query interface](#the-query-interface) for batch updates: ```swift try Player - .filter(Column("team") == "red") - .updateAll(db, Column("score") += 1) + .filter { $0.team == "red" } + .updateAll(db) { $0.score += 1 } ``` -:point_right: update methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. Batch updates are available on the [TableRecord] protocol. +:point_right: update methods are available for types that adopt the [PersistableRecord] protocol. Batch updates are available on the [TableRecord] protocol. ### Deleting Records @@ -1777,11 +1794,11 @@ try Player.deleteOne(db, id: 1) try Player.deleteOne(db, key: ["email": "arthur@example.com"]) try Country.deleteAll(db, ids: ["FR", "US"]) try Player - .filter(Column("email") == nil) + .filter { $0.email == nil } .deleteAll(db) ``` -:point_right: delete methods are available for subclasses of the [Record](#record-class) class, and types that adopt the [PersistableRecord] protocol. Batch deletes are available on the [TableRecord] protocol. +:point_right: delete methods are available for types that adopt the [PersistableRecord] protocol. Batch deletes are available on the [TableRecord] protocol. ### Counting Records @@ -1792,11 +1809,11 @@ To count records, call the `fetchCount` method: let playerCount: Int = try Player.fetchCount(db) let playerWithEmailCount: Int = try Player - .filter(Column("email") == nil) + .filter { $0.email == nil } .fetchCount(db) ``` -:point_right: `fetchCount` is available for subclasses of the [Record](#record-class) class, and types that adopt the [TableRecord] protocol. +:point_right: `fetchCount` is available for types that adopt the [TableRecord] protocol. Details follow: @@ -1807,11 +1824,9 @@ Details follow: - [PersistableRecord Protocol](#persistablerecord-protocol) - [Identifiable Records] - [Codable Records] -- [Record Class](#record-class) - [Record Comparison] - [Record Customization Options] - [Examples of Record Definitions](#examples-of-record-definitions) -- [List of Record Methods](#list-of-record-methods) ## Record Protocols Overview @@ -1822,6 +1837,7 @@ Details follow: ```swift struct Place: FetchableRecord { ... } + let places = try dbQueue.read { db in try Place.fetchAll(db, sql: "SELECT * FROM place") } @@ -1835,6 +1851,7 @@ Details follow: ```swift struct Place: TableRecord { ... } + let placeCount = try dbQueue.read { db in // Generates and runs `SELECT COUNT(*) FROM place` try Place.fetchCount(db) @@ -1845,8 +1862,9 @@ Details follow: ```swift struct Place: TableRecord, FetchableRecord { ... } + try dbQueue.read { db in - let places = try Place.order(Column("title")).fetchAll(db) + let places = try Place.order(\.title).fetchAll(db) let paris = try Place.fetchOne(id: 1) } ``` @@ -1855,6 +1873,7 @@ Details follow: ```swift struct Place : PersistableRecord { ... } + try dbQueue.write { db in try Place.delete(db, id: 1) try Place(...).insert(db) @@ -1868,7 +1887,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: @@ -1879,7 +1898,7 @@ protocol FetchableRecord { } ``` -**To use FetchableRecord**, subclass the [Record](#record-class) class, or adopt it explicitly. For example: +For example: ```swift struct Place { @@ -1888,23 +1907,12 @@ struct Place { var coordinate: CLLocationCoordinate2D } -extension Place : FetchableRecord { - init(row: Row) { - id = row["id"] - title = row["title"] - coordinate = CLLocationCoordinate2D( - latitude: row["latitude"], - longitude: row["longitude"]) - } -} -``` - -Rows also accept column enums: - -```swift -extension Place : FetchableRecord { - enum Columns: String, ColumnExpression { - case id, title, latitude, longitude +extension Place: FetchableRecord { + enum Columns { + static let id = Column("id") + static let title = Column("title") + static let latitude = Column("latitude") + static let longitude = Column("longitude") } init(row: Row) { @@ -1927,6 +1935,12 @@ struct Player: Decodable, FetchableRecord { var id: Int64 var name: String var score: Int + + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + static let score = Column(CodingKeys.score) + } } ``` @@ -1948,9 +1962,9 @@ 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. To use TableRecord, subclass the [Record](#record-class) class, or adopt it explicitly: +**The TableRecord protocol** generates SQL for you: ```swift protocol TableRecord { @@ -1965,6 +1979,7 @@ The `databaseTableName` type property is the name of a database table. By defaul ```swift struct Place: TableRecord { } + print(Place.databaseTableName) // prints "place" ``` @@ -1982,23 +1997,15 @@ You can still provide a custom table name: struct Place: TableRecord { static let databaseTableName = "location" } + print(Place.databaseTableName) // prints "location" ``` -Subclasses of the [Record](#record-class) class must always override their superclass's `databaseTableName` property: - -```swift -class Place: Record { - override class var databaseTableName: String { "place" } -} -print(Place.databaseTableName) // prints "place" -``` - When a type adopts both TableRecord and [FetchableRecord](#fetchablerecord-protocol), it can be fetched using the [query interface](#the-query-interface): ```swift // SELECT * FROM place WHERE name = 'Paris' -let paris = try Place.filter(nameColumn == "Paris").fetchOne(db) +let paris = try Place.filter { $0.name == "Paris" }.fetchOne(db) ``` TableRecord can also fetch deal with primary and unique keys: see [Fetching by Key](#fetching-by-key) and [Testing for Record Existence](#testing-for-record-existence). @@ -2006,7 +2013,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.** @@ -2045,16 +2052,23 @@ The `encode(to:)` method defines which [values](#values) (Bool, Int, String, Dat The optional `didInsert` method lets the adopting type store its rowID after successful insertion, and is only useful for tables that have an auto-incremented primary key. It is called from a protected dispatch queue, and serialized with all database updates. -**To use the persistable protocols**, subclass the [Record](#record-class) class, or adopt one of them explicitly. For example: +For example: ```swift -extension Place : MutablePersistableRecord { +extension Place: MutablePersistableRecord { + enum Columns { + static let id = Column("id") + static let title = Column("title") + static let latitude = Column("latitude") + static let longitude = Column("longitude") + } + /// The values persisted in the database func encode(to container: inout PersistenceContainer) { - container["id"] = id - container["title"] = title - container["latitude"] = coordinate.latitude - container["longitude"] = coordinate.longitude + container[Columns.id] = id + container[Columns.title] = title + container[Columns.latitude] = coordinate.latitude + container[Columns.longitude] = coordinate.longitude } // Update auto-incremented id upon successful insertion @@ -2072,23 +2086,6 @@ try paris.insert(db) paris.id // some value ``` -Persistence containers also accept column enums: - -```swift -extension Place : MutablePersistableRecord { - enum Columns: String, ColumnExpression { - case id, title, latitude, longitude - } - - func encode(to container: inout PersistenceContainer) { - container[Columns.id] = id - container[Columns.title] = title - container[Columns.latitude] = coordinate.latitude - container[Columns.longitude] = coordinate.longitude - } -} -``` - When your record type adopts the standard Encodable protocol, you don't have to provide the implementation for `encode(to:)`. See [Codable Records] for more information: ```swift @@ -2098,6 +2095,12 @@ struct Player: Encodable, MutablePersistableRecord { var name: String var score: Int + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + static let score = Column(CodingKeys.score) + } + // Update auto-incremented id upon successful insertion mutating func didInsert(_ inserted: InsertionSuccess) { id = inserted.rowID @@ -2108,7 +2111,7 @@ struct Player: Encodable, MutablePersistableRecord { ### Persistence Methods -[Record](#record-class) subclasses and types that adopt [PersistableRecord] are given methods that insert, update, and delete: +Types that adopt the [PersistableRecord] protocol are given methods that insert, update, and delete: ```swift // INSERT @@ -2122,7 +2125,6 @@ try place.update(db, columns: ["title"]) // Maybe UPDATE try place.updateChanges(db, from: otherPlace) try place.updateChanges(db) { $0.isFavorite = true } -try place.updateChanges(db) // Record class only // INSERT or UPDATE try place.save(db) @@ -2294,12 +2296,20 @@ struct Player: Codable, PersistableRecord, FetchableRecord { var id: Int64 var name: String var score: Int + + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + static let score = Column(CodingKeys.score) + } } // A partial player struct PartialPlayer: Encodable, PersistableRecord { static let databaseTableName = "player" var name: String + + typealias Columns = Player.Columns } ``` @@ -2310,11 +2320,10 @@ try dbQueue.write { db in let partialPlayer = PartialPlayer(name: "Alice") // INSERT INTO player (name) VALUES ('Alice') RETURNING * - if let player = try partialPlayer.insertAndFetch(db, as: Player.self) { - print(player.id) // The inserted id - print(player.name) // The inserted name - print(player.score) // The default score - } + let player = try partialPlayer.insertAndFetch(db, as: Player.self) + print(player.id) // The inserted id + print(player.name) // The inserted name + print(player.score) // The default score } ``` @@ -2325,8 +2334,10 @@ try dbQueue.write { db in let partialPlayer = PartialPlayer(name: "Alice") // INSERT INTO player (name) VALUES ('Alice') RETURNING score - let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in + let score = try partialPlayer.insertAndFetch(db) { statement in try Int.fetchOne(statement) + } select: { + [$0.score] } print(score) // Prints 1000, the default score } @@ -2354,18 +2365,20 @@ let deletedPlayers = try request.deleteAndFetchAll(db) // [Player] // Fetch a selection of columns from the deleted rows // DELETE FROM player RETURNING name -let statement = try request.deleteAndFetchStatement(db, selection: [Column("name")]) +let statement = try request.deleteAndFetchStatement(db) { [$0.name] } let deletedNames = try String.fetchSet(statement) // Fetch all updated players // UPDATE player SET score = score + 10 RETURNING * -let updatedPlayers = try request.updateAndFetchAll(db, [Column("score") += 10]) // [Player] +let updatedPlayers = try request.updateAndFetchAll(db) { [$0.score += 10] } // [Player] // Fetch a selection of columns from the updated rows // UPDATE player SET score = score + 10 RETURNING score -let statement = try request.updateAndFetchStatement( - db, [Column("score") += 10], - select: [Column("score")]) +let statement = try request.updateAndFetchStatement(db) { + [$0.score += 10] +} select: { + [$0.score] +} let updatedScores = try Int.fetchAll(statement) ``` @@ -2395,20 +2408,6 @@ try dbQueue.write { db in } ``` -When you subclass the [Record](#record-class) class, override the callback, and make sure you call `super` at some point of your implementation: - -```swift -class Player: Record { - var id: Int64? - - // Update auto-incremented id upon successful insertion - func didInsert(_ inserted: InsertionSuccess) { - super.didInsert(inserted) - id = inserted.rowID - } -} -``` - Callbacks can also help implementing record validation: ```swift @@ -2453,7 +2452,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. @@ -2461,7 +2460,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 { @@ -2488,7 +2487,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 @@ -2503,7 +2502,7 @@ try Player.deleteOne(db, id: 1) try Player.deleteAll(db, ids: [1, 2, 3]) ``` -> **Note**: `Identifiable` is not available on all application targets, and not all tables have a single-column primary key. GRDB provides other methods that deal with primary and unique keys, but they won't check the type of their arguments: +> **Note**: Not all record types can be made `Identifiable`, and not all tables have a single-column primary key. GRDB provides other methods that deal with primary and unique keys, but they won't check the type of their arguments: > > ```swift > // Available on non-Identifiable types @@ -2574,14 +2573,21 @@ Record types that adopt an archival protocol ([Codable, Encodable or Decodable]( ```swift // Declare a record... struct Player: Codable, FetchableRecord, PersistableRecord { + var id: Int64 var name: String var score: Int + + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + static let score = Column(CodingKeys.score) + } } // ...and there you go: try dbQueue.write { db in - try Player(name: "Arthur", score: 100).insert(db) - let players = try Player.fetchAll(db) + try Player(id: 1, name: "Arthur", score: 100).insert(db) + let players = try Player.order(\.score.desc).fetchAll(db) } ``` @@ -2667,7 +2673,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 @@ -2680,18 +2686,18 @@ Those behaviors can be overridden: ```swift protocol FetchableRecord { - static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { get } - static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get } + static func databaseDataDecodingStrategy(for column: String) -> DatabaseDataDecodingStrategy + static func databaseDateDecodingStrategy(for column: String) -> DatabaseDateDecodingStrategy } protocol EncodableRecord { - static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { get } - static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { get } - static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { get } + static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy + static func databaseDateEncodingStrategy(for column: String) -> DatabaseDateEncodingStrategy + static func databaseUUIDEncodingStrategy(for column: String) -> DatabaseUUIDEncodingStrategy } ``` -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). @@ -2707,7 +2713,10 @@ So make sure that those are properly encoded in your requests. For example: ```swift struct Player: Codable, FetchableRecord, PersistableRecord, Identifiable { // UUIDs are stored as strings - static let databaseUUIDEncodingStrategy = DatabaseUUIDEncodingStrategy.uppercaseString + static func databaseUUIDEncodingStrategy(for column: String) -> DatabaseUUIDEncodingStrategy { + .uppercaseString + } + var id: UUID ... } @@ -2723,10 +2732,10 @@ try dbQueue.write { db in _ = try Player.filter(id: uuid).fetchOne(db) // NOT OK: performs a blob-based query, fails to find the inserted player - _ = try Player.filter(Column("id") == uuid).fetchOne(db) + _ = try Player.filter { $0.id == uuid }.fetchOne(db) // OK: performs a string-based query, finds the inserted player - _ = try Player.filter(Column("id") == uuid.uuidString).fetchOne(db) + _ = try Player.filter { $0.id == uuid.uuidString }.fetchOne(db) } ``` @@ -2776,7 +2785,9 @@ let player = try decoder.decode(Player.self, from: jsonData) ```swift extension Player: FetchableRecord { - static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "database row"] + static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { + [decoderName: "database row"] + } } // prints "Decoded from database row" @@ -2806,65 +2817,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. - - -## Record Class - -**Record** is a class that is designed to be subclassed. It inherits its features from the [FetchableRecord, TableRecord, and PersistableRecord](#record-protocols-overview) protocols. On top of that, Record instances can compare against previous versions of themselves in order to [avoid useless updates](#record-comparison). - -Record subclasses define their custom database relationship by overriding database methods. For example: - -```swift -class Place: Record { - var id: Int64? - var title: String - var isFavorite: Bool - var coordinate: CLLocationCoordinate2D - - init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) { - self.id = id - self.title = title - self.isFavorite = isFavorite - self.coordinate = coordinate - super.init() - } - - /// The table name - override class var databaseTableName: String { "place" } - - /// The table columns - enum Columns: String, ColumnExpression { - case id, title, favorite, latitude, longitude - } - - /// Creates a record from a database row - required init(row: Row) throws { - id = row[Columns.id] - title = row[Columns.title] - isFavorite = row[Columns.favorite] - coordinate = CLLocationCoordinate2D( - latitude: row[Columns.latitude], - longitude: row[Columns.longitude]) - try super.init(row: row) - } - - /// The values persisted in the database - override func encode(to container: inout PersistenceContainer) throws { - container[Columns.id] = id - container[Columns.title] = title - container[Columns.favorite] = isFavorite - container[Columns.latitude] = coordinate.latitude - container[Columns.longitude] = coordinate.longitude - } - - /// Update record ID after a successful insertion - override func didInsert(_ inserted: InsertionSuccess) { - super.didInsert(inserted) - id = inserted.rowID - } -} -``` +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 @@ -2915,23 +2868,6 @@ The `updateChanges` methods perform a database update of the changed columns onl } ``` -- `updateChanges(_:)` (Record class only) - - Instances of the [Record](#record-class) class are able to compare against themselves, and know if they have changes that have not been saved since the last fetch or saving: - - ```swift - // Record class only - if let player = try Player.fetchOne(db, id: 42) { - player.score = 100 - if try player.updateChanges(db) { - print("player was modified, and updated in the database") - } else { - print("player was not modified, and database was not hit") - } - } - ``` - - ### The `databaseEquals` Method This method returns whether two records have the same database representation: @@ -2960,46 +2896,6 @@ for (column, oldValue) in try newPlayer.databaseChanges(from: oldPlayer) { // prints "score was 100" ``` -The [Record](#record-class) class is able to compare against itself: - -```swift -// Record class only -let player = Player(id: 1, name: "Arthur", score: 100) -try player.insert(db) -player.score = 1000 -for (column, oldValue) in try player.databaseChanges { - print("\(column) was \(oldValue)") -} -// prints "score was 100" -``` - -[Record](#record-class) instances also have a `hasDatabaseChanges` property: - -```swift -// Record class only -player.score = 1000 -if player.hasDatabaseChanges { - try player.save(db) -} -``` - -`Record.hasDatabaseChanges` is false after a Record instance has been fetched or saved into the database. Subsequent modifications may set it, or not: `hasDatabaseChanges` is based on value comparison. **Setting a property to the same value does not set the changed flag**: - -```swift -let player = Player(name: "Barbara", score: 750) -player.hasDatabaseChanges // true - -try player.insert(db) -player.hasDatabaseChanges // false - -player.name = "Barbara" -player.hasDatabaseChanges // false - -player.score = 1000 -player.hasDatabaseChanges // true -try player.databaseChanges // ["score": 750] -``` - For an efficient algorithm which synchronizes the content of a database table with a JSON payload, check [groue/SortedDifference](https://github.com/groue/SortedDifference). @@ -3088,19 +2984,20 @@ struct Player : MutablePersistableRecord { try player.insert(db) ``` -> **Note**: If you specify the `ignore` policy for inserts, the [`didInsert` callback](#persistence-callbacks) will be called with some random id in case of failed insert. You can detect failed insertions with `insertAndFetch`: +> **Note**: If you specify the `ignore` policy for inserts, the [`didInsert` callback](#persistence-callbacks) will be called with some random id in case of failed insert. You can detect failed insertions with `insertAndFetch`: > > ```swift > // How to detect failed `INSERT OR IGNORE`: > // INSERT OR IGNORE INTO player ... RETURNING * -> if let insertedPlayer = try player.insertAndFetch(db) { +> do { +> let insertedPlayer = try player.insertAndFetch(db) { > // Succesful insertion -> } else { -> // Ignored failure +> catch RecordError.recordNotFound { +> // Failed insertion due to IGNORE policy > } > ``` > -> **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 @@ -3201,8 +3098,12 @@ struct Place { // SQL generation extension Place: TableRecord { /// The table columns - enum Columns: String, ColumnExpression { - case id, title, isFavorite, latitude, longitude + enum Columns { + static let id = Column("id") + static let title = Column("title") + static let isFavorite = Column("isFavorite") + static let latitude = Column("latitude") + static let longitude = Column("longitude") } } @@ -3279,12 +3180,15 @@ extension Place: TableRecord { } /// Arrange the selected columns and lock their order - static let databaseSelection: [any SQLSelectable] = [ - Columns.id, - Columns.title, - Columns.favorite, - Columns.latitude, - Columns.longitude] + static var databaseSelection: [any SQLSelectable] { + [ + Columns.id, + Columns.title, + Columns.favorite, + Columns.latitude, + Columns.longitude, + ] + } } // Fetching methods @@ -3313,241 +3217,6 @@ extension Place: MutablePersistableRecord { -
- Subclass the Record class - -See the [Record class](#record-class) for more information. - -```swift -class Place: Record { - var id: Int64? - var title: String - var isFavorite: Bool - var coordinate: CLLocationCoordinate2D - - init(id: Int64?, title: String, isFavorite: Bool, coordinate: CLLocationCoordinate2D) { - self.id = id - self.title = title - self.isFavorite = isFavorite - self.coordinate = coordinate - super.init() - } - - /// The table name - override class var databaseTableName: String { "place" } - - /// The table columns - enum Columns: String, ColumnExpression { - case id, title, isFavorite, latitude, longitude - } - - /// Creates a record from a database row - required init(row: Row) throws { - id = row[Columns.id] - title = row[Columns.title] - isFavorite = row[Columns.isFavorite] - coordinate = CLLocationCoordinate2D( - latitude: row[Columns.latitude], - longitude: row[Columns.longitude]) - try super.init(row: row) - } - - /// The values persisted in the database - override func encode(to container: inout PersistenceContainer) throws { - container[Columns.id] = id - container[Columns.title] = title - container[Columns.isFavorite] = isFavorite - container[Columns.latitude] = coordinate.latitude - container[Columns.longitude] = coordinate.longitude - } - - // Update auto-incremented id upon successful insertion - override func didInsert(_ inserted: InsertionSuccess) { - super.didInsert(inserted) - id = inserted.rowID - } -} -``` - -
- - -## List of Record Methods - -This is the list of record methods, along with their required protocols. The [Record](#record-class) class adopts all these protocols, and adds a few extra methods. - -| Method | Protocols | Notes | -| ------ | --------- | :---: | -| **Core Methods** | | | -| `init(row:)` | [FetchableRecord] | | -| `Type.databaseTableName` | [TableRecord] | | -| `Type.databaseSelection` | [TableRecord] | [*](#columns-selected-by-a-request) | -| `Type.persistenceConflictPolicy` | [PersistableRecord] | [*](#conflict-resolution) | -| `record.encode(to:)` | [EncodableRecord] | | -| **Insert and Update Records** | | | -| `record.insert(db)` | [PersistableRecord] | | -| `record.insertAndFetch(db)` | [PersistableRecord] & [FetchableRecord] | | -| `record.insertAndFetch(_:as:)` | [PersistableRecord] | | -| `record.insertAndFetch(_:selection:fetch:)` | [PersistableRecord] | | -| `record.inserted(db)` | [PersistableRecord] | | -| `record.save(db)` | [PersistableRecord] | | -| `record.saveAndFetch(db)` | [PersistableRecord] & [FetchableRecord] | | -| `record.saveAndFetch(_:as:)` | [PersistableRecord] | | -| `record.saveAndFetch(_:selection:fetch:)` | [PersistableRecord] | | -| `record.saved(db)` | [PersistableRecord] | | -| `record.update(db)` | [PersistableRecord] | | -| `record.updateAndFetch(db)` | [PersistableRecord] & [FetchableRecord] | | -| `record.updateAndFetch(_:as:)` | [PersistableRecord] | | -| `record.updateAndFetch(_:selection:fetch:)` | [PersistableRecord] | | -| `record.update(db, columns:...)` | [PersistableRecord] | | -| `record.updateAndFetch(_:columns:selection:fetch:)` | [PersistableRecord] | | -| `record.updateChanges(db, from:...)` | [PersistableRecord] | [*](#record-comparison) | -| `record.updateChanges(db) { ... }` | [PersistableRecord] | [*](#record-comparison) | -| `record.updateChangesAndFetch(_:columns:as:modify:)` | [PersistableRecord] | | -| `record.updateChangesAndFetch(_:columns:selection:fetch:modify:)` | [PersistableRecord] | | -| `record.updateChanges(db)` | [Record](#record-class) | [*](#record-comparison) | -| `record.upsert(db)` | [PersistableRecord] | | -| `record.upsertAndFetch(db)` | [PersistableRecord] & [FetchableRecord] | | -| `record.upsertAndFetch(_:as:)` | [PersistableRecord] | | -| `Type.updateAll(db, ...)` | [TableRecord] | | -| `Type.filter(...).updateAll(db, ...)` | [TableRecord] | ² | -| **Delete Records** | | | -| `record.delete(db)` | [PersistableRecord] | | -| `Type.deleteOne(db, key:...)` | [TableRecord] | ¹ | -| `Type.deleteOne(db, id:...)` | [TableRecord] & [Identifiable] | ¹ | -| `Type.deleteAll(db)` | [TableRecord] | | -| `Type.deleteAll(db, keys:...)` | [TableRecord] | ¹ | -| `Type.deleteAll(db, ids:...)` | [TableRecord] & [Identifiable] | ¹ | -| `Type.filter(...).deleteAll(db)` | [TableRecord] | ² | -| **Persistence Callbacks** | | | -| `record.willInsert(_:)` | [PersistableRecord] | | -| `record.aroundInsert(_:insert:)` | [PersistableRecord] | | -| `record.didInsert(_:)` | [PersistableRecord] | | -| `record.willUpdate(_:columns:)` | [PersistableRecord] | | -| `record.aroundUpdate(_:columns:update:)` | [PersistableRecord] | | -| `record.didUpdate(_:)` | [PersistableRecord] | | -| `record.willSave(_:)` | [PersistableRecord] | | -| `record.aroundSave(_:save:)` | [PersistableRecord] | | -| `record.didSave(_:)` | [PersistableRecord] | | -| `record.willDelete(_:)` | [PersistableRecord] | | -| `record.aroundDelete(_:delete:)` | [PersistableRecord] | | -| `record.didDelete(deleted:)` | [PersistableRecord] | | -| **Check Record Existence** | | | -| `record.exists(db)` | [PersistableRecord] | | -| `Type.exists(db, key: ...)` | [TableRecord] | ¹ | -| `Type.exists(db, id: ...)` | [TableRecord] & [Identifiable] | ¹ | -| `Type.filter(...).isEmpty(db)` | [TableRecord] | ² | -| **Convert Record to Dictionary** | | | -| `record.databaseDictionary` | [EncodableRecord] | | -| **Count Records** | | | -| `Type.fetchCount(db)` | [TableRecord] | | -| `Type.filter(...).fetchCount(db)` | [TableRecord] | ² | -| **Fetch Record [Cursors](#cursors)** | | | -| `Type.fetchCursor(db)` | [FetchableRecord] & [TableRecord] | | -| `Type.fetchCursor(db, keys:...)` | [FetchableRecord] & [TableRecord] | ¹ | -| `Type.fetchCursor(db, ids:...)` | [FetchableRecord] & [TableRecord] & [Identifiable] | ¹ | -| `Type.fetchCursor(db, sql: sql)` | [FetchableRecord] | ³ | -| `Type.fetchCursor(statement)` | [FetchableRecord] | ⁴ | -| `Type.filter(...).fetchCursor(db)` | [FetchableRecord] & [TableRecord] | ² | -| **Fetch Record Arrays** | | | -| `Type.fetchAll(db)` | [FetchableRecord] & [TableRecord] | | -| `Type.fetchAll(db, keys:...)` | [FetchableRecord] & [TableRecord] | ¹ | -| `Type.fetchAll(db, ids:...)` | [FetchableRecord] & [TableRecord] & [Identifiable] | ¹ | -| `Type.fetchAll(db, sql: sql)` | [FetchableRecord] | ³ | -| `Type.fetchAll(statement)` | [FetchableRecord] | ⁴ | -| `Type.filter(...).fetchAll(db)` | [FetchableRecord] & [TableRecord] | ² | -| **Fetch Record Sets** | | | -| `Type.fetchSet(db)` | [FetchableRecord] & [TableRecord] | | -| `Type.fetchSet(db, keys:...)` | [FetchableRecord] & [TableRecord] | ¹ | -| `Type.fetchSet(db, ids:...)` | [FetchableRecord] & [TableRecord] & [Identifiable] | ¹ | -| `Type.fetchSet(db, sql: sql)` | [FetchableRecord] | ³ | -| `Type.fetchSet(statement)` | [FetchableRecord] | ⁴ | -| `Type.filter(...).fetchSet(db)` | [FetchableRecord] & [TableRecord] | ² | -| **Fetch Individual Records** | | | -| `Type.fetchOne(db)` | [FetchableRecord] & [TableRecord] | | -| `Type.fetchOne(db, key:...)` | [FetchableRecord] & [TableRecord] | ¹ | -| `Type.fetchOne(db, id:...)` | [FetchableRecord] & [TableRecord] & [Identifiable] | ¹ | -| `Type.fetchOne(db, sql: sql)` | [FetchableRecord] | ³ | -| `Type.fetchOne(statement)` | [FetchableRecord] | ⁴ | -| `Type.filter(...).fetchOne(db)` | [FetchableRecord] & [TableRecord] | ² | -| `Type.find(db, key:...)` | [FetchableRecord] & [TableRecord] | ¹ | -| `Type.find(db, id:...)` | [FetchableRecord] & [TableRecord] & [Identifiable] | ¹ | -| **[Codable Records]** | | | -| `Type.databaseDecodingUserInfo` | [FetchableRecord] | [*](#the-userinfo-dictionary) | -| `Type.databaseJSONDecoder(for:)` | [FetchableRecord] | [*](#json-columns) | -| `Type.databaseDateDecodingStrategy` | [FetchableRecord] | [*](#data-date-and-uuid-coding-strategies) | -| `Type.databaseEncodingUserInfo` | [EncodableRecord] | [*](#the-userinfo-dictionary) | -| `Type.databaseJSONEncoder(for:)` | [EncodableRecord] | [*](#json-columns) | -| `Type.databaseDateEncodingStrategy` | [EncodableRecord] | [*](#data-date-and-uuid-coding-strategies) | -| `Type.databaseUUIDEncodingStrategy` | [EncodableRecord] | [*](#data-date-and-uuid-coding-strategies) | -| **Define [Associations]** | | | -| `Type.belongsTo(...)` | [TableRecord] | [*](Documentation/AssociationsBasics.md) | -| `Type.hasMany(...)` | [TableRecord] | [*](Documentation/AssociationsBasics.md) | -| `Type.hasOne(...)` | [TableRecord] | [*](Documentation/AssociationsBasics.md) | -| `Type.hasManyThrough(...)` | [TableRecord] | [*](Documentation/AssociationsBasics.md) | -| `Type.hasOneThrough(...)` | [TableRecord] | [*](Documentation/AssociationsBasics.md) | -| **Building Query Interface [Requests](#requests)** | | | -| `record.request(for:...)` | [TableRecord] & [EncodableRecord] | [*](Documentation/AssociationsBasics.md) | -| `Type.all()` | [TableRecord] | ² | -| `Type.none()` | [TableRecord] | ² | -| `Type.select(...)` | [TableRecord] | ² | -| `Type.select(..., as:...)` | [TableRecord] | ² | -| `Type.selectPrimaryKey(as:...)` | [TableRecord] | ² | -| `Type.annotated(with:...)` | [TableRecord] | ² | -| `Type.filter(...)` | [TableRecord] | ² | -| `Type.filter(id:)` | [TableRecord] & Identifiable | [*](#identifiable-records) | -| `Type.filter(ids:)` | [TableRecord] & Identifiable | [*](#identifiable-records) | -| `Type.matching(...)` | [TableRecord] | ² | -| `Type.including(all:)` | [TableRecord] | ² | -| `Type.including(optional:)` | [TableRecord] | ² | -| `Type.including(required:)` | [TableRecord] | ² | -| `Type.joining(optional:)` | [TableRecord] | ² | -| `Type.joining(required:)` | [TableRecord] | ² | -| `Type.group(...)` | [TableRecord] | ² | -| `Type.groupByPrimaryKey()` | [TableRecord] | ² | -| `Type.having(...)` | [TableRecord] | ² | -| `Type.order(...)` | [TableRecord] | ² | -| `Type.orderByPrimaryKey()` | [TableRecord] | ² | -| `Type.limit(...)` | [TableRecord] | ² | -| `Type.with(...)` | [TableRecord] | ² | -| **[Record Comparison]** | | | -| `record.databaseEquals(...)` | [EncodableRecord] | | -| `record.databaseChanges(from:...)` | [EncodableRecord] | | -| `record.updateChanges(db, from:...)` | [PersistableRecord] | | -| `record.updateChanges(db) { ... }` | [PersistableRecord] | | -| `record.hasDatabaseChanges` | [Record](#record-class) | | -| `record.databaseChanges` | [Record](#record-class) | | -| `record.updateChanges(db)` | [Record](#record-class) | | - -¹ All unique keys are supported: primary keys (single-column, composite, [`rowid`](https://www.sqlite.org/rowidtable.html)) and unique indexes: - -```swift -try Player.fetchOne(db, id: 1) // Player? -try Player.fetchOne(db, key: ["email": "arthur@example.com"]) // Player? -try Country.fetchAll(db, keys: ["FR", "US"]) // [Country] -``` - -² See [Fetch Requests](#requests): - -```swift -let request = Player.filter(emailColumn != nil).order(nameColumn) -let players = try request.fetchAll(db) // [Player] -let count = try request.fetchCount(db) // Int -``` - -³ See [SQL queries](#fetch-queries): - -```swift -let player = try Player.fetchOne(db, sql: "SELECT * FROM player WHERE id = ?", arguments: [1]) // Player? -``` - -⁴ See [`Statement`]: - -```swift -let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?") -let player = try Player.fetchOne(statement, arguments: [1]) // Player? -``` - The Query Interface =================== @@ -3557,27 +3226,27 @@ The Query Interface ```swift try dbQueue.write { db in // Update database schema - try db.create(table: "wine") { t in ... } + try db.create(table: "player") { t in ... } // Fetch records - let wines = try Wine - .filter(originColumn == "Burgundy") - .order(priceColumn) + let bestPlayers = try Player + .order(\.score.desc) + .limit(10) .fetchAll(db) // Count - let count = try Wine - .filter(colorColumn == Color.red) + let count = try Player + .filter { $0.score >= 1000 } .fetchCount(db) - // Update - try Wine - .filter(originColumn == "Burgundy") - .updateAll(db, priceColumn *= 0.75) + // Batch update + try Player + .filter { $0.team == "Reds" } + .updateAll(db) { $0.score += 100 } - // Delete - try Wine - .filter(corkedColumn == true) + // Batch delete + try Player + .filter { $0.score == 0 } .deleteAll(db) } ``` @@ -3589,23 +3258,24 @@ Please bear in mind that the query interface can not generate all possible SQL q ```swift try dbQueue.write { db in // Update database schema (with SQL) - try db.execute(sql: "CREATE TABLE wine (...)") + try db.execute(sql: "CREATE TABLE player (...)") // Fetch records (with SQL) - let wines = try Wine.fetchAll(db, - sql: "SELECT * FROM wine WHERE origin = ? ORDER BY price", - arguments: ["Burgundy"]) + let bestPlayers = try Player.fetchAll(db, sql: """ + SELECT * FROM player ORDER BY score DESC LIMIT 10 + """) // Count (with an SQL snippet) - let count = try Wine - .filter(sql: "color = ?", arguments: [Color.red]) + let minScore = 1000 + let count = try Player + .filter(sql: "score >= ?", arguments: [minScore]) .fetchCount(db) // Update (with SQL) - try db.execute(sql: "UPDATE wine SET price = price * 0.75 WHERE origin = 'Burgundy'") + try db.execute(sql: "UPDATE player SET score = score + 100 WHERE team = 'Reds'") // Delete (with SQL) - try db.execute(sql: "DELETE FROM wine WHERE corked") + try db.execute(sql: "DELETE FROM player WHERE score = 0") } ``` @@ -3613,7 +3283,7 @@ So don't miss the [SQL API](#sqlite-api). > **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output. -- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) +- [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) - [Requests](#requests) - [Expressions](#expressions) - [SQL Operators](#sql-operators) @@ -3632,20 +3302,20 @@ 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: ```swift -let request = Player.filter(emailColumn != nil).order(nameColumn) +let request = Player.filter { $0.email != nil }.order(\.name) let players = try request.fetchAll(db) // [Player] let count = try request.fetchCount(db) // Int ``` -Query interface requests usually start from **a type** that adopts the `TableRecord` protocol, such as a `Record` subclass (see [Records](#records)): +Query interface requests usually start from **a type** that adopts the `TableRecord` protocol: ```swift -class Player: Record { ... } +struct Player: TableRecord { ... } // The request for all players: let request = Player.all() @@ -3668,27 +3338,31 @@ let players = try request.fetchAll(db) // [Player] > **Note**: all examples in the documentation below use a record type, but you can always substitute a `Table` instead. -Next, declare the table **columns** that you want to use for filtering, or sorting: +Next, declare the table **columns** that you want to use for filtering, or sorting, in a nested type named `Columns`: ```swift -let idColumn = Column("id") -let nameColumn = Column("name") +extension Player { + enum Columns { + static let id = Column("id") + static let name = Column("name") + } +} ``` -You can also declare column enums, if you prefer: +When `Player` is `Codable`, you'll prefer defining columns from coding keys: ```swift -// Columns.id and Columns.name can be used just as -// idColumn and nameColumn declared above. -enum Columns: String, ColumnExpression { - case id - case name +extension Player { + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + } } ``` 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 @@ -3697,21 +3371,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(_:)-ruzy) and [`select(..., as:)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/queryinterfacerequest/select(_:as:)-58954) define the selected columns. See [Columns Selected by a Request]. ```swift // SELECT name FROM player - Player.select(nameColumn, as: String.self) + Player.select(\.name, 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 { $0.name != nil }.selectID() + ``` + +- [`annotated(with: expression...)`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/selectionrequest/annotated(with:)-1satx) extends the selection. ```swift // SELECT *, (score + bonus) AS total FROM player - Player.annotated(with: (scoreColumn + bonusColumn).forKey("total")) + Player.annotated { ($0.score + $0.bonus).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 @@ -3721,33 +3405,33 @@ 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 // FROM player // JOIN team ON team.id = player.teamId - Player.annotated(withRequired: Player.team.select(colorColumn)) + Player.annotated(withRequired: Player.team.select(\.color)) ``` -- [`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() + Player.select(\.name, 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(_:)-6xr3d) applies conditions. ```swift // SELECT * FROM player WHERE id IN (1, 2, 3) - Player.filter([1,2,3].contains(idColumn)) + Player.filter { [1,2,3].contains($0.id) } // SELECT * FROM player WHERE (name IS NOT NULL) AND (height > 1.75) - Player.filter(nameColumn != nil && heightColumn > 1.75) + Player.filter { $0.name != nil && $0.height > 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 @@ -3757,7 +3441,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 @@ -3773,7 +3457,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' @@ -3783,26 +3467,26 @@ 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(_:)-2g7br) groups rows. ```swift // SELECT name, MAX(score) FROM player GROUP BY name Player - .select(nameColumn, max(scoreColumn)) - .group(nameColumn) + .select { [$0.name, max($0.score)] } + .group(\.name) ``` -- [`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(_:)-2oggh) applies conditions on grouped rows. ```swift // SELECT team, MAX(score) FROM player GROUP BY team HAVING MIN(score) >= 1000 Player - .select(teamColumn, max(scoreColumn)) - .group(teamColumn) - .having(min(scoreColumn) >= 1000) + .select { [$0.team, max($0.score)] } + .group(\.team) + .having { min($0.score) >= 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.* @@ -3813,35 +3497,38 @@ 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(_:)-9d0hr) sorts. ```swift // SELECT * FROM player ORDER BY name - Player.order(nameColumn) + Player.order(\.name) + + // SELECT * FROM player ORDER BY score DESC + Player.order(\.score.desc) // SELECT * FROM player ORDER BY score DESC, name - Player.order(scoreColumn.desc, nameColumn) + Player.order { [$0.score.desc, $0.name] } ``` SQLite considers NULL values to be smaller than any other values for sorting purposes. Hence, NULLs naturally appear at the beginning of an ascending ordering and at the end of a descending ordering. With a [custom SQLite build], this can be changed using `.ascNullsLast` and `.descNullsFirst`: ```swift // SELECT * FROM player ORDER BY score ASC NULLS LAST - Player.order(nameColumn.ascNullsLast) + Player.order(\.name.ascNullsLast) ``` Each `order` call clears any previous ordering: ```swift // SELECT * FROM player ORDER BY name - Player.order(scoreColumn).order(nameColumn) + Player.order(\.score).order(\.name) ``` -- [`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 - Player.order(scoreColumn.desc, nameColumn).reversed() + Player.order { [$0.score.desc, $0.name] }.reversed() ``` If no ordering was already specified, this method has no effect: @@ -3851,7 +3538,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 @@ -3861,7 +3548,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.* @@ -3870,7 +3557,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 @@ -3880,7 +3567,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 @@ -3893,7 +3580,7 @@ You can now build requests with the following methods: `all`, `none`, `select`, Citizenship.selectPrimaryKey(as: Row.self) // QueryInterfaceRequest ``` - - [`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 @@ -3906,31 +3593,31 @@ 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: ```swift // SELECT * FROM player WHERE (email IS NOT NULL) ORDER BY name -Player.order(nameColumn).filter(emailColumn != nil) +Player.order(\.name).filter { $0.email != nil } ``` The `select`, `order`, `group`, and `limit` methods ignore and replace previously applied selection, orderings, grouping, and limits. On the opposite, `filter`, `matching`, and `having` methods extend the query: ```swift Player // SELECT * FROM player - .filter(nameColumn != nil) // WHERE (name IS NOT NULL) - .filter(emailColumn != nil) // AND (email IS NOT NULL) - .order(nameColumn) // - ignored - + .filter { $0.name != nil } // WHERE (name IS NOT NULL) + .filter { $0.email != nil } // AND (email IS NOT NULL) + .order(\.name) // - ignored - .reversed() // - ignored - - .order(scoreColumn) // ORDER BY score + .order(\.score) // ORDER BY score .limit(20, offset: 40) // - ignored - .limit(10) // LIMIT 10 ``` -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) @@ -3960,28 +3647,54 @@ let request = table.all() The `select(...)` and `select(..., as:)` methods change the selection of a single request (see [Fetching from Requests] for detailed information): ```swift -let request = Player.select(max(Column("score"))) +let request = Player.select { max($0.score) } let maxScore = try Int.fetchOne(db, request) // Int? -let request = Player.select(max(Column("score")), as: Int.self) +let request = Player.select({ max($0.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 -struct RestrictedPlayer : TableRecord { +// Select a limited set of columns +struct RestrictedPlayer: TableRecord { static let databaseTableName = "player" - static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")] -} - -struct ExtendedPlayer : TableRecord { - static let databaseTableName = "player" - static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] + + enum Columns { + static let id = Column("id") + static let name = Column("name") + } + + static var databaseSelection: [any SQLSelectable] { + [Columns.id, Columns.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 and more +struct ExtendedPlayer : TableRecord { + static let databaseTableName = "player" + static var databaseSelection: [any SQLSelectable] { + [.allColumns, .rowID] + } +} // SELECT *, rowid FROM player let request = ExtendedPlayer.all() @@ -3997,7 +3710,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. @@ -4007,28 +3720,28 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli ```swift // SELECT * FROM player WHERE (name = 'Arthur') - Player.filter(nameColumn == "Arthur") + Player.filter { $0.name == "Arthur" } // SELECT * FROM player WHERE (name IS NULL) - Player.filter(nameColumn == nil) + Player.filter { $0.name == nil } // SELECT * FROM player WHERE (score IS 1000) - Player.filter(scoreColumn === 1000) + Player.filter { $0.score === 1000 } // SELECT * FROM rectangle WHERE width < height - Rectangle.filter(widthColumn < heightColumn) + Rectangle.filter { $0.width < $0.height } ``` Subqueries are supported: ```swift // SELECT * FROM player WHERE score = (SELECT max(score) FROM player) - let maximumScore = Player.select(max(scoreColumn)) - Player.filter(scoreColumn == maximumScore) + let maximumScore = Player.select { max($0.score) } + Player.filter { $0.score == maximumScore } // SELECT * FROM player WHERE score = (SELECT max(score) FROM player) let maximumScore = SQLRequest("SELECT max(score) FROM player") - Player.filter(scoreColumn == maximumScore) + Player.filter { $0.score == maximumScore } ``` > **Note**: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See [string comparison](#string-comparison) if you need more control. @@ -4039,7 +3752,7 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli ```swift // SELECT ((temperature * 1.8) + 32) AS fahrenheit FROM planet - Planet.select((temperatureColumn * 1.8 + 32).forKey("fahrenheit")) + Planet.select { ($0.temperature * 1.8 + 32).forKey("fahrenheit") } ``` > **Note**: an expression like `nameColumn + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. See the `concat` operator below. @@ -4048,11 +3761,9 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli ```swift // SELECT score + bonus + 1000 FROM player - let values = [ - scoreColumn, - bonusColumn, - 1000.databaseValue] - Player.select(values.joined(operator: .add)) + Player.select { + [$0.score, $0.bonus, 1000.databaseValue].joined(operator: .add) + } ``` Note in the example above how you concatenate raw values: `1000.databaseValue`. A plain `1000` would not compile. @@ -4065,7 +3776,7 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli ```swift // SELECT mask & 2 AS isRocky FROM planet - Planet.select((Column("mask") & 2).forKey("isRocky")) + Planet.select { ($0.mask & 2).forKey("isRocky") } ``` - `||` @@ -4074,7 +3785,9 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli ```swift // SELECT firstName || ' ' || lastName FROM player - Player.select([firstNameColumn, " ".databaseValue, lastNameColumn].joined(operator: .concat)) + Player.select { + [$0.firstName, " ".databaseValue, $0.lastName].joined(operator: .concat) + } ``` Note in the example above how you concatenate raw strings: `" ".databaseValue`. A plain `" "` would not compile. @@ -4086,30 +3799,20 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli The SQL logical operators are derived from the Swift `&&`, `||` and `!`: ```swift - // SELECT * FROM player WHERE ((NOT verified) OR (score < 1000)) - Player.filter(!verifiedColumn || scoreColumn < 1000) + // SELECT * FROM player WHERE ((NOT isVerified) OR (score < 1000)) + Player.filter { !$0.isVerified || $0.score < 1000 } ``` When you want to join a sequence of expressions with the `AND` or `OR` operator, use `joined(operator:)`: ```swift - // SELECT * FROM player WHERE (verified AND (score >= 1000) AND (name IS NOT NULL)) - let conditions = [ - verifiedColumn, - scoreColumn >= 1000, - nameColumn != nil] - Player.filter(conditions.joined(operator: .and)) + // SELECT * FROM player WHERE (isVerified AND (score >= 1000) AND (name IS NOT NULL)) + Player.filter { + [$0.isVerified, $0.score >= 1000, $0.name != nil].joined(operator: .and) + } ``` When the sequence is empty, `joined(operator: .and)` returns true, and `joined(operator: .or)` returns false: - - ```swift - // SELECT * FROM player WHERE 1 - Player.filter([].joined(operator: .and)) - - // SELECT * FROM player WHERE 0 - Player.filter([].joined(operator: .or)) - ``` - `BETWEEN`, `IN`, `NOT IN` @@ -4117,34 +3820,34 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli ```swift // SELECT * FROM player WHERE id IN (1, 2, 3) - Player.filter([1, 2, 3].contains(idColumn)) + Player.filter { [1, 2, 3].contains($0.id) } // SELECT * FROM player WHERE id NOT IN (1, 2, 3) - Player.filter(![1, 2, 3].contains(idColumn)) + Player.filter { ![1, 2, 3].contains($0.id) } // SELECT * FROM player WHERE score BETWEEN 0 AND 1000 - Player.filter((0...1000).contains(scoreColumn)) + Player.filter { (0...1000).contains($0.score) } // SELECT * FROM player WHERE (score >= 0) AND (score < 1000) - Player.filter((0..<1000).contains(scoreColumn)) + Player.filter { (0..<1000).contains($0.score) } // SELECT * FROM player WHERE initial BETWEEN 'A' AND 'N' - Player.filter(("A"..."N").contains(initialColumn)) + Player.filter { ("A"..."N").contains($0.initial) } // SELECT * FROM player WHERE (initial >= 'A') AND (initial < 'N') - Player.filter(("A"..<"N").contains(initialColumn)) + Player.filter { ("A"..<"N").contains($0.initial) } ``` To check inclusion inside a subquery, call the `contains` method as well: ```swift // SELECT * FROM player WHERE id IN (SELECT playerId FROM playerSelection) - let selectedPlayerIds = PlayerSelection.select(playerIdColumn) - Player.filter(selectedPlayerIds.contains(idColumn)) + let selectedPlayerIds = PlayerSelection.select(\.playerId) + Player.filter { selectedPlayerIds.contains($0.id) } // SELECT * FROM player WHERE id IN (SELECT playerId FROM playerSelection) let selectedPlayerIds = SQLRequest("SELECT playerId FROM playerSelection") - Player.filter(selectedPlayerIds.contains(idColumn)) + Player.filter { selectedPlayerIds.contains($0.id) } ``` To check inclusion inside a [common table expression], call the `contains` method as well: @@ -4155,7 +3858,7 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli let cte = CommonTableExpression(named: "selectedName", ...) Player .with(cte) - .filter(cte.contains(nameColumn)) + .filter { cte.contains($0.name) } ``` > **Note**: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See [string comparison](#string-comparison) if you need more control. @@ -4168,15 +3871,15 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli // Teams that have at least one other player // // SELECT * FROM team - // WHERE EXISTS (SELECT * FROM player WHERE teamID = team.id) - let teamAlias = TableAlias() - let player = Player.filter(Column("teamID") == teamAlias[Column("id")]) + // WHERE EXISTS (SELECT * FROM player WHERE teamId = team.id) + let teamAlias = TableAlias() + let player = Player.filter { $0.teamId == teamAlias.id } let teams = Team.aliased(teamAlias).filter(player.exists()) // Teams that have no player // // SELECT * FROM team - // WHERE NOT EXISTS (SELECT * FROM player WHERE teamID = team.id) + // WHERE NOT EXISTS (SELECT * FROM player WHERE teamId = team.id) let teams = Team.aliased(teamAlias).filter(!player.exists()) ``` @@ -4189,8 +3892,8 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli // // SELECT coach.* FROM player coach // WHERE EXISTS (SELECT * FROM player WHERE coachId = coach.id) - let coachAlias = TableAlias(name: "coach") - let coachedPlayer = Player.filter(Column("coachId") == coachAlias[Column("id")]) + let coachAlias = TableAlias(name: "coach") + let coachedPlayer = Player.filter { $0.coachId == coachAlias.id } let coaches = Player.aliased(coachAlias).filter(coachedPlayer.exists()) ``` @@ -4199,7 +3902,7 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli ```swift // SELECT coach.* FROM player coach // WHERE EXISTS (SELECT * FROM player WHERE coachId = coach.id) - let coachedPlayer = SQLRequest("SELECT * FROM player WHERE coachId = \(coachAlias[Column("id")])") + let coachedPlayer = SQLRequest("SELECT * FROM player WHERE coachId = \(coachAlias.id)") let coaches = Player.aliased(coachAlias).filter(coachedPlayer.exists()) ``` @@ -4209,10 +3912,10 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli ```swift // SELECT * FROM player WHERE (email LIKE '%@example.com') - Player.filter(emailColumn.like("%@example.com")) + Player.filter { $0.email.like("%@example.com") } // SELECT * FROM book WHERE (title LIKE '%10\%%' ESCAPE '\') - Player.filter(emailColumn.like("%10\\%%", escape: "\\")) + Player.filter { $0.email.like("%10\\%%", escape: "\\") } ``` > **Note**: the SQLite LIKE operator is case-insensitive but not Unicode-aware. For example, the expression `'a' LIKE 'A'` is true but `'æ' LIKE 'Æ'` is false. @@ -4230,7 +3933,7 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli Document.matching(pattern) // SELECT * FROM document WHERE content MATCH 'sqlite database' - Document.filter(contentColumn.match(pattern)) + Document.filter { $0.content.match(pattern) } ``` FTS5: @@ -4248,7 +3951,7 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli ```swift // SELECT (score + bonus) AS total // FROM player - Player.select((Column("score") + Column("bonus")).forKey("total")) + Player.select { ($0.score + $0.bonus).forKey("total") } ``` If you need to refer to this aliased column in another place of the request, use a detached column: @@ -4258,35 +3961,35 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli // FROM player // ORDER BY total Player - .select((Column("score") + Column("bonus")).forKey("total")) + .select { ($0.score + $0.bonus).forKey("total") } .order(Column("total").detached) ``` - Unlike `Column("total")`, the detached column `Column("total").detached` is never associated to the "player" table, so it is always rendered as `total` in the generated SQL, even when the request involves other tables via an [association](Documentation/AssociationsBasics.md) or a [common table expression]. + The detached column `Column("total").detached` is not considered as a part of the "player" table, so it is always rendered as `total` in the generated SQL, even when the request involves other tables via an [association](Documentation/AssociationsBasics.md) or a [common table expression]. ### SQL Functions -📖 [`SQLSpecificExpressible`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/sqlspecificexpressible) +📖 [`SQLSpecificExpressible`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/sqlspecificexpressible) GRDB comes with a Swift version of many SQLite [built-in functions](https://sqlite.org/lang_corefunc.html), listed below. But not all: see [Embedding SQL in Query Interface Requests] for a way to add support for missing SQL functions. -- `ABS`, `AVG`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`: +- `ABS`, `AVG`, `COALESCE`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`: - Those are based on the `abs`, `average`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min`, `sum` and `total` Swift functions: + Those are based on the `abs`, `average`, `coalesce`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min`, `sum`, and `total` Swift functions: ```swift // SELECT MIN(score), MAX(score) FROM player - Player.select(min(scoreColumn), max(scoreColumn)) + Player.select { [min($0.score), max($0.score)] } // SELECT COUNT(name) FROM player - Player.select(count(nameColumn)) + Player.select { count($0.name) } // SELECT COUNT(DISTINCT name) FROM player - Player.select(count(distinct: nameColumn)) + Player.select { count(distinct: $0.name) } // SELECT JULIANDAY(date, 'start of year') FROM game - Game.select(julianDay(dateColumn, .startOfYear)) + Game.select { julianDay($0.date, .startOfYear) } ``` For more information about the functions `dateTime` and `julianDay`, see [Date And Time Functions](https://www.sqlite.org/lang_datefunc.html). @@ -4297,7 +4000,7 @@ GRDB comes with a Swift version of many SQLite [built-in functions](https://sqli ```swift // SELECT (CAST(wins AS REAL) / games) AS successRate FROM player - Player.select((cast(winsColumn, as: .real) / gamesColumn).forKey("successRate")) + Player.select { (cast($0.wins, as: .real) / $0.games).forKey("successRate") } ``` See [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr) for more information about SQLite conversions. @@ -4308,10 +4011,10 @@ GRDB comes with a Swift version of many SQLite [built-in functions](https://sqli ```swift // SELECT IFNULL(name, 'Anonymous') FROM player - Player.select(nameColumn ?? "Anonymous") + Player.select { $0.name ?? "Anonymous" } // SELECT IFNULL(name, email) FROM player - Player.select(nameColumn ?? emailColumn) + Player.select { $0.name ?? $0.email } ``` - `LOWER`, `UPPER` @@ -4321,7 +4024,7 @@ GRDB comes with a Swift version of many SQLite [built-in functions](https://sqli Instead, GRDB extends SQLite with SQL functions that call the Swift built-in string functions `capitalized`, `lowercased`, `uppercased`, `localizedCapitalized`, `localizedLowercased` and `localizedUppercased`: ```swift - Player.select(nameColumn.uppercased()) + Player.select { $0.name.uppercased() } ``` > **Note**: When *comparing* strings, you'd rather use a [collation](#string-comparison): @@ -4330,10 +4033,10 @@ GRDB comes with a Swift version of many SQLite [built-in functions](https://sqli > let name: String = ... > > // Not recommended - > nameColumn.uppercased() == name.uppercased() + > Player.filter { $0.name.uppercased() == name.uppercased() } > > // Better - > nameColumn.collating(.caseInsensitiveCompare) == name + > Player.filter { $0.name.collating(.caseInsensitiveCompare) == name } > ``` - Custom SQL functions and aggregates @@ -4341,10 +4044,10 @@ GRDB comes with a Swift version of many SQLite [built-in functions](https://sqli You can apply your own [custom SQL functions and aggregates](#custom-functions-): ```swift - let f = DatabaseFunction("f", ...) + let myFunction = DatabaseFunction("myFunction", ...) - // SELECT f(name) FROM player - Player.select(f.apply(nameColumn)) + // SELECT myFunction(name) FROM player + Player.select { myFunction($0.name) } ``` ## Embedding SQL in Query Interface Requests @@ -4393,8 +4096,10 @@ LIMIT ... -- 9 ```swift // SELECT IFNULL(name, 'O''Brien') AS displayName, score FROM player let defaultName = "O'Brien" - let displayName: SQL = "IFNULL(\(Column("name")), \(defaultName)) AS displayName" - let request = Player.select(displayName, Column("score")) + let request = Player.select { + let displayName: SQL = "IFNULL(\($0.name), \(defaultName)) AS displayName" + return [displayName, $0.score] + } ``` When the custom SQL snippet should behave as a full-fledged expression, with support for the `+` Swift operator, the `forKey` aliasing method, and all other [SQL Operators](#sql-operators), build an _expression literal_ with the `SQL.sqlExpression` method: @@ -4402,8 +4107,10 @@ LIMIT ... -- 9 ```swift // SELECT IFNULL(name, 'O''Brien') AS displayName, score FROM player let defaultName = "O'Brien" - let displayName = SQL("IFNULL(\(Column("name")), \(defaultName))").sqlExpression - let request = Player.select(displayName.forKey("displayName"), Column("score")) + let request = Player.select { + let displayName = SQL("IFNULL(\($0.name), \(defaultName))").sqlExpression + return [displayName.forKey("displayName"), $0.score] + } ``` Such expression literals allow you to build a reusable support library of SQL functions or operators that are missing from the query interface. For example, you can define a Swift `date` function: @@ -4414,7 +4121,7 @@ LIMIT ... -- 9 } // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23' - let request = Player.filter(date(Column("createdAt")) == "2020-01-23") + let request = Player.filter { date($0.createdAt) == "2020-01-23" } ``` See the [Query Interface Organization] for more information about `SQLSpecificExpressible` and `SQLExpression`. @@ -4449,8 +4156,10 @@ LIMIT ... -- 9 ```swift // SELECT * FROM player WHERE (score >= 1000) AND (team = 'red') let minScore = 1000 - let scoreCondition: SQL = "\(Column("score")) >= \(minScore)" - let request = Player.filter(scoreCondition && Column("team") == "red") + let request = Player.filter { + let scoreCondition: SQL = "\($0.score) >= \(minScore)" + return scoreCondition && $0.team == "red" + } ``` See `SELECT ...` above for more SQL Interpolation examples. @@ -4472,9 +4181,11 @@ LIMIT ... -- 9 ```swift // SELECT * FROM "player" // ORDER BY (score + bonus) ASC, name DESC - let total = SQL("(score + bonus)").sqlExpression let request = Player - .order(total.desc, Column("name")) + .order { + let total = SQL("(\($0.score) + \($0.bonus))").sqlExpression + return [total.desc, $0.name] + } .reversed() ``` @@ -4487,7 +4198,7 @@ Once you have a request, you can fetch the records at the origin of the request: ```swift // Some request based on `Player` -let request = Player.filter(...)... // QueryInterfaceRequest +let request = Player.filter { ... }... // QueryInterfaceRequest // Fetch players: try request.fetchCursor(db) // A Cursor of Player @@ -4500,7 +4211,7 @@ For example: ```swift let allPlayers = try Player.fetchAll(db) // [Player] -let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db) // Player? +let arthur = try Player.filter { $0.name == "Arthur" }.fetchOne(db) // Player? ``` See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. @@ -4511,11 +4222,11 @@ The simplest way is to use the request as an argument to a fetching method of th ```swift // Fetch an Int -let request = Player.select(max(scoreColumn)) +let request = Player.select { max($0.score) } let maxScore = try Int.fetchOne(db, request) // Int? // Fetch a Row -let request = Player.select(min(scoreColumn), max(scoreColumn)) +let request = Player.select { [min($0.score), max($0.score)] } let row = try Row.fetchOne(db, request)! // Row let minScore = row[0] as Int? let maxScore = row[1] as Int? @@ -4545,7 +4256,7 @@ You can also change the request so that it knows the type it has to fetch: ```swift // A request of Int - let request = Player.select(max(scoreColumn), as: Int.self) + let request = Player.select({ max($0.score) }, as: Int.self) let maxScore = try dbQueue.read { db in try request.fetchOne(db) // Int? @@ -4598,7 +4309,7 @@ let request = Citizenship.filter(key: ["citizenId": 1, "countryCode": "FR"]) ```swift // Some request based on `Player` -let request = Player.filter(...)... +let request = Player.filter { ... }... // Check for player existence: let noSuchPlayer = try request.isEmpty(db) // Bool @@ -4650,23 +4361,23 @@ let playerExists = try Player.exists(db, id: 1) let count = try Player.fetchCount(db) // Int // SELECT COUNT(*) FROM player WHERE email IS NOT NULL -let count = try Player.filter(emailColumn != nil).fetchCount(db) +let count = try Player.filter { $0.email != nil }.fetchCount(db) // SELECT COUNT(DISTINCT name) FROM player -let count = try Player.select(nameColumn).distinct().fetchCount(db) +let count = try Player.select(\.name).distinct().fetchCount(db) // SELECT COUNT(*) FROM (SELECT DISTINCT name, score FROM player) -let count = try Player.select(nameColumn, scoreColumn).distinct().fetchCount(db) +let count = try Player.select { [$0.name, $0.score] }.distinct().fetchCount(db) ``` **Other aggregated values** can also be selected and fetched (see [SQL Functions](#sql-functions)): ```swift -let request = Player.select(max(scoreColumn)) +let request = Player.select { max($0.score) } let maxScore = try Int.fetchOne(db, request) // Int? -let request = Player.select(min(scoreColumn), max(scoreColumn)) +let request = Player.select { [min($0.score), max($0.score)] } let row = try Row.fetchOne(db, request)! // Row let minScore = row[0] as Int? let maxScore = row[1] as Int? @@ -4681,14 +4392,14 @@ let maxScore = row[1] as Int? // DELETE FROM player try Player.deleteAll(db) -// DELETE FROM player WHERE team = 'red' +// DELETE FROM player WHERE team = 'Reds' try Player - .filter(teamColumn == "red") + .filter { $0.team == "Reds" } .deleteAll(db) // DELETE FROM player ORDER BY score LIMIT 10 try Player - .order(scoreColumn) + .order(\.score) .limit(10) .deleteAll(db) ``` @@ -4733,47 +4444,50 @@ try Document.deleteOne(db, id: 1) // Document? ```swift // UPDATE player SET score = 0, isHealthy = 1, bonus = NULL -try Player.updateAll(db, - Column("score").set(to: 0), - Column("isHealthy").set(to: true), - Column("bonus").set(to: nil)) +try Player.updateAll(db) { [ + $0.score.set(to: 0), + $0.isHealthy.set(to: true), + $0.bonus.set(to: nil), +] } -// UPDATE player SET score = 0 WHERE team = 'red' +// UPDATE player SET score = 0 WHERE team = 'Reds' try Player - .filter(Column("team") == "red") - .updateAll(db, Column("score").set(to: 0)) + .filter { $0.team == "Reds" } + .updateAll(db) { $0.score.set(to: 0) } -// UPDATE player SET top = 1 ORDER BY score DESC LIMIT 10 +// UPDATE player SET isGreat = 1 ORDER BY score DESC LIMIT 10 try Player - .order(Column("score").desc) + .order(\.score.desc) .limit(10) - .updateAll(db, Column("top").set(to: true)) + .updateAll(db) { $0.isGreat.set(to: true) } // UPDATE country SET population = 67848156 WHERE id = 'FR' try Country .filter(id: "FR") - .updateAll(db, Column("population").set(to: 67_848_156)) + .updateAll(db) { $0.population.set(to: 67_848_156) } ``` Column assignments accept any expression: ```swift // UPDATE player SET score = score + (bonus * 2) -try Player.updateAll(db, Column("score").set(to: Column("score") + Column("bonus") * 2)) +try Player.updateAll(db) { + $0.score.set(to: $0.score + $0.bonus * 2) +} ``` As a convenience, you can also use the `+=`, `-=`, `*=`, or `/=` operators: ```swift // UPDATE player SET score = score + (bonus * 2) -try Player.updateAll(db, Column("score") += Column("bonus") * 2) +try Player.updateAll(db) { $0.score += $0.bonus * 2 } ``` Default [Conflict Resolution] rules apply, and you may also provide a specific one: ```swift // UPDATE OR IGNORE player SET ... -try Player.updateAll(db, onConflict: .ignore, /* assignments... */) +try Player.updateAll(db, onConflict: .ignore) { /* assignments... */ } ``` > **Note** The `updateAll` method is available on types that adopt the [TableRecord] protocol, and `Table`: @@ -4844,7 +4558,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 { @@ -4860,7 +4574,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 @@ -4931,7 +4645,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 @@ -4939,7 +4653,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 @@ -4966,7 +4680,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). @@ -5121,7 +4835,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. @@ -5283,7 +4997,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: @@ -5315,7 +5029,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**. @@ -5357,7 +5071,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: @@ -5393,7 +5107,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"] @@ -5432,7 +5146,7 @@ They uncover programmer errors, false assumptions, and prevent misuses. Here are Solution: add a unique index to the player.email column, or use the `deleteAll` method to make it clear that you may delete more than one row: ```swift - try Player.filter(Column("email") == "arthur@example.com").deleteAll(db) + try Player.filter { $0.email == "arthur@example.com" }.deleteAll(db) ``` - **Database connections are not reentrant:** @@ -5541,7 +5255,7 @@ try String.fetchOne(db, sql: "SELECT \(uppercased.name)('Jérôme')") Those unicode-aware string functions are also readily available in the [query interface](#sql-functions): ```swift -Player.select(nameColumn.uppercased) +Player.select { $0.name.uppercased } ``` @@ -5571,7 +5285,7 @@ try db.create(table: "player") { t in } // Players are sorted in a localized case insensitive way: -let players = try Player.order(nameColumn).fetchAll(db) +let players = try Player.order(\.name).fetchAll(db) ``` > **Warning**: SQLite *requires* host applications to provide the definition of any collation other than binary, nocase and rtrim. When a database file has to be shared or migrated to another SQLite library of platform (such as the Android version of your application), make sure you provide a compatible collation. @@ -5582,7 +5296,7 @@ If you can't or don't want to define the comparison behavior of a column (see wa let collation = DatabaseCollation.localizedCaseInsensitiveCompare let players = try Player.fetchAll(db, sql: "SELECT * FROM player ORDER BY name COLLATE \(collation.name))") -let players = try Player.order(nameColumn.collating(collation)).fetchAll(db) +let players = try Player.order { $0.name.collating(collation) }.fetchAll(db) ``` @@ -5638,7 +5352,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: @@ -5697,7 +5411,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 @@ -5723,9 +5437,7 @@ Open a read-only connection to your resource: // HOW TO open a read-only connection to a database resource // Get the path to the database resource. -if let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite") - -if let dbPath { +if let dbPath = Bundle.main.path(forResource: "db", ofType: "sqlite") { // If the resource exists, open a read-only connection. // Writes are disallowed because resources can not be modified. var config = Configuration() @@ -5741,7 +5453,7 @@ if let dbPath { 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 @@ -5756,7 +5468,7 @@ You can compile the request into a prepared [`Statement`]: ```swift try dbQueue.read { db in - let request = Player.filter(Column("email") == "arthur@example.com") + let request = Player.filter { $0.email == "arthur@example.com" } let statement = try request.makePreparedRequest(db).statement print(statement) // SELECT * FROM player WHERE email = ? print(statement.arguments) // ["arthur@example.com"] @@ -5775,11 +5487,11 @@ let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) try dbQueue.read { db in // Prints "SELECT * FROM player WHERE email = ?" - let players = try Player.filter(Column("email") == "arthur@example.com").fetchAll(db) + let players = try Player.filter { $0.email == "arthur@example.com" }.fetchAll(db) } ``` -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. @@ -5811,12 +5523,12 @@ config.prepareDatabase { db in let dbQueue = try DatabaseQueue(path: dbPath, configuration: config) try dbQueue.read { db in - let players = try Player.filter(Column("email") == "arthur@example.com").fetchAll(db) + let players = try Player.filter { $0.email == "arthur@example.com" }.fetchAll(db) // Prints "0.003s SELECT * FROM player WHERE email = ?" } ``` -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? @@ -5896,7 +5608,7 @@ let books: [Book] = try dbQueue.read { db in // SELECT book.* FROM book // LEFT JOIN author ON author.id = book.authorID // WHERE author.id IS NULL - let authorAlias = TableAlias() + let authorAlias = TableAlias() let request = Book .joining(optional: Book.author.aliased(authorAlias)) .filter(!authorAlias.exists) @@ -5940,9 +5652,10 @@ struct BookInfo: Decodable, FetchableRecord { // SELECT book.*, author.name AS authorName // FROM book // LEFT JOIN author ON author.id = book.authorID - let authorName = Author.Columns.name.forKey(CodingKeys.authorName) return Book - .annotated(withOptional: Book.author.select(authorName)) + .annotated(withOptional: Book.author.select { + $0.name.forKey(CodingKeys.authorName) + }) .asRequest(of: BookInfo.self) } } @@ -6119,9 +5832,12 @@ When this is the case, there are two possible explanations: // STANDARD, AND RECOMMENDED (statement arguments) try db.execute(sql: "UPDATE player SET name = ?", arguments: [name]) + + // STANDARD, AND RECOMMENDED (SQL interpolation) + try db.execute(literal: "UPDATE player SET name = \(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). @@ -6196,15 +5912,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 @@ -6212,7 +5928,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 @@ -6228,27 +5944,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 @@ -6260,7 +5976,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 @@ -6278,15 +5994,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). #### 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 @@ -6302,11 +6022,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. #### 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 @@ -6318,23 +6042,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 @@ -6353,7 +6077,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 @@ -6363,40 +6087,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 diff --git a/SQLiteCustom/GRDB.xcconfig b/SQLiteCustom/GRDB.xcconfig index bb0c76999..85a9b5316 100755 --- a/SQLiteCustom/GRDB.xcconfig +++ b/SQLiteCustom/GRDB.xcconfig @@ -13,3 +13,4 @@ OTHER_CFLAGS = -DUSING_BUILTIN_SQLITE -DGRDBCUSTOMSQLITE $(CUSTOM_SQLLIBRARY_CFL GCC_PREPROCESSOR_DEFINITIONS = "GRDBCUSTOMSQLITE=1" OTHER_SWIFT_FLAGS = -D USING_BUILTIN_SQLITE -D GRDBCUSTOMSQLITE $(CUSTOM_OTHER_SWIFT_FLAGS) HEADER_SEARCH_PATHS = $(SRCROOT)/SQLiteCustom/src +SWIFT_VERSION = 6.0 diff --git a/SQLiteCustom/GRDBCustomSQLite-Testing.xcconfig b/SQLiteCustom/GRDBCustomSQLite-Testing.xcconfig index 62178e5d3..41762aa8c 100755 --- a/SQLiteCustom/GRDBCustomSQLite-Testing.xcconfig +++ b/SQLiteCustom/GRDBCustomSQLite-Testing.xcconfig @@ -10,3 +10,7 @@ CUSTOM_OTHER_SWIFT_FLAGS= // do not modify OTHER_CFLAGS = -DUSING_BUILTIN_SQLITE -DGRDBCUSTOMSQLITE $(CUSTOM_SQLLIBRARY_CFLAGS) // Do not modify. OTHER_SWIFT_FLAGS = -D USING_BUILTIN_SQLITE -D GRDBCUSTOMSQLITE $(CUSTOM_OTHER_SWIFT_FLAGS) // Do not modify. + +// Tests still use the Swift 5 language mode. +SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES = YES +OTHER_SWIFT_FLAGS = $(inherited) -enable-upcoming-feature GlobalActorIsolatedTypesUsability diff --git a/SQLiteCustom/GRDBDeploymentTarget.xcconfig b/SQLiteCustom/GRDBDeploymentTarget.xcconfig index 904204125..045b59696 100644 --- a/SQLiteCustom/GRDBDeploymentTarget.xcconfig +++ b/SQLiteCustom/GRDBDeploymentTarget.xcconfig @@ -1,4 +1,4 @@ -IPHONEOS_DEPLOYMENT_TARGET = 11.0 -MACOSX_DEPLOYMENT_TARGET = 10.13 -TVOS_DEPLOYMENT_TARGET = 11.0 -WATCHOS_DEPLOYMENT_TARGET = 4.0 +IPHONEOS_DEPLOYMENT_TARGET = 13.0 +MACOSX_DEPLOYMENT_TARGET = 10.15 +TVOS_DEPLOYMENT_TARGET = 13.0 +WATCHOS_DEPLOYMENT_TARGET = 7.0 diff --git a/SQLiteCustom/src b/SQLiteCustom/src index 31e6aa661..69395d1f7 160000 --- a/SQLiteCustom/src +++ b/SQLiteCustom/src @@ -1 +1 @@ -Subproject commit 31e6aa66188e59616f062df77329d6ee9ee45929 +Subproject commit 69395d1f72e61f37cf2e5164c054d85c80d5481c diff --git a/Scripts/swiftlint.yml b/Scripts/swiftlint.yml index af49e16e2..9245d10d5 100644 --- a/Scripts/swiftlint.yml +++ b/Scripts/swiftlint.yml @@ -15,7 +15,9 @@ disabled_rules: - is_disjoint - large_tuple - nesting + - non_optional_string_data_conversion - opening_brace + - optional_data_string_conversion - redundant_optional_initialization - syntactic_sugar - todo diff --git a/Sources/CSQLite/module.modulemap b/Sources/GRDBSQLite/module.modulemap similarity index 65% rename from Sources/CSQLite/module.modulemap rename to Sources/GRDBSQLite/module.modulemap index 0a291b5e2..95e4e886f 100644 --- a/Sources/CSQLite/module.modulemap +++ b/Sources/GRDBSQLite/module.modulemap @@ -1,4 +1,4 @@ -module CSQLite [system] { +module GRDBSQLite [system] { header "shim.h" link "sqlite3" export * diff --git a/Sources/CSQLite/shim.h b/Sources/GRDBSQLite/shim.h similarity index 100% rename from Sources/CSQLite/shim.h rename to Sources/GRDBSQLite/shim.h diff --git a/Support/GRDB.xcconfig b/Support/GRDB.xcconfig index 5303f7a07..a3fabb088 100644 --- a/Support/GRDB.xcconfig +++ b/Support/GRDB.xcconfig @@ -3,6 +3,7 @@ INFOPLIST_FILE = Support/Info.plist PRODUCT_NAME = GRDB PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.$(PRODUCT_NAME:rfc1034identifier) MODULEMAP_FILE = $(SRCROOT)/Support/module.modulemap +SWIFT_VERSION = 6.0 // Slow compilation hunt: // OTHER_SWIFT_FLAGS = $(inherited) -Xfrontend -warn-long-expression-type-checking=100 -Xfrontend -warn-long-function-bodies=100 diff --git a/Support/GRDBDeploymentTarget.xcconfig b/Support/GRDBDeploymentTarget.xcconfig index 753467b40..eb0e48eac 100644 --- a/Support/GRDBDeploymentTarget.xcconfig +++ b/Support/GRDBDeploymentTarget.xcconfig @@ -1,7 +1,7 @@ -IPHONEOS_DEPLOYMENT_TARGET = 11.0 -MACOSX_DEPLOYMENT_TARGET = 10.13 -TVOS_DEPLOYMENT_TARGET = 11.0 -WATCHOS_DEPLOYMENT_TARGET = 4.0 +IPHONEOS_DEPLOYMENT_TARGET = 13.0 +MACOSX_DEPLOYMENT_TARGET = 10.15 +TVOS_DEPLOYMENT_TARGET = 13.0 +WATCHOS_DEPLOYMENT_TARGET = 7.0 OTHER_SWIFT_FLAGS = $(inherited) -D SQLITE_ENABLE_FTS5 //// Compile with all opt-in APIs diff --git a/Support/GRDBTests.xcconfig b/Support/GRDBTests.xcconfig new file mode 100644 index 000000000..94ad77784 --- /dev/null +++ b/Support/GRDBTests.xcconfig @@ -0,0 +1,5 @@ +#include "GRDBDeploymentTarget.xcconfig" + +// Tests still use the Swift 5 language mode. +SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES = YES +OTHER_SWIFT_FLAGS = $(inherited) -enable-upcoming-feature GlobalActorIsolatedTypesUsability diff --git a/Support/Info.plist b/Support/Info.plist index a9a6ba2d3..5be4870c8 100644 --- a/Support/Info.plist +++ b/Support/Info.plist @@ -15,7 +15,7 @@ CFBundlePackageType FMWK CFBundleShortVersionString - 6.28.0 + 7.5.0 CFBundleSignature ???? CFBundleVersion diff --git a/TODO.md b/TODO.md index 096a98127..94fd5c432 100644 --- a/TODO.md +++ b/TODO.md @@ -85,7 +85,119 @@ - [ ] Check https://sqlite.org/sqlar.html - [ ] More schema alterations - [ ] Database.clearSchemaCache() is fine, but what about dbPool readers? Can we invalidate the cache for a whole pool? +- [ ] What can we do with `cross-module-optimization`? See https://github.com/apple/swift-homomorphic-encryption +- [X] GRDB7/BREAKING: insertAndFetch, saveAndFetch, and updateAndFetch no longer return optionals (32f41472) +- [X] GRDB7/BREAKING: AsyncValueObservation does not need any scheduler (83c0e643) +- [X] GRDB7/BREAKING: Stop exporting SQLite (679d6463) +- [X] GRDB7/BREAKING: Remove Configuration.defaultTransactionKind (2661ff46) +- [X] GRDB7: Replace LockedBox with Mutex (00ccab06) +- [X] GRDB7: Sendable: BusyCallback (e0d8e20b) +- [X] GRDB7: Sendable: BusyMode (e0d8e20b) +- [X] GRDB7: Sendable: TransactionClock (f7dc72a5) +- [X] GRDB7: Sendable: Configuration (54ffb21f) +- [X] GRDB7: Sendable: DatabaseDataEncodingStrategy (264d7fb5) +- [X] GRDB7: Sendable: DatabaseDateEncodingStrategy (264d7fb5) +- [X] GRDB7: Sendable: DatabaseColumnEncodingStrategy (264d7fb5) +- [X] GRDB7: Sendable: DatabaseDataDecodingStrategy (264d7fb5) +- [X] GRDB7: Sendable: DatabaseDateDecodingStrategy (264d7fb5) +- [X] GRDB7: Sendable: DatabaseColumnDecodingStrategy (264d7fb5) +- [X] GRDB7/BREAKING: Remove DatabaseFuture and concurrentRead (05f7d3c8) +- [X] GRDB7: Sendable: DatabaseFunction (6e691fe7) +- [X] GRDB7: Sendable: DatabaseMigrator (22114ad4) +- [X] GRDB7: Not Sendable: FilterCursor (b26e9709) +- [X] GRDB7: Sendable: RowAdapter (d138af26) +- [X] GRDB7: Sendable: ValueObservationScheduler (8429eb68) +- [X] GRDB7: Sendable: DatabaseCollation (4d9d67dd) +- [X] GRDB7: Sendable: LogErrorFunction (f362518d) +- [X] GRDB7: Sendable: ReadWriteBox (57a86a0e) +- [X] GRDB7: Sendable: Pool (f13b2d2e) +- [X] GRDB7: Sendable: OnDemandFuture fulfill (2aabc4c1) +- [X] GRDB7: Sendable: WALSnapshotTransaction (7fd34012) +- [-] GRDB7: sending closures for SerializedDatabase +- [-] GRDB7: sending closures for ValueObservationScheduler +- [X] GRDB7: Sendable closures for ValueObservation.handleEvents +- [X] GRDB7: Not Sendable: Record (make it explicit if subclasses can be made sendable) +- [ ] GRDB7: Not Sendable: databasepublishers/databaseregion, migrate, read, value, write +- [X] GRDB7: Sendable closures for writePublisher +- [X] GRDB7: Sendable closures for readPublisher +- [-] GRDB7: Not Sendable: fts5customtokenizer, fts5tokenizer, fts5wrappertokenizer +- [X] GRDB7: Sendable: DatabasePromise (05899228, 5a2c15b8) +- [X] GRDB7: Sendable: TableAlias (f2b0b186) +- [X] GRDB7: Sendable: SQLRelation (9545bf70) +- [X] GRDB7: Sendable: SQL (ac33856f) +- [ ] GRDB7: Split Row.swift (2ce8a619) +- [X] GRDB7: Cleanup ValueReducer (6c73b1c5) +- [X] GRDB7: DatabaseCursor has a primary associated type (b11c5dd2) +- [ ] GRDB7: Enable Strict Concurrency Checks (6aa43ded) +- [X] GRDB7: Sendable: OrderedDictionary (e022c35b) +- [X] GRDB7: Rename ReadWriteBox to ReadWriteLock (7f5205ef) +- [X] GRDB7: Sendable: DatabaseRegionConvertible (b4677ded) +- [X] GRDB7: Sendable: ValueConcurrentObserver (87b9db65, 5465d056) +- [X] GRDB7: Sendable: ValueWriteOnlyObserver (ff2a7548) +- [X] GRDB7: Sendable: DatabaseCancellable (2f93f00b, 8f486a5e) +- [X] GRDB7: ValueObservation closures +- [?] GRDB7: DatabasePublishers.ValueSubscription +- [X] GRDB7: Sendable: ValueObservation (93f6f982) +- [?] GRDB7: Not Sendable: SharedValueObservation +- [X] GRDB7: doc (c0838cf9) +- [X] GRDB7/BREAKING: PersistenceContainer is Sendable (50eefa8c) +- [X] GRDB7: TableRecord.databaseSelection must be declared as a computed property (24d232aa) + - [X] Doc + - [X] Migration Guide +- [X] GRDB7: Sendable: Association (b06aaee4) +- [ ] GRDB7/Tests: Sendable: ValueObservationRecorder (2947b3d7) +- [X] GRDB7: ValueObservation.print cautiously uses its stream argument (5f8b39b7) +- [ ] GRDB7/Tests: use a single and Sendable test TextOutputStream (bbb1a736) +- [X] GRDB7: ValueObservation needs a ValueReducer, not a `_ValueReducer` (08733108) +- [X] GRDB7: Database support for cancellation (4ddf4bca) +- [X] GRDB7: SerializedDatabase support for async db access with support for Task cancellation (737cb149) +- [X] GRDB7: DatabaseWriter async methods support Task cancellation (a5226501) +- [X] GRDB7: DatabaseReader async methods support Task cancellation (10c9d311) +- [X] GRDB7: Document that async methods can throw CancellationError (8df18fb8) +- [-] GRDB7: Sendable: AssociationAggregate (48ad10ae) +- [X] GRDB7: Sendable: AsyncValueObservation (necessary for async algorithm) (ce63cdfa) +- [X] GRDB7: Sendable: DatabaseRegionObservation (b4ff52fb) +- [-] GRDB7: DispatchQueue.asyncSending (7b075e6b) +- [X] GRDB7: Replace sequences with collection (e.g. https://github.com/tidal-music/tidal-sdk-ios/pull/39) +- [X] GRDB7: Replace `some` DatabaseReader/Writer with `any` where possible, in order to avoid issues with accessing DatabaseContext from GRDBQuery (if the problem exists in Xcode 16) +- [X] GRDB7: bump to iOS 13, macOS 10.15, tvOS 13 (for ValueObservation support for MainActor) + +- [ ] GRDB7: DatabasePublishers.Value should carry the type of the Scheduler, so that we can rely on main-actor-isolated callbacks. +- [X] GRDB7: Remove warning about "products" in Package.swift +- [X] GRDB7: Fixits + - [X] defaultTransactionKind + - [X] concurrentRead +- [X] GRDB7: Swift Concurrency recommendations + - [X] Record classe(s) + - [X] InferSendableFromCaptures +- [X] GRDB7: stop fostering the Record class + - Remove all mentions from the README + - Warn about it in the documentation of the class. +- [X] GRDB7: Breaking changes documentation + - [X] [BREAKING] Xcode 16+, Swift 6+ + - [X] [BREAKING] iOS 13+ + - [X] [BREAKING] macOS 10.15+ + - [X] [BREAKING] tvOS 13+ + - [X] [BREAKING] watchOS 7+ + - [-] insertAndFetch, updateAndFetch, saveAndFetch + - [X] CSQLite renamed to GRDBCSQLite + - [X] CSQLite is not exported + - [X] defaultTransactionKind + - [X] concurrentRead + - [X] record column strategies: + - databaseDataEncodingStrategy + - databaseDateEncodingStrategy + - databaseUUIDEncodingStrategy + - databaseDataDecodingStrategy + - databaseDateDecodingStrategy + - [X] PersistenceContainer subscript no longer returns its input value + - [X] cancellation of async database access + - [X] Async sequences built from ValueObservation schedule values and errors on the cooperative thread pool by default. + - [X] `TableRecord.databaseSelection` should be declared as a computed static property + - [-] databaseDecodingUserInfo and databaseEncodingUserInfo must be declared as a computed property +- [ ] GRDB7: Review experimental apis +- [?] GRDB7: Change ValueObservation callback argument so that it could expose snapshots? https://github.com/groue/GRDB.swift/discussions/1523#discussioncomment-9092500 ## Unsure if necessary diff --git a/Tests/CocoaPods/GRDBiOS-framework/AppDelegate.swift b/Tests/CocoaPods/GRDBiOS-framework/AppDelegate.swift index 38d6b51bd..b010f4c99 100644 --- a/Tests/CocoaPods/GRDBiOS-framework/AppDelegate.swift +++ b/Tests/CocoaPods/GRDBiOS-framework/AppDelegate.swift @@ -13,6 +13,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate { // test_SQLITE_ENABLE_PREUPDATE_HOOK _ = DatabasePreUpdateEvent.self + // test C functions + _ = sqlite3_libversion_number() + return true } } diff --git a/Tests/CocoaPods/GRDBiOS-framework/Podfile b/Tests/CocoaPods/GRDBiOS-framework/Podfile index 8a4c9e93a..82bf451d2 100644 --- a/Tests/CocoaPods/GRDBiOS-framework/Podfile +++ b/Tests/CocoaPods/GRDBiOS-framework/Podfile @@ -1,6 +1,6 @@ use_frameworks! target 'iOS' -platform :ios, '11.0' +platform :ios, '13.0' pod 'GRDB.swift', :path => '../../..' post_install do |installer| diff --git a/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj index 4de5afc20..b04521c00 100644 --- a/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/GRDBiOS-framework/iOS.xcodeproj/project.pbxproj @@ -251,7 +251,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -301,7 +301,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_COMPILATION_MODE = wholemodule; @@ -318,7 +318,7 @@ CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; INFOPLIST_FILE = Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTest; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -335,7 +335,7 @@ CODE_SIGN_IDENTITY = "iPhone Developer"; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; INFOPLIST_FILE = Info.plist; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBTest; PRODUCT_NAME = "$(TARGET_NAME)"; diff --git a/Tests/CocoaPods/GRDBiOS-static/AppDelegate.swift b/Tests/CocoaPods/GRDBiOS-static/AppDelegate.swift index 38d6b51bd..b010f4c99 100644 --- a/Tests/CocoaPods/GRDBiOS-static/AppDelegate.swift +++ b/Tests/CocoaPods/GRDBiOS-static/AppDelegate.swift @@ -13,6 +13,9 @@ class AppDelegate: UIResponder, UIApplicationDelegate { // test_SQLITE_ENABLE_PREUPDATE_HOOK _ = DatabasePreUpdateEvent.self + // test C functions + _ = sqlite3_libversion_number() + return true } } diff --git a/Tests/CocoaPods/GRDBiOS-static/Podfile b/Tests/CocoaPods/GRDBiOS-static/Podfile index 94614c25b..f4137605f 100644 --- a/Tests/CocoaPods/GRDBiOS-static/Podfile +++ b/Tests/CocoaPods/GRDBiOS-static/Podfile @@ -1,5 +1,5 @@ target 'iOS' -platform :ios, '11.0' +platform :ios, '13.0' pod 'GRDB.swift', :path => '../../..' post_install do |installer| diff --git a/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj index 625554512..acfaddb1c 100644 --- a/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/GRDBiOS-static/iOS.xcodeproj/project.pbxproj @@ -232,7 +232,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -282,7 +282,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 11.0; + IPHONEOS_DEPLOYMENT_TARGET = 13.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_COMPILATION_MODE = wholemodule; diff --git a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj index 2869b204e..a872849dd 100644 --- a/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher3/GRDBTests.xcodeproj/project.pbxproj @@ -21,6 +21,8 @@ 5623B61E2AED39F700436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B61B2AED39F700436239 /* DatabaseQueueTemporaryCopyTests.swift */; }; 5623B61F2AED39F700436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B61C2AED39F700436239 /* DatabaseQueueInMemoryCopyTests.swift */; }; 5623B6202AED39F700436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B61C2AED39F700436239 /* DatabaseQueueInMemoryCopyTests.swift */; }; + 563EA3E52C7B3A4F001BE0D4 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EA3E42C7B3A4F001BE0D4 /* Mutex.swift */; }; + 563EA3E62C7B3A4F001BE0D4 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EA3E42C7B3A4F001BE0D4 /* Mutex.swift */; }; 56419D6724A54062004967E1 /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419C9C24A54053004967E1 /* DatabasePoolTests.swift */; }; 56419D6824A54062004967E1 /* DatabasePoolTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419C9C24A54053004967E1 /* DatabasePoolTests.swift */; }; 56419D6924A54062004967E1 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419C9D24A54053004967E1 /* ResultCodeTests.swift */; }; @@ -493,6 +495,8 @@ 568C3F802A5AB36900A2309D /* ForeignKeyDefinitionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */; }; 5691D97527257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; 5691D97627257CE40021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97427257CE40021D540 /* AvailableElements.swift */; }; + 56DFC3B32C84798300DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */; }; + 56DFC3B42C84798300DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */; }; 56F61DF0283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; }; 56F61DF1283D484700AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DEE283D484700AF9884 /* getThreadsCount.c */; }; 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; @@ -510,6 +514,7 @@ 561F38F82AC9CE6D0051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = ""; }; 5623B61B2AED39F700436239 /* DatabaseQueueTemporaryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTemporaryCopyTests.swift; sourceTree = ""; }; 5623B61C2AED39F700436239 /* DatabaseQueueInMemoryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryCopyTests.swift; sourceTree = ""; }; + 563EA3E42C7B3A4F001BE0D4 /* Mutex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = ""; }; 56419C9C24A54053004967E1 /* DatabasePoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolTests.swift; sourceTree = ""; }; 56419C9D24A54053004967E1 /* ResultCodeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ResultCodeTests.swift; sourceTree = ""; }; 56419C9E24A54053004967E1 /* DatabaseQueueTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTests.swift; sourceTree = ""; }; @@ -749,6 +754,7 @@ 567B5C4A2AD32F7000629622 /* DatabaseReaderDumpTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseReaderDumpTests.swift; sourceTree = ""; }; 568C3F7E2A5AB36900A2309D /* ForeignKeyDefinitionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ForeignKeyDefinitionTests.swift; sourceTree = ""; }; 5691D97427257CE40021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; + 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = ""; }; 56F61DEC283D484700AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; 56F61DEE283D484700AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; 56F61DEF283D484700AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = ""; }; @@ -881,6 +887,7 @@ 56419CAD24A54054004967E1 /* AssociationPrefetchingSQLTests.swift */, 56419D5824A54061004967E1 /* AssociationRowScopeSearchTests.swift */, 56419D6324A54062004967E1 /* AssociationTableAliasTestsSQLTests.swift */, + 56DFC3B22C84798300DFE5DC /* AsyncSemaphore.swift */, 565A27CB27871FFF00659A62 /* BackupTestCase.swift */, 567B5C272AD32A2D00629622 /* CaseInsensitiveIdentifierTests.swift */, 56419CD424A54057004967E1 /* CGFloatTests.swift */, @@ -996,6 +1003,7 @@ 56419D2F24A5405E004967E1 /* MutablePersistableRecordEncodableTests.swift */, 56419D4424A5405F004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 56419D3B24A5405F004967E1 /* MutablePersistableRecordTests.swift */, + 563EA3E42C7B3A4F001BE0D4 /* Mutex.swift */, 56419CFD24A5405A004967E1 /* NumericOverflowTests.swift */, 56419D4F24A54060004967E1 /* OrderedDictionaryTests.swift */, 56419D4524A5405F004967E1 /* PersistableRecordTests.swift */, @@ -1435,6 +1443,7 @@ 56419E0924A54062004967E1 /* DatabaseValueConversionTests.swift in Sources */, 56419DB124A54062004967E1 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56419D9324A54062004967E1 /* PrimaryKeyInfoTests.swift in Sources */, + 563EA3E62C7B3A4F001BE0D4 /* Mutex.swift in Sources */, 567B5C392AD32A2D00629622 /* FoundationDecimalTests.swift in Sources */, 5641A1BA24A540D6004967E1 /* Inverted.swift in Sources */, 5641A1B624A540D6004967E1 /* Prefix.swift in Sources */, @@ -1488,6 +1497,7 @@ 56419ED724A54063004967E1 /* ColumnInfoTests.swift in Sources */, 56419D9F24A54062004967E1 /* CompilationSubClassTests.swift in Sources */, 567B5C3F2AD32A2D00629622 /* CaseInsensitiveIdentifierTests.swift in Sources */, + 56DFC3B32C84798300DFE5DC /* AsyncSemaphore.swift in Sources */, 56419DBB24A54062004967E1 /* ValueObservationRegionRecordingTests.swift in Sources */, 56419EA924A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56419E7F24A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -1683,6 +1693,7 @@ 56419E0A24A54062004967E1 /* DatabaseValueConversionTests.swift in Sources */, 56419DB224A54062004967E1 /* AssociationBelongsToDecodableRecordTests.swift in Sources */, 56419D9424A54062004967E1 /* PrimaryKeyInfoTests.swift in Sources */, + 563EA3E52C7B3A4F001BE0D4 /* Mutex.swift in Sources */, 567B5C3A2AD32A2D00629622 /* FoundationDecimalTests.swift in Sources */, 5641A1BB24A540D6004967E1 /* Inverted.swift in Sources */, 5641A1B724A540D6004967E1 /* Prefix.swift in Sources */, @@ -1736,6 +1747,7 @@ 56419ED824A54063004967E1 /* ColumnInfoTests.swift in Sources */, 56419DA024A54062004967E1 /* CompilationSubClassTests.swift in Sources */, 567B5C402AD32A2D00629622 /* CaseInsensitiveIdentifierTests.swift in Sources */, + 56DFC3B42C84798300DFE5DC /* AsyncSemaphore.swift in Sources */, 56419DBC24A54062004967E1 /* ValueObservationRegionRecordingTests.swift in Sources */, 56419EAA24A54063004967E1 /* DatabasePoolReleaseMemoryTests.swift in Sources */, 56419E8024A54063004967E1 /* DatabaseQueueConcurrencyTests.swift in Sources */, @@ -1810,7 +1822,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.13; + MACOSX_DEPLOYMENT_TARGET = 10.15; ONLY_ACTIVE_ARCH = YES; SWIFT_VERSION = 5.0; }; @@ -1844,7 +1856,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.13; + MACOSX_DEPLOYMENT_TARGET = 10.15; SWIFT_VERSION = 5.0; }; name = Release; diff --git a/Tests/CocoaPods/SQLCipher3/Podfile b/Tests/CocoaPods/SQLCipher3/Podfile index fbe38136b..66346dd90 100644 --- a/Tests/CocoaPods/SQLCipher3/Podfile +++ b/Tests/CocoaPods/SQLCipher3/Podfile @@ -1,4 +1,4 @@ -platform :macos, '10.13' +platform :macos, '10.15' use_frameworks! def common @@ -19,7 +19,7 @@ post_install do |installer| target.build_configurations.each do |config| # Workaround for Xcode 14.3+ # https://github.com/CocoaPods/CocoaPods/issues/11839 - config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.13' + config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.15' config.build_settings['GCC_OPTIMIZATION_LEVEL'] = '3' end end diff --git a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj index f8c3e463f..64c03419a 100644 --- a/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj +++ b/Tests/CocoaPods/SQLCipher4/GRDBTests.xcodeproj/project.pbxproj @@ -21,6 +21,8 @@ 5623B6242AED3A2200436239 /* DatabaseQueueInMemoryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6212AED3A2200436239 /* DatabaseQueueInMemoryCopyTests.swift */; }; 5623B6252AED3A2200436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6222AED3A2200436239 /* DatabaseQueueTemporaryCopyTests.swift */; }; 5623B6262AED3A2200436239 /* DatabaseQueueTemporaryCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623B6222AED3A2200436239 /* DatabaseQueueTemporaryCopyTests.swift */; }; + 563EA3E82C7B3A78001BE0D4 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EA3E72C7B3A78001BE0D4 /* Mutex.swift */; }; + 563EA3E92C7B3A78001BE0D4 /* Mutex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563EA3E72C7B3A78001BE0D4 /* Mutex.swift */; }; 56419FC824A540A1004967E1 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFD24A54093004967E1 /* FetchRequestTests.swift */; }; 56419FC924A540A1004967E1 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFD24A54093004967E1 /* FetchRequestTests.swift */; }; 56419FCA24A540A1004967E1 /* DatabasePoolBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */; }; @@ -495,6 +497,8 @@ 568C3F982A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */; }; 5691D97227257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; 5691D97327257C930021D540 /* AvailableElements.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5691D97127257C930021D540 /* AvailableElements.swift */; }; + 56DFC3B02C84797400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */; }; + 56DFC3B12C84797400DFE5DC /* AsyncSemaphore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */; }; 56F61DF6283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; }; 56F61DF7283D4AB100AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */; }; 5B33E6E34F941B4C839A714F /* (null) in Frameworks */ = {isa = PBXBuildFile; }; @@ -512,6 +516,7 @@ 561F38FE2AC9CE870051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = ""; }; 5623B6212AED3A2200436239 /* DatabaseQueueInMemoryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueInMemoryCopyTests.swift; sourceTree = ""; }; 5623B6222AED3A2200436239 /* DatabaseQueueTemporaryCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueTemporaryCopyTests.swift; sourceTree = ""; }; + 563EA3E72C7B3A78001BE0D4 /* Mutex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Mutex.swift; sourceTree = ""; }; 56419EFD24A54093004967E1 /* FetchRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchRequestTests.swift; sourceTree = ""; }; 56419EFE24A54093004967E1 /* DatabasePoolBackupTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolBackupTests.swift; sourceTree = ""; }; 56419EFF24A54093004967E1 /* TableRecordDeleteTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecordDeleteTests.swift; sourceTree = ""; }; @@ -752,6 +757,7 @@ 568C3F892A5AB3A800A2309D /* DatabaseSnapshotPoolTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSnapshotPoolTests.swift; sourceTree = ""; }; 568C3F8A2A5AB3A800A2309D /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordMinimalNonOptionalPrimaryKeySingleTests.swift; sourceTree = ""; }; 5691D97127257C930021D540 /* AvailableElements.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AvailableElements.swift; sourceTree = ""; }; + 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AsyncSemaphore.swift; sourceTree = ""; }; 56F61DF2283D4AB100AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "GRDBTests-Bridging-Header.h"; sourceTree = ""; }; 56F61DF4283D4AB100AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = ""; }; 56F61DF5283D4AB100AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = ""; }; @@ -885,6 +891,7 @@ 56419F4424A54097004967E1 /* AssociationPrefetchingSQLTests.swift */, 56419F5024A54098004967E1 /* AssociationRowScopeSearchTests.swift */, 56419F9E24A5409D004967E1 /* AssociationTableAliasTestsSQLTests.swift */, + 56DFC3AF2C84797400DFE5DC /* AsyncSemaphore.swift */, 565A27C827871FE500659A62 /* BackupTestCase.swift */, 568C3F882A5AB3A800A2309D /* CaseInsensitiveIdentifierTests.swift */, 56419F6B24A5409A004967E1 /* CGFloatTests.swift */, @@ -1000,6 +1007,7 @@ 56419F0224A54093004967E1 /* MutablePersistableRecordEncodableTests.swift */, 56419F3124A54096004967E1 /* MutablePersistableRecordPersistenceConflictPolicyTests.swift */, 56419F0124A54093004967E1 /* MutablePersistableRecordTests.swift */, + 563EA3E72C7B3A78001BE0D4 /* Mutex.swift */, 56419F0824A54093004967E1 /* NumericOverflowTests.swift */, 56419F0324A54093004967E1 /* OrderedDictionaryTests.swift */, 56419F1A24A54094004967E1 /* PersistableRecordTests.swift */, @@ -1441,6 +1449,7 @@ 5641A08E24A540A1004967E1 /* DatabaseLogErrorTests.swift in Sources */, 5641A01624A540A1004967E1 /* UtilsTests.swift in Sources */, 5641A12A24A540A1004967E1 /* FlattenCursorTests.swift in Sources */, + 563EA3E82C7B3A78001BE0D4 /* Mutex.swift in Sources */, 5641A10424A540A1004967E1 /* DatabaseValueTests.swift in Sources */, 5641A06824A540A1004967E1 /* RowFetchTests.swift in Sources */, 5641A0E024A540A1004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */, @@ -1494,6 +1503,7 @@ 5641A02424A540A1004967E1 /* ValueObservationPrintTests.swift in Sources */, 5641A12024A540A1004967E1 /* AssociationHasManyThroughOrderingTests.swift in Sources */, 5641A04224A540A1004967E1 /* FTS5TableBuilderTests.swift in Sources */, + 56DFC3B02C84797400DFE5DC /* AsyncSemaphore.swift in Sources */, 5641A10624A540A1004967E1 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 5641A11A24A540A1004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */, 5641A05424A540A1004967E1 /* DatabaseWriterTests.swift in Sources */, @@ -1689,6 +1699,7 @@ 5641A08F24A540A1004967E1 /* DatabaseLogErrorTests.swift in Sources */, 5641A01724A540A1004967E1 /* UtilsTests.swift in Sources */, 5641A12B24A540A1004967E1 /* FlattenCursorTests.swift in Sources */, + 563EA3E92C7B3A78001BE0D4 /* Mutex.swift in Sources */, 5641A10524A540A1004967E1 /* DatabaseValueTests.swift in Sources */, 5641A06924A540A1004967E1 /* RowFetchTests.swift in Sources */, 5641A0E124A540A1004967E1 /* QueryInterfaceExtensibilityTests.swift in Sources */, @@ -1742,6 +1753,7 @@ 5641A02524A540A1004967E1 /* ValueObservationPrintTests.swift in Sources */, 5641A12124A540A1004967E1 /* AssociationHasManyThroughOrderingTests.swift in Sources */, 5641A04324A540A1004967E1 /* FTS5TableBuilderTests.swift in Sources */, + 56DFC3B12C84797400DFE5DC /* AsyncSemaphore.swift in Sources */, 5641A10724A540A1004967E1 /* TableRecord+QueryInterfaceRequestTests.swift in Sources */, 5641A11B24A540A1004967E1 /* StatementColumnConvertibleFetchTests.swift in Sources */, 5641A05524A540A1004967E1 /* DatabaseWriterTests.swift in Sources */, @@ -1816,7 +1828,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.13; + MACOSX_DEPLOYMENT_TARGET = 10.15; ONLY_ACTIVE_ARCH = YES; SWIFT_VERSION = 5.0; }; @@ -1850,7 +1862,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.13; + MACOSX_DEPLOYMENT_TARGET = 10.15; SWIFT_VERSION = 5.0; }; name = Release; diff --git a/Tests/CocoaPods/SQLCipher4/Podfile b/Tests/CocoaPods/SQLCipher4/Podfile index 031d49b72..d6e376243 100644 --- a/Tests/CocoaPods/SQLCipher4/Podfile +++ b/Tests/CocoaPods/SQLCipher4/Podfile @@ -1,4 +1,4 @@ -platform :macos, '10.13' +platform :macos, '10.15' use_frameworks! def common @@ -19,7 +19,7 @@ post_install do |installer| target.build_configurations.each do |config| # Workaround for Xcode 14.3+ # https://github.com/CocoaPods/CocoaPods/issues/11839 - config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.13' + config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.15' config.build_settings['GCC_OPTIMIZATION_LEVEL'] = '3' end end diff --git a/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift b/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift index 402b3f553..f37f2eb1e 100644 --- a/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift +++ b/Tests/CombineExpectations/PublisherExpectations/AvailableElements.swift @@ -1,7 +1,6 @@ #if canImport(Combine) import XCTest -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation which waits for the timeout to expire, or /// the recorded publisher to complete. @@ -46,7 +45,7 @@ extension PublisherExpectations { } /// A waiter that waits but never fails - private class Waiter: XCTWaiter, XCTWaiterDelegate { + private class Waiter: XCTWaiter, XCTWaiterDelegate, @unchecked Sendable { init() { super.init(delegate: nil) delegate = self diff --git a/Tests/CombineExpectations/PublisherExpectations/Finished.swift b/Tests/CombineExpectations/PublisherExpectations/Finished.swift index 0a47d09f6..c7b7ecf3d 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Finished.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Finished.swift @@ -17,7 +17,6 @@ import XCTest // try wait(for: recorder.finished.inverted, timeout: 1) // } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation which waits for the recorded publisher /// to complete. diff --git a/Tests/CombineExpectations/PublisherExpectations/Inverted.swift b/Tests/CombineExpectations/PublisherExpectations/Inverted.swift index c7f8d72cc..755897823 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Inverted.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Inverted.swift @@ -1,7 +1,6 @@ #if canImport(Combine) import XCTest -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation that fails if the base expectation is fulfilled. /// diff --git a/Tests/CombineExpectations/PublisherExpectations/Map.swift b/Tests/CombineExpectations/PublisherExpectations/Map.swift index ab4f95c73..87276c91d 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Map.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Map.swift @@ -1,7 +1,6 @@ #if canImport(Combine) import XCTest -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation that transforms the value of a base expectation. /// @@ -20,7 +19,6 @@ extension PublisherExpectations { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectation { /// Returns a publisher expectation that transforms the value of the /// base expectation. diff --git a/Tests/CombineExpectations/PublisherExpectations/Next.swift b/Tests/CombineExpectations/PublisherExpectations/Next.swift index 76ad0c105..6a27fa7df 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Next.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Next.swift @@ -1,7 +1,6 @@ #if canImport(Combine) import XCTest -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation which waits for the recorded publisher to emit /// `count` elements, or to complete. diff --git a/Tests/CombineExpectations/PublisherExpectations/NextOne.swift b/Tests/CombineExpectations/PublisherExpectations/NextOne.swift index 84ee6233e..65ebe04b1 100644 --- a/Tests/CombineExpectations/PublisherExpectations/NextOne.swift +++ b/Tests/CombineExpectations/PublisherExpectations/NextOne.swift @@ -1,7 +1,6 @@ #if canImport(Combine) import XCTest -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation which waits for the recorded publisher to emit /// one element, or to complete. diff --git a/Tests/CombineExpectations/PublisherExpectations/Prefix.swift b/Tests/CombineExpectations/PublisherExpectations/Prefix.swift index 11aced69d..c9bae6cf5 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Prefix.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Prefix.swift @@ -1,7 +1,6 @@ #if canImport(Combine) import XCTest -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation which waits for the recorded publisher to emit /// `maxLength` elements, or to complete. diff --git a/Tests/CombineExpectations/PublisherExpectations/Recording.swift b/Tests/CombineExpectations/PublisherExpectations/Recording.swift index 0b95292dc..1368f4225 100644 --- a/Tests/CombineExpectations/PublisherExpectations/Recording.swift +++ b/Tests/CombineExpectations/PublisherExpectations/Recording.swift @@ -2,7 +2,6 @@ import Combine import XCTest -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// A publisher expectation which waits for the recorded publisher /// to complete. diff --git a/Tests/CombineExpectations/Recorder.swift b/Tests/CombineExpectations/Recorder.swift index 0d7031aaf..bc61f110d 100644 --- a/Tests/CombineExpectations/Recorder.swift +++ b/Tests/CombineExpectations/Recorder.swift @@ -13,7 +13,6 @@ import XCTest /// /// let elements = try wait(for: recorder.elements, timeout: 1) /// XCTAssertEqual(elements, ["foo", "bar", "baz"]) -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public class Recorder: Subscriber { public typealias Input = Input public typealias Failure = Failure @@ -287,7 +286,6 @@ public class Recorder: Subscriber { // MARK: - Publisher Expectations -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension PublisherExpectations { /// The type of the publisher expectation returned by `Recorder.completion`. public typealias Completion = Map, Subscribers.Completion> @@ -302,7 +300,6 @@ extension PublisherExpectations { public typealias Single = Map, Input> } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Recorder { /// Returns a publisher expectation which waits for the timeout to expire, /// or the recorded publisher to complete. @@ -584,7 +581,6 @@ extension Recorder { // MARK: - Publisher + Recorder -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Publisher { /// Returns a subscribed Recorder. /// diff --git a/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.pbxproj b/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.pbxproj index 4d0fd10cd..315344000 100644 --- a/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.pbxproj +++ b/Tests/CustomSQLite/CustomSQLite.xcodeproj/project.pbxproj @@ -342,7 +342,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.13; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; @@ -397,7 +397,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.13; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = macosx; diff --git a/Tests/CustomSQLite/CustomSQLite/AppDelegate.swift b/Tests/CustomSQLite/CustomSQLite/AppDelegate.swift index 12798376f..e8f1bf336 100644 --- a/Tests/CustomSQLite/CustomSQLite/AppDelegate.swift +++ b/Tests/CustomSQLite/CustomSQLite/AppDelegate.swift @@ -7,5 +7,7 @@ class AppDelegate: NSObject, NSApplicationDelegate { _ = try! DatabaseQueue() _ = FTS5() _ = sqlite3_preupdate_new(nil, 0, nil) + let sqliteVersion = String(cString: sqlite3_libversion()) + print(sqliteVersion) } } diff --git a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift index 2b1cf9394..9d7f4a813 100644 --- a/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseReaderReadPublisherTests.swift @@ -22,10 +22,6 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // MARK: - func testReadPublisher() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -44,7 +40,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() } #endif } @@ -128,10 +124,6 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // frame #71: 0x00007fff72311cc9 libdyld.dylib`start + 1 // frame #72: 0x00007fff72311cc9 libdyld.dylib`start + 1 func testReadPublisherError() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(reader: some DatabaseReader) throws { let publisher = reader.readPublisher(value: { db in try Row.fetchAll(db, sql: "THIS IS NOT SQL") @@ -149,7 +141,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshotPool() } #endif } @@ -157,10 +149,6 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // MARK: - func testReadPublisherIsAsynchronous() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -189,7 +177,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() } #endif } @@ -197,10 +185,6 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // MARK: - func testReadPublisherDefaultScheduler() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -229,7 +213,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() } #endif } @@ -237,10 +221,6 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // MARK: - func testReadPublisherCustomScheduler() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -270,7 +250,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { try Test(test).runAtTemporaryDatabasePath { try setUp(DatabaseQueue(path: $0)) } try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)) } try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshot() } -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try Test(test).runAtTemporaryDatabasePath { try setUp(DatabasePool(path: $0)).makeSnapshotPool() } #endif } @@ -278,10 +258,6 @@ class DatabaseReaderReadPublisherTests : XCTestCase { // MARK: - func testReadPublisherIsReadonly() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(reader: some DatabaseReader) throws { let publisher = reader.readPublisher(value: { db in try Player.createTable(db) @@ -298,7 +274,7 @@ class DatabaseReaderReadPublisherTests : XCTestCase { try Test(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshot() } -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try Test(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0).makeSnapshotPool() } #endif } diff --git a/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift b/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift index e126c54b3..a83adfa02 100644 --- a/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseRegionObservationPublisherTests.swift @@ -20,10 +20,6 @@ private struct Player: Codable, FetchableRecord, PersistableRecord { class DatabaseRegionObservationPublisherTests : XCTestCase { func testChangesNotifications() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -61,10 +57,6 @@ class DatabaseRegionObservationPublisherTests : XCTestCase { // TODO: do the same, but asynchronously. If this is too hard, update the // public API so that users can easily do it. func testPrependInitialDatabaseSync() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer diff --git a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift index 1ab142081..7d1b2d0a5 100644 --- a/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift +++ b/Tests/GRDBCombineTests/DatabaseWriterWritePublisherTests.swift @@ -22,10 +22,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWritePublisher() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -49,10 +45,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWritePublisherValue() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -76,10 +68,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWritePublisherError() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher(updates: { db in try db.execute(sql: "THIS IS NOT SQL") @@ -99,10 +87,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } func testWritePublisherErrorRollbacksTransaction() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -132,10 +116,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWritePublisherIsAsynchronous() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -168,10 +148,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWritePublisherDefaultScheduler() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -206,10 +182,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWritePublisherCustomScheduler() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -247,10 +219,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // TODO: Fix flaky test with both pool and on-disk queue: // - Expectation timeout func testWriteThenReadPublisher() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -274,10 +242,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWriteThenReadPublisherIsReadonly() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(writer: some DatabaseWriter) throws { let publisher = writer .writePublisher( @@ -299,10 +263,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // MARK: - func testWriteThenReadPublisherWriteError() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher( updates: { db in try db.execute(sql: "THIS IS NOT SQL") }, @@ -322,10 +282,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { } func testWriteThenReadPublisherWriteErrorRollbacksTransaction() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -359,10 +315,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // TODO: Fix flaky test with both pool and on-disk queue: // - Expectation timeout func testWriteThenReadPublisherReadError() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(writer: some DatabaseWriter) throws { let publisher = writer.writePublisher( updates: { _ in }, @@ -386,10 +338,6 @@ class DatabaseWriterWritePublisherTests : XCTestCase { // Regression test against deadlocks created by concurrent completion // and cancellations triggered by .switchToLatest().prefix(1) func testDeadlockPrevention() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer diff --git a/Tests/GRDBCombineTests/Support.swift b/Tests/GRDBCombineTests/Support.swift index d8f2ec838..6d35dd771 100644 --- a/Tests/GRDBCombineTests/Support.swift +++ b/Tests/GRDBCombineTests/Support.swift @@ -51,7 +51,6 @@ final class Test { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) final class AsyncTest { // Raise the repeatCount in order to help spotting flaky tests. private let repeatCount: Int @@ -100,7 +99,6 @@ final class AsyncTest { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func assertNoFailure( _ completion: Subscribers.Completion, file: StaticString = #file, @@ -111,7 +109,6 @@ public func assertNoFailure( } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) public func assertFailure( _ completion: Subscribers.Completion, file: StaticString = #file, diff --git a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift index b55fd98c6..0849a0085 100644 --- a/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift +++ b/Tests/GRDBCombineTests/ValueObservationPublisherTests.swift @@ -22,10 +22,6 @@ class ValueObservationPublisherTests : XCTestCase { // MARK: - Default Scheduler func testDefaultSchedulerChangesNotifications() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -64,10 +60,6 @@ class ValueObservationPublisherTests : XCTestCase { } func testDefaultSchedulerFirstValueIsEmittedAsynchronously() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -97,10 +89,6 @@ class ValueObservationPublisherTests : XCTestCase { } func testDefaultSchedulerError() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(writer: some DatabaseWriter) throws { let publisher = ValueObservation .trackingConstantRegion { try $0.execute(sql: "THIS IS NOT SQL") } @@ -123,10 +111,6 @@ class ValueObservationPublisherTests : XCTestCase { // MARK: - Immediate Scheduler func testImmediateSchedulerChangesNotifications() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -165,10 +149,6 @@ class ValueObservationPublisherTests : XCTestCase { } func testImmediateSchedulerEmitsFirstValueSynchronously() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -201,10 +181,6 @@ class ValueObservationPublisherTests : XCTestCase { } func testImmediateSchedulerError() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(writer: some DatabaseWriter) throws { let publisher = ValueObservation .trackingConstantRegion { try $0.execute(sql: "THIS IS NOT SQL") } @@ -226,7 +202,6 @@ class ValueObservationPublisherTests : XCTestCase { // MARK: - Demand - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) private class DemandSubscriber: Subscriber { private var subscription: Subscription? let subject = PassthroughSubject() @@ -257,10 +232,6 @@ class ValueObservationPublisherTests : XCTestCase { } func testDemandNoneReceivesNoElement() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -292,10 +263,6 @@ class ValueObservationPublisherTests : XCTestCase { } func testDemandOneReceivesOneElement() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -330,10 +297,6 @@ class ValueObservationPublisherTests : XCTestCase { } func testDemandOneDoesNotReceiveTwoElements() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -372,10 +335,6 @@ class ValueObservationPublisherTests : XCTestCase { } func testDemandTwoReceivesTwoElements() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func setUp(_ writer: Writer) throws -> Writer { try writer.write(Player.createTable) return writer @@ -418,10 +377,6 @@ class ValueObservationPublisherTests : XCTestCase { /// Regression test for https://github.com/groue/GRDB.swift/issues/1194 func testIssue1194() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - struct Record: Codable, FetchableRecord, PersistableRecord { var id: Int64 } diff --git a/Tests/GRDBManualInstall/GRDBManualInstall.xcodeproj/project.pbxproj b/Tests/GRDBManualInstall/GRDBManualInstall.xcodeproj/project.pbxproj new file mode 100644 index 000000000..bd3054f18 --- /dev/null +++ b/Tests/GRDBManualInstall/GRDBManualInstall.xcodeproj/project.pbxproj @@ -0,0 +1,401 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXBuildFile section */ + 56CFC70E2C9F5BDB000B5023 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56CFC7082C9F5BB4000B5023 /* GRDB.framework */; }; + 56CFC70F2C9F5BDB000B5023 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56CFC7082C9F5BB4000B5023 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 56CFC7072C9F5BB4000B5023 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56CFC7002C9F5BB4000B5023 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = DC3773F319C8CBB3004FCF85; + remoteInfo = GRDB; + }; + 56CFC70B2C9F5BC7000B5023 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56CFC7002C9F5BB4000B5023 /* GRDB.xcodeproj */; + proxyType = 1; + remoteGlobalIDString = DC3773F219C8CBB3004FCF85; + remoteInfo = GRDB; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 56CFC7102C9F5BDB000B5023 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + 56CFC70F2C9F5BDB000B5023 /* GRDB.framework in Embed Frameworks */, + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 56CFC6EE2C9F5B8F000B5023 /* GRDBManualInstall.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBManualInstall.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 56CFC7002C9F5BB4000B5023 /* GRDB.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = GRDB.xcodeproj; path = /Users/groue/Documents/git/groue/GRDB.swift/GRDB.xcodeproj; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + 56CFC6F02C9F5B8F000B5023 /* GRDBManualInstall */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = GRDBManualInstall; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + 56CFC6EB2C9F5B8F000B5023 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 56CFC70E2C9F5BDB000B5023 /* GRDB.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 56CFC6E52C9F5B8F000B5023 = { + isa = PBXGroup; + children = ( + 56CFC7002C9F5BB4000B5023 /* GRDB.xcodeproj */, + 56CFC6F02C9F5B8F000B5023 /* GRDBManualInstall */, + 56CFC70D2C9F5BDB000B5023 /* Frameworks */, + 56CFC6EF2C9F5B8F000B5023 /* Products */, + ); + sourceTree = ""; + }; + 56CFC6EF2C9F5B8F000B5023 /* Products */ = { + isa = PBXGroup; + children = ( + 56CFC6EE2C9F5B8F000B5023 /* GRDBManualInstall.app */, + ); + name = Products; + sourceTree = ""; + }; + 56CFC7032C9F5BB4000B5023 /* Products */ = { + isa = PBXGroup; + children = ( + 56CFC7082C9F5BB4000B5023 /* GRDB.framework */, + ); + name = Products; + sourceTree = ""; + }; + 56CFC70D2C9F5BDB000B5023 /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 56CFC6ED2C9F5B8F000B5023 /* GRDBManualInstall */ = { + isa = PBXNativeTarget; + buildConfigurationList = 56CFC6FD2C9F5B91000B5023 /* Build configuration list for PBXNativeTarget "GRDBManualInstall" */; + buildPhases = ( + 56CFC6EA2C9F5B8F000B5023 /* Sources */, + 56CFC6EB2C9F5B8F000B5023 /* Frameworks */, + 56CFC6EC2C9F5B8F000B5023 /* Resources */, + 56CFC7102C9F5BDB000B5023 /* Embed Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 56CFC70C2C9F5BC7000B5023 /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + 56CFC6F02C9F5B8F000B5023 /* GRDBManualInstall */, + ); + name = GRDBManualInstall; + packageProductDependencies = ( + ); + productName = GRDBManualInstall; + productReference = 56CFC6EE2C9F5B8F000B5023 /* GRDBManualInstall.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 56CFC6E62C9F5B8F000B5023 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 1600; + TargetAttributes = { + 56CFC6ED2C9F5B8F000B5023 = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = 56CFC6E92C9F5B8F000B5023 /* Build configuration list for PBXProject "GRDBManualInstall" */; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 56CFC6E52C9F5B8F000B5023; + minimizedProjectReferenceProxies = 1; + preferredProjectObjectVersion = 77; + productRefGroup = 56CFC6EF2C9F5B8F000B5023 /* Products */; + projectDirPath = ""; + projectReferences = ( + { + ProductGroup = 56CFC7032C9F5BB4000B5023 /* Products */; + ProjectRef = 56CFC7002C9F5BB4000B5023 /* GRDB.xcodeproj */; + }, + ); + projectRoot = ""; + targets = ( + 56CFC6ED2C9F5B8F000B5023 /* GRDBManualInstall */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXReferenceProxy section */ + 56CFC7082C9F5BB4000B5023 /* GRDB.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = GRDB.framework; + remoteRef = 56CFC7072C9F5BB4000B5023 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; +/* End PBXReferenceProxy section */ + +/* Begin PBXResourcesBuildPhase section */ + 56CFC6EC2C9F5B8F000B5023 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 56CFC6EA2C9F5B8F000B5023 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 56CFC70C2C9F5BC7000B5023 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = GRDB; + targetProxy = 56CFC70B2C9F5BC7000B5023 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 56CFC6FB2C9F5B91000B5023 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MACOSX_DEPLOYMENT_TARGET = 14.6; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 56CFC6FC2C9F5B91000B5023 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MACOSX_DEPLOYMENT_TARGET = 14.6; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + }; + name = Release; + }; + 56CFC6FE2C9F5B91000B5023 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_ENTITLEMENTS = GRDBManualInstall/GRDBManualInstall.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_ASSET_PATHS = "\"GRDBManualInstall/Preview Content\""; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBManualInstall; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 56CFC6FF2C9F5B91000B5023 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_ENTITLEMENTS = GRDBManualInstall/GRDBManualInstall.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_ASSET_PATHS = "\"GRDBManualInstall/Preview Content\""; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBManualInstall; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 56CFC6E92C9F5B8F000B5023 /* Build configuration list for PBXProject "GRDBManualInstall" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56CFC6FB2C9F5B91000B5023 /* Debug */, + 56CFC6FC2C9F5B91000B5023 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 56CFC6FD2C9F5B91000B5023 /* Build configuration list for PBXNativeTarget "GRDBManualInstall" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56CFC6FE2C9F5B91000B5023 /* Debug */, + 56CFC6FF2C9F5B91000B5023 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 56CFC6E62C9F5B8F000B5023 /* Project object */; +} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Tests/GRDBManualInstall/GRDBManualInstall.xcodeproj/project.xcworkspace/contents.xcworkspacedata similarity index 100% rename from Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.xcworkspace/contents.xcworkspacedata rename to Tests/GRDBManualInstall/GRDBManualInstall.xcodeproj/project.xcworkspace/contents.xcworkspacedata diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AccentColor.colorset/Contents.json b/Tests/GRDBManualInstall/GRDBManualInstall/Assets.xcassets/AccentColor.colorset/Contents.json similarity index 100% rename from Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/AccentColor.colorset/Contents.json rename to Tests/GRDBManualInstall/GRDBManualInstall/Assets.xcassets/AccentColor.colorset/Contents.json diff --git a/Tests/GRDBManualInstall/GRDBManualInstall/Assets.xcassets/AppIcon.appiconset/Contents.json b/Tests/GRDBManualInstall/GRDBManualInstall/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..3f00db43e --- /dev/null +++ b/Tests/GRDBManualInstall/GRDBManualInstall/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,58 @@ +{ + "images" : [ + { + "idiom" : "mac", + "scale" : "1x", + "size" : "16x16" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "16x16" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "32x32" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "32x32" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "128x128" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "128x128" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "256x256" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "256x256" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "512x512" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "512x512" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Preview Content/Preview Assets.xcassets/Contents.json b/Tests/GRDBManualInstall/GRDBManualInstall/Assets.xcassets/Contents.json similarity index 100% rename from Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Preview Content/Preview Assets.xcassets/Contents.json rename to Tests/GRDBManualInstall/GRDBManualInstall/Assets.xcassets/Contents.json diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Tests/GRDBManualInstall/GRDBManualInstall/GRDBManualInstall.entitlements similarity index 63% rename from Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist rename to Tests/GRDBManualInstall/GRDBManualInstall/GRDBManualInstall.entitlements index 18d981003..18aff0ce4 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ b/Tests/GRDBManualInstall/GRDBManualInstall/GRDBManualInstall.entitlements @@ -2,7 +2,9 @@ - IDEDidComputeMac32BitWarning + com.apple.security.app-sandbox + + com.apple.security.files.user-selected.read-only diff --git a/Tests/GRDBManualInstall/GRDBManualInstall/GRDBManualInstallApp.swift b/Tests/GRDBManualInstall/GRDBManualInstall/GRDBManualInstallApp.swift new file mode 100644 index 000000000..56fb2f55d --- /dev/null +++ b/Tests/GRDBManualInstall/GRDBManualInstall/GRDBManualInstallApp.swift @@ -0,0 +1,27 @@ +import GRDB +import SwiftUI + +@main +struct GRDBManualInstallApp: App { + var body: some Scene { + WindowGroup { + VStack { + Image(systemName: "globe") + .imageScale(.large) + .foregroundStyle(.tint) + Text("SQLite version: \(sqliteVersion)") + } + .padding() + } + } + + var sqliteVersion: String { + do { + return try DatabaseQueue().read { db in + try String.fetchOne(db, sql: "SELECT sqlite_version()")! + } + } catch { + return "error" + } + } +} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/Contents.json b/Tests/GRDBManualInstall/GRDBManualInstall/Preview Content/Preview Assets.xcassets/Contents.json similarity index 100% rename from Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Resources/Assets.xcassets/Contents.json rename to Tests/GRDBManualInstall/GRDBManualInstall/Preview Content/Preview Assets.xcassets/Contents.json diff --git a/Tests/GRDBTests/AssociationAggregateTests.swift b/Tests/GRDBTests/AssociationAggregateTests.swift index a8875291a..268172100 100644 --- a/Tests/GRDBTests/AssociationAggregateTests.swift +++ b/Tests/GRDBTests/AssociationAggregateTests.swift @@ -7,6 +7,10 @@ private struct Team: Codable, FetchableRecord, PersistableRecord { static let customPlayers = hasMany(Player.self, key: "customPlayers") var id: Int64 var name: String + + enum Columns { + static let name = Column(CodingKeys.name) + } } private struct Player: Codable, FetchableRecord, PersistableRecord { @@ -15,6 +19,11 @@ private struct Player: Codable, FetchableRecord, PersistableRecord { var teamId: Int64? var name: String var score: Int + + enum Columns { + static let name = Column(CodingKeys.name) + static let score = Column(CodingKeys.score) + } } private struct Award: Codable, FetchableRecord, PersistableRecord { @@ -100,9 +109,9 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .select(Column("name")) + .select { $0.name } .annotated(with: Team.players.count) - .group(Column("name")) + .group { $0.name } try assertEqualSQL(db, request, """ SELECT "team"."name", COUNT(DISTINCT "player"."id") AS "playerCount" \ @@ -112,12 +121,31 @@ class AssociationAggregateTests: GRDBTestCase { """) } } - + + #if compiler(>=6.1) + func testAggregateWithGroup_swift61() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let request = Team + .select(\.name) + .annotated(with: Team.players.count) + .group(\.name) + + try assertEqualSQL(db, request, """ + SELECT "team"."name", COUNT(DISTINCT "player"."id") AS "playerCount" \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ + GROUP BY "team"."name" + """) + } + } + #endif + func testAnnotatedWithHasManyDefaultAverage() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.average(Column("score"))) + .annotated(with: Team.players.average { $0.score }) .orderByPrimaryKey() .asRequest(of: TeamInfo.self) @@ -235,7 +263,7 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.max(Column("score"))) + .annotated(with: Team.players.max { $0.score }) .orderByPrimaryKey() .asRequest(of: TeamInfo.self) @@ -268,6 +296,45 @@ class AssociationAggregateTests: GRDBTestCase { } } + #if compiler(>=6.1) + func testAnnotatedWithHasManyDefaultMax_Swift61() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.read { db in + let request = Team + .annotated(with: Team.players.max(\.score)) + .orderByPrimaryKey() + .asRequest(of: TeamInfo.self) + + try assertEqualSQL(db, request, """ + SELECT "team".*, MAX("player"."score") AS "maxPlayerScore" \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ + GROUP BY "team"."id" \ + ORDER BY "team"."id" + """) + + let teamInfos = try request.fetchAll(db) + XCTAssertEqual(teamInfos.count, 4) + + XCTAssertEqual(teamInfos[0].team.id, 1) + XCTAssertEqual(teamInfos[0].team.name, "Reds") + XCTAssertEqual(teamInfos[0].maxPlayerScore, 1000) + + XCTAssertEqual(teamInfos[1].team.id, 2) + XCTAssertEqual(teamInfos[1].team.name, "Blues") + XCTAssertEqual(teamInfos[1].maxPlayerScore, 800) + + XCTAssertEqual(teamInfos[2].team.id, 3) + XCTAssertEqual(teamInfos[2].team.name, "Greens") + XCTAssertNil(teamInfos[2].maxPlayerScore) + + XCTAssertEqual(teamInfos[3].team.id, 4) + XCTAssertEqual(teamInfos[3].team.name, "Oranges") + XCTAssertEqual(teamInfos[3].maxPlayerScore, 0) + } + } + #endif + func testAnnotatedWithHasManyDefaultMaxJoiningRequired() throws { // It is important to have an explicit test for this technique because // it is the only currently available that forces a JOIN, and we don't @@ -277,7 +344,7 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.max(Column("score"))) + .annotated(with: Team.players.max { $0.score }) .joining(required: Team.players) // <- the tested technique .orderByPrimaryKey() .asRequest(of: TeamInfo.self) @@ -312,7 +379,7 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.min(Column("score"))) + .annotated(with: Team.players.min { $0.score }) .orderByPrimaryKey() .asRequest(of: TeamInfo.self) @@ -349,7 +416,7 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.sum(Column("score"))) + .annotated(with: Team.players.sum { $0.score }) .orderByPrimaryKey() .asRequest(of: TeamInfo.self) @@ -386,7 +453,7 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.total(Column("score"))) + .annotated(with: Team.players.total { $0.score }) .orderByPrimaryKey() .asRequest(of: TeamInfo.self) @@ -423,10 +490,10 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.average(Column("score"))) + .annotated(with: Team.players.average { $0.score }) .annotated(with: Team.players.count) - .annotated(with: Team.players.min(Column("score")), Team.players.max(Column("score"))) - .annotated(with: Team.players.sum(Column("score"))) + .annotated(with: Team.players.min { $0.score }, Team.players.max { $0.score }) + .annotated(with: Team.players.sum { $0.score }) .orderByPrimaryKey() .asRequest(of: TeamInfo.self) @@ -484,7 +551,7 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.customPlayers.average(Column("score"))) + .annotated(with: Team.customPlayers.average { $0.score }) .orderByPrimaryKey() .asRequest(of: CustomTeamInfo.self) @@ -558,7 +625,7 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.customPlayers.max(Column("score"))) + .annotated(with: Team.customPlayers.max { $0.score }) .orderByPrimaryKey() .asRequest(of: CustomTeamInfo.self) @@ -595,7 +662,7 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.customPlayers.min(Column("score"))) + .annotated(with: Team.customPlayers.min { $0.score }) .orderByPrimaryKey() .asRequest(of: CustomTeamInfo.self) @@ -632,7 +699,7 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.customPlayers.sum(Column("score"))) + .annotated(with: Team.customPlayers.sum { $0.score }) .orderByPrimaryKey() .asRequest(of: CustomTeamInfo.self) @@ -669,7 +736,7 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.customPlayers.total(Column("score"))) + .annotated(with: Team.customPlayers.total { $0.score }) .orderByPrimaryKey() .asRequest(of: CustomTeamInfo.self) @@ -706,10 +773,10 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.customPlayers.average(Column("score"))) + .annotated(with: Team.customPlayers.average { $0.score }) .annotated(with: Team.customPlayers.count) - .annotated(with: Team.customPlayers.min(Column("score")), Team.customPlayers.max(Column("score"))) - .annotated(with: Team.customPlayers.sum(Column("score"))) + .annotated(with: Team.customPlayers.min { $0.score }, Team.customPlayers.max { $0.score }) + .annotated(with: Team.customPlayers.sum { $0.score }) .orderByPrimaryKey() .asRequest(of: CustomTeamInfo.self) @@ -767,11 +834,11 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.average(Column("score")).forKey("a1")) + .annotated(with: Team.players.average { $0.score }.forKey("a1")) .annotated(with: Team.players.count.forKey("a2")) - .annotated(with: Team.players.max(Column("score")).forKey("a3")) - .annotated(with: Team.players.min(Column("score")).forKey("a4")) - .annotated(with: Team.players.sum(Column("score")).forKey("a5")) + .annotated(with: Team.players.max { $0.score }.forKey("a3")) + .annotated(with: Team.players.min { $0.score }.forKey("a4")) + .annotated(with: Team.players.sum { $0.score }.forKey("a5")) try assertEqualSQL(db, request, """ SELECT "team".*, \ @@ -791,10 +858,10 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.average(Column("score") * Column("score")).forKey("a1")) - .annotated(with: Team.players.max(Column("score") * 10).forKey("a3")) - .annotated(with: Team.players.min(-Column("score")).forKey("a4")) - .annotated(with: Team.players.sum(Column("score") * Column("score")).forKey("a5")) + .annotated(with: Team.players.average { $0.score * $0.score }.forKey("a1")) + .annotated(with: Team.players.max { $0.score * 10 }.forKey("a3")) + .annotated(with: Team.players.min { -$0.score }.forKey("a4")) + .annotated(with: Team.players.sum { $0.score * $0.score }.forKey("a5")) try assertEqualSQL(db, request, """ SELECT "team".*, \ AVG("player"."score" * "player"."score") AS "a1", \ @@ -817,8 +884,8 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.filter(Column("score") < 500).forKey("lowPlayers").count) - .annotated(with: Team.players.filter(Column("score") >= 500).forKey("highPlayers").count) + .annotated(with: Team.players.filter { $0.score < 500 }.forKey("lowPlayers").count) + .annotated(with: Team.players.filter { $0.score >= 500 }.forKey("highPlayers").count) .orderByPrimaryKey() .asRequest(of: TeamInfo.self) @@ -1454,7 +1521,7 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in let request = Team - .annotated(with: Team.players.min(Column("score")) ?? 0) + .annotated(with: Team.players.min { $0.score } ?? 0) .orderByPrimaryKey() .asRequest(of: TeamInfo.self) @@ -1491,7 +1558,7 @@ class AssociationAggregateTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.read { db in do { - let request = Team.annotated(with: abs(Team.players.max(Column("score")))) + let request = Team.annotated(with: abs(Team.players.max { $0.score })) try assertEqualSQL(db, request, """ SELECT "team".*, ABS(MAX("player"."score")) \ FROM "team" \ @@ -1500,7 +1567,7 @@ class AssociationAggregateTests: GRDBTestCase { """) } do { - let request = Team.annotated(with: abs(Team.players.max(Column("score"))).forKey("foo")) + let request = Team.annotated(with: abs(Team.players.max { $0.score }).forKey("foo")) try assertEqualSQL(db, request, """ SELECT "team".*, ABS(MAX("player"."score")) AS "foo" \ FROM "team" \ @@ -1540,7 +1607,7 @@ class AssociationAggregateTests: GRDBTestCase { try dbQueue.read { db in do { // This is a meaningless request, but this is enough for this test - let request = Team.annotated(with: length(Team.players.max(Column("score")))) + let request = Team.annotated(with: length(Team.players.max { $0.score })) try assertEqualSQL(db, request, """ SELECT "team".*, LENGTH(MAX("player"."score")) \ FROM "team" \ @@ -1550,7 +1617,7 @@ class AssociationAggregateTests: GRDBTestCase { } do { // This is a meaningless request, but this is enough for this test - let request = Team.annotated(with: length(Team.players.max(Column("score"))).forKey("foo")) + let request = Team.annotated(with: length(Team.players.max { $0.score }).forKey("foo")) try assertEqualSQL(db, request, """ SELECT "team".*, LENGTH(MAX("player"."score")) AS "foo" \ FROM "team" \ diff --git a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift index bdfac0827..9e1518cf8 100644 --- a/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToDecodableRecordTests.swift @@ -5,6 +5,11 @@ private struct Team: Codable, FetchableRecord, PersistableRecord { static let databaseTableName = "teams" var id: Int64 var name: String + + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + } } private struct Player: Codable, FetchableRecord, PersistableRecord { @@ -13,6 +18,10 @@ private struct Player: Codable, FetchableRecord, PersistableRecord { var id: Int64 var teamId: Int64? var name: String + + enum Columns { + static let name = Column(CodingKeys.name) + } } private struct PlayerWithRequiredTeam: Decodable, FetchableRecord { @@ -34,14 +43,24 @@ private struct PlayerWithTeamName: Decodable, FetchableRecord { private extension QueryInterfaceRequest { func filter(teamName: String) -> QueryInterfaceRequest { - joining(required: PlayerWithOptionalTeam.team.filter(Column("name") == teamName)) + joining(required: PlayerWithOptionalTeam.team.filter { $0.name == teamName }) } func orderedByTeamName() -> QueryInterfaceRequest { let teamAlias = TableAlias() - return joining(optional: PlayerWithOptionalTeam.team.aliased(teamAlias)) - .order(teamAlias[Column("name")], Column("name")) + return self + .joining(optional: PlayerWithOptionalTeam.team.aliased(teamAlias)) + .order { [teamAlias[Team.Columns.name], $0.name] } } + +#if compiler(>=6.1) + func orderedByTeamName_swift61() -> QueryInterfaceRequest { + let teamAlias = TableAlias() + return self + .joining(optional: PlayerWithOptionalTeam.team.aliased(teamAlias)) + .order { [teamAlias.name, $0.name] } + } +#endif } /// Test support for Decodable records @@ -82,7 +101,7 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase { func testAnnotatedWithRequired() throws { let dbQueue = try makeDatabaseQueue() let request = Player - .annotated(withRequired: Player.team.select(Column("name").forKey("teamName"))) + .annotated(withRequired: Player.team.select { $0.name.forKey("teamName") }) .asRequest(of: PlayerWithTeamName.self) let records = try dbQueue.inDatabase { try request.fetchAll($0) } XCTAssertEqual(records.count, 1) @@ -113,7 +132,7 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase { func testAnnotatedWithOptional() throws { let dbQueue = try makeDatabaseQueue() let request = Player - .annotated(withOptional: Player.team.select(Column("name").forKey("teamName"))) + .annotated(withOptional: Player.team.select { $0.name.forKey("teamName") }) .asRequest(of: PlayerWithTeamName.self) let records = try dbQueue.inDatabase { try request.fetchAll($0) } XCTAssertEqual(records.count, 2) @@ -152,7 +171,7 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase { func testRequestRefining() throws { let dbQueue = try makeDatabaseQueue() let request = Player - .including(required: PlayerWithRequiredTeam.team.select(Column("name"), Column("id"))) + .including(required: PlayerWithRequiredTeam.team.select { [$0.name, $0.id] }) .filter(teamName: "Reds") .orderedByTeamName() .asRequest(of: PlayerWithRequiredTeam.self) @@ -170,4 +189,28 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase { XCTAssertEqual(records[0].team.id, 1) XCTAssertEqual(records[0].team.name, "Reds") } + +#if compiler(>=6.1) + func testRequestRefining_swift61() throws { + let dbQueue = try makeDatabaseQueue() + let request = Player + .including(required: PlayerWithRequiredTeam.team.select { [$0.name, $0.id] }) + .filter(teamName: "Reds") + .orderedByTeamName_swift61() + .asRequest(of: PlayerWithRequiredTeam.self) + let records = try dbQueue.inDatabase { try request.fetchAll($0) } + XCTAssertEqual(lastSQLQuery, """ + SELECT "players".*, "teams"."name", "teams"."id" \ + FROM "players" \ + JOIN "teams" ON ("teams"."id" = "players"."teamId") AND ("teams"."name" = 'Reds') \ + ORDER BY "teams"."name", "players"."name" + """) + XCTAssertEqual(records.count, 1) + XCTAssertEqual(records[0].player.id, 1) + XCTAssertEqual(records[0].player.teamId, 1) + XCTAssertEqual(records[0].player.name, "Arthur") + XCTAssertEqual(records[0].team.id, 1) + XCTAssertEqual(records[0].team.name, "Reds") + } +#endif } diff --git a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift index 813a993e2..e21ebefe4 100644 --- a/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToRowScopeTests.swift @@ -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() diff --git a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift index b51ec961e..694d63eb1 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLDerivationTests.swift @@ -5,23 +5,39 @@ 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) + + enum Columns { + static let id = Column("id") + static let bid = Column("idb") + } } private struct B : TableRecord { static let a = hasOne(A.self) static let databaseTableName = "b" + + enum Columns { + static let id = Column("id") + static let name = Column("name") + } } -private struct RestrictedB : TableRecord { +private struct RestrictedB1 : TableRecord { static let databaseTableName = "b" - static let databaseSelection: [any SQLSelectable] = [Column("name")] + 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 let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] + static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] } } /// Test SQL generation @@ -48,7 +64,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 +97,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,15 +110,32 @@ 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" \ JOIN "b" ON "b"."id" = "a"."bid" """) } + #if compiler(>=6.1) + do { + let aAlias = TableAlias() + let request = A + .aliased(aAlias) + .including(required: A.b + .select { [ + $0.name, + ($0.id + aAlias.id).forKey("foo") + ] }) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \ + FROM "a" \ + JOIN "b" ON "b"."id" = "a"."bid" + """) + } + #endif } } @@ -140,6 +178,20 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase { JOIN "b" ON ("b"."id" = "a"."bid") AND ("b"."id" IN ("a"."id", "b"."id", 42)) """) } + #if compiler(>=6.1) + do { + let alias = TableAlias() + let request = A + .aliased(alias) + .including(required: A.b + .filter { [alias.id, $0.id, 42].contains($0.id) }) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON ("b"."id" = "a"."bid") AND ("b"."id" IN ("a"."id", "b"."id", 42)) + """) + } + #endif do { let request = A.including(required: A.b.filter(key: ["id": 1])) try assertEqualSQL(db, request, """ @@ -173,16 +225,32 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase { func testFilterAssociationInWhereClause() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let bAlias = TableAlias() - let request = A - .including(required: A.b.aliased(bAlias)) - .filter(bAlias[Column("name")] != nil) - try assertEqualSQL(db, request, """ - SELECT "a".*, "b".* \ - FROM "a" \ - JOIN "b" ON "b"."id" = "a"."bid" \ - WHERE "b"."name" IS NOT NULL - """) + do { + let bAlias = TableAlias() + let request = A + .including(required: A.b.aliased(bAlias)) + .filter(bAlias[Column("name")] != nil) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON "b"."id" = "a"."bid" \ + WHERE "b"."name" IS NOT NULL + """) + } + #if compiler(>=6.1) + do { + let bAlias = TableAlias() + let request = A + .including(required: A.b.aliased(bAlias)) + .filter { _ in bAlias.name != nil } + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON "b"."id" = "a"."bid" \ + WHERE "b"."name" IS NOT NULL + """) + } + #endif } } diff --git a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift index 2e44dfc36..3e4c2fd43 100644 --- a/Tests/GRDBTests/AssociationBelongsToSQLTests.swift +++ b/Tests/GRDBTests/AssociationBelongsToSQLTests.swift @@ -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 diff --git a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift index 932167d5e..686fa14b7 100644 --- a/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift @@ -5,23 +5,39 @@ 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) + + enum Columns { + static let id = Column("id") + } } private struct B : TableRecord { static let a = belongsTo(A.self) static let databaseTableName = "b" + + enum Columns { + static let id = Column("id") + static let aid = Column("aid") + static let name = Column("name") + } } -private struct RestrictedB : TableRecord { +private struct RestrictedB1 : TableRecord { static let databaseTableName = "b" - static let databaseSelection: [any SQLSelectable] = [Column("name")] + 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 let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] + static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] } } /// Test SQL generation @@ -48,11 +64,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 +97,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,15 +110,32 @@ 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" \ JOIN "b" ON "b"."aid" = "a"."id" """) } + #if compiler(>=6.1) + do { + let aAlias = TableAlias() + let request = A + .aliased(aAlias) + .including(required: A.b + .select { [ + $0.name, + ($0.id + aAlias.id).forKey("foo"), + ] }) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \ + FROM "a" \ + JOIN "b" ON "b"."aid" = "a"."id" + """) + } + #endif } } @@ -161,16 +199,32 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase { func testFilterAssociationInWhereClause() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let bAlias = TableAlias() - let request = A - .including(required: A.b.aliased(bAlias)) - .filter(bAlias[Column("name")] != nil) - try assertEqualSQL(db, request, """ - SELECT "a".*, "b".* \ - FROM "a" \ - JOIN "b" ON "b"."aid" = "a"."id" \ - WHERE "b"."name" IS NOT NULL - """) + do { + let bAlias = TableAlias() + let request = A + .including(required: A.b.aliased(bAlias)) + .filter(bAlias[Column("name")] != nil) + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON "b"."aid" = "a"."id" \ + WHERE "b"."name" IS NOT NULL + """) + } + #if compiler(>=6.1) + do { + let bAlias = TableAlias() + let request = A + .including(required: A.b.aliased(bAlias)) + .filter { _ in bAlias.name != nil } + try assertEqualSQL(db, request, """ + SELECT "a".*, "b".* \ + FROM "a" \ + JOIN "b" ON "b"."aid" = "a"."id" \ + WHERE "b"."name" IS NOT NULL + """) + } + #endif } } diff --git a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift index ce9a335e0..913327259 100644 --- a/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift +++ b/Tests/GRDBTests/AssociationHasOneThroughSQLDerivationTests.swift @@ -4,27 +4,48 @@ 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) + + enum Columns { + static let id = Column("id") + static let bid = Column("bid") + } } 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) + + enum Columns { + static let id = Column("id") + static let cid = Column("cid") + } } private struct C: TableRecord { + enum Columns { + static let id = Column("id") + static let name = Column("name") + } } -private struct RestrictedC : TableRecord { +private struct RestrictedC1 : TableRecord { static let databaseTableName = "c" - static let databaseSelection: [any SQLSelectable] = [Column("name")] + 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 let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] + static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] } } /// Test SQL generation @@ -56,7 +77,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 +114,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" \ @@ -111,6 +138,24 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase { JOIN "c" ON "c"."id" = "b"."cId" """) } + #if compiler(>=6.1) + do { + let aAlias = TableAlias() + let request = A + .aliased(aAlias) + .including(required: A.c + .select { [ + $0.name, + ($0.id + aAlias.id).forKey("foo") + ] }) + try assertEqualSQL(db, request, """ + SELECT "a".*, "c"."name", "c"."id" + "a"."id" AS "foo" \ + FROM "a" \ + JOIN "b" ON "b"."id" = "a"."bId" \ + JOIN "c" ON "c"."id" = "b"."cId" + """) + } + #endif } } @@ -180,17 +225,34 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase { func testFilterAssociationInWhereClause() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - let cAlias = TableAlias() - let request = A - .including(required: A.c.aliased(cAlias)) - .filter(cAlias[Column("name")] != nil) - try assertEqualSQL(db, request, """ - SELECT "a".*, "c".* \ - FROM "a" \ - JOIN "b" ON "b"."id" = "a"."bId" \ - JOIN "c" ON "c"."id" = "b"."cId" \ - WHERE "c"."name" IS NOT NULL - """) + do { + let cAlias = TableAlias() + let request = A + .including(required: A.c.aliased(cAlias)) + .filter(cAlias[Column("name")] != nil) + try assertEqualSQL(db, request, """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON "b"."id" = "a"."bId" \ + JOIN "c" ON "c"."id" = "b"."cId" \ + WHERE "c"."name" IS NOT NULL + """) + } + #if compiler(>=6.1) + do { + let cAlias = TableAlias() + let request = A + .including(required: A.c.aliased(cAlias)) + .filter { _ in cAlias.name != nil } + try assertEqualSQL(db, request, """ + SELECT "a".*, "c".* \ + FROM "a" \ + JOIN "b" ON "b"."id" = "a"."bId" \ + JOIN "c" ON "c"."id" = "b"."cId" \ + WHERE "c"."name" IS NOT NULL + """) + } + #endif } } diff --git a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift index 5962b2e7b..ead7d89b9 100644 --- a/Tests/GRDBTests/AssociationPrefetchingRowTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingRowTests.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import XCTest import GRDB diff --git a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift index 5a96828c6..3813344ff 100644 --- a/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift +++ b/Tests/GRDBTests/AssociationPrefetchingSQLTests.swift @@ -80,7 +80,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey()) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -105,7 +105,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey()) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -131,7 +131,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .forKey("bs2")) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -170,7 +170,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .order(Column("colb2"))) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -221,7 +221,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .hasMany(Child.self)) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -244,7 +244,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .hasMany(Child.self)) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -263,7 +263,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .filter(Column("parentA") == "foo") .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -286,7 +286,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey() .limit(1) - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -318,7 +318,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey()) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -352,7 +352,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey()) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -404,7 +404,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .forKey("cs2")) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -502,7 +502,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .including(all: Child.hasMany(GrandChild.self))) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -534,7 +534,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .including(all: Child.hasMany(GrandChild.self))) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -550,7 +550,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .including(all: Child.hasMany(GrandChild.self))) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -576,7 +576,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .filter(Column("name") == "foo") .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -617,7 +617,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey()) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -646,7 +646,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey()) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -699,7 +699,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .forKey("cs2")) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -741,7 +741,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey()) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -777,7 +777,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .forKey("ds3")) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -821,7 +821,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey()) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -856,7 +856,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey()) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -894,7 +894,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey()) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -936,7 +936,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey()) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -970,7 +970,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey()) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1010,7 +1010,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .including(all: A.hasMany(C.self)) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1052,7 +1052,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .including(all: A.hasMany(C.self)) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1098,7 +1098,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .including(all: A.hasMany(C.self)) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1139,7 +1139,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { ) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1191,7 +1191,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .forKey("a2")) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1249,7 +1249,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { ) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1301,7 +1301,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .forKey("c2")) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1361,7 +1361,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey() .filter(Column("cold2") != 8) - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1399,7 +1399,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey() .filter(Column("cold2") != 8) - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1437,7 +1437,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { ) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1492,7 +1492,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .forKey("a2")) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1553,7 +1553,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { ) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1608,7 +1608,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .forKey("c2")) .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1671,7 +1671,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey() .filter(Column("cold2") != 8) - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1712,7 +1712,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .orderByPrimaryKey() .filter(Column("cold2") != 8) - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1755,7 +1755,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { .filter(sql: "1 + 1") .orderByPrimaryKey() - sqlQueries.removeAll() + clearSQLQueries() _ = try Row.fetchAll(db, request) let selectQueries = sqlQueries.filter(isSelectQuery) @@ -1802,7 +1802,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { do { // Group an association - sqlQueries.removeAll() + clearSQLQueries() let association = Team.players.select(max(Column("score"))).group(Column("category")) let request = Team.including(all: association) _ = try Row.fetchAll(db, request) @@ -1821,7 +1821,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { do { // Filter an association with an association aggregate - sqlQueries.removeAll() + clearSQLQueries() let association = Team.players.having(Player.awards.isEmpty) let request = Team.including(all: association) _ = try Row.fetchAll(db, request) @@ -1842,7 +1842,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { do { // Annotate an association with an association aggregate - sqlQueries.removeAll() + clearSQLQueries() let association = Team.players.annotated(with: Player.awards.count) let request = Team.including(all: association) _ = try Row.fetchAll(db, request) @@ -1880,7 +1880,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { try db.execute(sql: "INSERT INTO team DEFAULT VALUES") do { - sqlQueries.removeAll() + clearSQLQueries() let association = Team.players.distinct() let request = Team.including(all: association) _ = try Row.fetchAll(db, request) @@ -1916,7 +1916,7 @@ class AssociationPrefetchingSQLTests: GRDBTestCase { try db.execute(sql: "INSERT INTO team DEFAULT VALUES") do { - sqlQueries.removeAll() + clearSQLQueries() let cte = CommonTableExpression(named: "cte", sql: "SELECT 42") let association = Team.players.with(cte).filter(Column("playerId") == cte.all()) let request = Team.including(all: association) diff --git a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift index 3ecb21d40..c95f3a266 100644 --- a/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift +++ b/Tests/GRDBTests/AssociationTableAliasTestsSQLTests.swift @@ -10,11 +10,23 @@ private struct A : TableRecord { static let child = hasOne(A.self) static let b1 = belongsTo(B.self, key: "b1", using: ForeignKey(["bid1"])) static let b2 = belongsTo(B.self, key: "b2", using: ForeignKey(["bid2"])) + + enum Columns { + static let id = Column("id") + static let bid1 = Column("bid1") + static let bid2 = Column("bid2") + static let parentId = Column("parentId") + static let name = Column("name") + } } private struct B : TableRecord { static let databaseTableName = "b" static let a1 = hasOne(A.self, key: "a1", using: ForeignKey(["bid1"])) static let a2 = hasOne(A.self, key: "a1", using: ForeignKey(["bid2"])) + + enum Columns { + static let id = Column("id") + } } /// Tests for table name conflicts, recursive associations, @@ -118,6 +130,86 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase { } } + #if compiler(>=6.1) + func testTableAliasBasics_swift61() throws { + // A table reference qualifies all unqualified selectables, expressions, and orderings + + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + do { + let alias = TableAlias() + + let expectedSQL = """ + SELECT "name" \ + FROM "a" \ + WHERE ("id" = 1) AND ("name" IS NOT NULL) AND ("name" = 'foo') \ + GROUP BY "name" \ + HAVING "name" \ + ORDER BY "name" + """ + + do { + let request = A + .aliased(alias) + .select(\.name) + .filter(key: 1) + .filter { $0.name != nil && alias.name == "foo" } + .group(\.name) + .having(\.name) + .order(\.name) + try assertEqualSQL(db, request, expectedSQL) + } + do { + let request = A + .select(\.name) + .filter(key: 1) + .filter { $0.name != nil && alias.name == "foo" } + .group(\.name) + .having(\.name) + .order(\.name) + .aliased(alias) + try assertEqualSQL(db, request, expectedSQL) + } + } + do { + let alias = TableAlias(name: "customA") + + let expectedSQL = """ + SELECT "customA"."name" \ + FROM "a" "customA" \ + WHERE ("customA"."id" = 1) AND ("customA"."name" IS NOT NULL) AND ("customA"."name" = 'foo') \ + GROUP BY "customA"."name" \ + HAVING "customA"."name" \ + ORDER BY "customA"."name" + """ + + do { + let request = A + .aliased(alias) + .select(\.name) + .filter(key: 1) + .filter { $0.name != nil && alias.name == "foo" } + .group(\.name) + .having(\.name) + .order(\.name) + try assertEqualSQL(db, request, expectedSQL) + } + do { + let request = A + .select(\.name) + .filter(key: 1) + .filter { $0.name != nil && alias.name == "foo" } + .group(\.name) + .having(\.name) + .order(\.name) + .aliased(alias) + try assertEqualSQL(db, request, expectedSQL) + } + } + } + } + #endif + func testRecursiveRelationDepth1() throws { // A.include(A.parent) // A.include(A.child) diff --git a/Tests/GRDBTests/AsyncSemaphore.swift b/Tests/GRDBTests/AsyncSemaphore.swift new file mode 100644 index 000000000..97691ab67 --- /dev/null +++ b/Tests/GRDBTests/AsyncSemaphore.swift @@ -0,0 +1,255 @@ +// Vendored from + +// Copyright (C) 2022 Gwendal Roué +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +import Foundation + +/// An object that controls access to a resource across multiple execution +/// contexts through use of a traditional counting semaphore. +/// +/// You increment a semaphore count by calling the ``signal()`` method, and +/// decrement a semaphore count by calling ``wait()`` or one of its variants. +/// +/// ## Topics +/// +/// ### Creating a Semaphore +/// +/// - ``init(value:)`` +/// +/// ### Signaling the Semaphore +/// +/// - ``signal()`` +/// +/// ### Waiting for the Semaphore +/// +/// - ``wait()`` +/// - ``waitUnlessCancelled()`` +public final class AsyncSemaphore: @unchecked Sendable { + /// `Suspension` is the state of a task waiting for a signal. + /// + /// It is a class because instance identity helps `waitUnlessCancelled()` + /// deal with both early and late cancellation. + /// + /// We make it @unchecked Sendable in order to prevent compiler warnings: + /// instances are always protected by the semaphore's lock. + private class Suspension: @unchecked Sendable { + enum State { + /// Initial state. Next is suspendedUnlessCancelled, or cancelled. + case pending + + /// Waiting for a signal, with support for cancellation. + case suspendedUnlessCancelled(UnsafeContinuation) + + /// Waiting for a signal, with no support for cancellation. + case suspended(UnsafeContinuation) + + /// Cancelled before we have started waiting. + case cancelled + } + + var state: State + + init(state: State) { + self.state = state + } + } + + // MARK: - Internal State + + /// The semaphore value. + private var value: Int + + /// As many elements as there are suspended tasks waiting for a signal. + private var suspensions: [Suspension] = [] + + /// The lock that protects `value` and `suspensions`. + /// + /// It is recursive in order to handle cancellation (see the implementation + /// of ``waitUnlessCancelled()``). + private let _lock = NSRecursiveLock() + + // MARK: - Creating a Semaphore + + /// Creates a semaphore. + /// + /// - parameter value: The starting value for the semaphore. Do not pass a + /// value less than zero. + public init(value: Int) { + precondition(value >= 0, "AsyncSemaphore requires a value equal or greater than zero") + self.value = value + } + + deinit { + precondition(suspensions.isEmpty, "AsyncSemaphore is deallocated while some task(s) are suspended waiting for a signal.") + } + + // MARK: - Locking + + // Let's hide the locking primitive in order to avoid a compiler warning: + // + // > Instance method 'lock' is unavailable from asynchronous contexts; + // > Use async-safe scoped locking instead; this is an error in Swift 6. + // + // We're not sweeping bad stuff under the rug. We really need to protect + // our inner state (`value` and `suspension`) across the calls to + // `withUnsafeContinuation`. Unfortunately, this method introduces a + // suspension point. So we need a lock. + private func lock() { _lock.lock() } + private func unlock() { _lock.unlock() } + + // MARK: - Waiting for the Semaphore + + /// Waits for, or decrements, a semaphore. + /// + /// Decrement the counting semaphore. If the resulting value is less than + /// zero, this function suspends the current task until a signal occurs, + /// without blocking the underlying thread. Otherwise, no suspension happens. + public func wait() async { + lock() + + value -= 1 + if value >= 0 { + unlock() + return + } + + await withUnsafeContinuation { continuation in + // Register the continuation that `signal` will resume. + let suspension = Suspension(state: .suspended(continuation)) + suspensions.insert(suspension, at: 0) // FIFO + unlock() + } + } + + /// Waits for, or decrements, a semaphore, with support for cancellation. + /// + /// Decrement the counting semaphore. If the resulting value is less than + /// zero, this function suspends the current task until a signal occurs, + /// without blocking the underlying thread. Otherwise, no suspension happens. + /// + /// If the task is canceled before a signal occurs, this function + /// throws `CancellationError`. + public func waitUnlessCancelled() async throws { + lock() + + value -= 1 + if value >= 0 { + defer { unlock() } + + do { + // All code paths check for cancellation + try Task.checkCancellation() + } catch { + // Cancellation is like a signal: we don't really "consume" + // the semaphore, and restore the value. + value += 1 + throw error + } + + return + } + + // Get ready for being suspended waiting for a continuation, or for + // early cancellation. + let suspension = Suspension(state: .pending) + + try await withTaskCancellationHandler { + try await withUnsafeThrowingContinuation { (continuation: UnsafeContinuation) in + if case .cancelled = suspension.state { + // Early cancellation: waitUnlessCancelled() is called from + // a cancelled task, and the `onCancel` closure below + // has marked the suspension as cancelled. + // Resume with a CancellationError. + unlock() + continuation.resume(throwing: CancellationError()) + } else { + // Current task is not cancelled: register the continuation + // that `signal` will resume. + suspension.state = .suspendedUnlessCancelled(continuation) + suspensions.insert(suspension, at: 0) // FIFO + unlock() + } + } + } onCancel: { + // withTaskCancellationHandler may immediately call this block (if + // the current task is cancelled), or call it later (if the task is + // cancelled later). In the first case, we're still holding the lock, + // waiting for the continuation. In the second case, we do not hold + // the lock. Being able to handle both situations is the reason why + // we use a recursive lock. + lock() + + // We're no longer waiting for a signal + value += 1 + if let index = suspensions.firstIndex(where: { $0 === suspension }) { + suspensions.remove(at: index) + } + + if case let .suspendedUnlessCancelled(continuation) = suspension.state { + // Late cancellation: the task is cancelled while waiting + // from the semaphore. Resume with a CancellationError. + unlock() + continuation.resume(throwing: CancellationError()) + } else { + // Early cancellation: waitUnlessCancelled() is called from + // a cancelled task. + // + // The next step is the `withTaskCancellationHandler` + // operation closure right above. + suspension.state = .cancelled + unlock() + } + } + } + + // MARK: - Signaling the Semaphore + + /// Signals (increments) a semaphore. + /// + /// Increment the counting semaphore. If the previous value was less than + /// zero, this function resumes a task currently suspended in ``wait()`` + /// or ``waitUnlessCancelled()``. + /// + /// - returns: This function returns true if a suspended task is + /// resumed. Otherwise, the result is false, meaning that no task was + /// waiting for the semaphore. + @discardableResult + public func signal() -> Bool { + lock() + + value += 1 + + switch suspensions.popLast()?.state { // FIFO + case let .suspendedUnlessCancelled(continuation): + unlock() + continuation.resume() + return true + case let .suspended(continuation): + unlock() + continuation.resume() + return true + default: + unlock() + return false + } + } +} diff --git a/Tests/GRDBTests/BackupTestCase.swift b/Tests/GRDBTests/BackupTestCase.swift index 33b2f1ac6..4ea5d049f 100644 --- a/Tests/GRDBTests/BackupTestCase.swift +++ b/Tests/GRDBTests/BackupTestCase.swift @@ -84,7 +84,7 @@ class BackupTestCase: GRDBTestCase { let sourceDbPageCount = try setupBackupSource(source) try setupBackupDestination(destination) - try source.write { sourceDb in + try source.read { sourceDb in try destination.barrierWriteWithoutTransaction { destDb in XCTAssertThrowsError( try sourceDb.backup(to: destDb, pagesPerStep: 1) { progress in @@ -102,7 +102,7 @@ class BackupTestCase: GRDBTestCase { XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT id FROM items")!, 1) } - try source.write { dbSource in + try source.read { dbSource in try destination.barrierWriteWithoutTransaction { dbDest in var progressCount: Int = 1 var isCompleted: Bool = false diff --git a/Tests/GRDBTests/ColumnExpressionTests.swift b/Tests/GRDBTests/ColumnExpressionTests.swift index b716a0700..5cd5ddf0c 100644 --- a/Tests/GRDBTests/ColumnExpressionTests.swift +++ b/Tests/GRDBTests/ColumnExpressionTests.swift @@ -20,7 +20,9 @@ class ColumnExpressionTests: GRDBTestCase { } // Test databaseSelection - static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score] + static var databaseSelection: [any SQLSelectable] { + [Columns.id, Columns.name, Columns.score] + } init(row: Row) { // Test row subscript @@ -38,7 +40,7 @@ class ColumnExpressionTests: GRDBTestCase { static var testRequest: QueryInterfaceRequest { // Test expression derivation - return filter(Columns.name != nil).order(Columns.score.desc) + filter { $0.name != nil }.order { $0.score.desc } } } @@ -52,10 +54,10 @@ class ColumnExpressionTests: GRDBTestCase { // Test rowId column identification try XCTAssertEqual(Player.filter(key: 1).databaseRegion(db).description, "player(id,name,score)[1]") - try XCTAssertEqual(Player.filter(Player.Columns.id == 1).databaseRegion(db).description, "player(id,name,score)[1]") - try XCTAssertEqual(Player.filter(1 == Player.Columns.id).databaseRegion(db).description, "player(id,name,score)[1]") - try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).databaseRegion(db).description, "player(id,name,score)[1,2]") - try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "player(id,name,score)[1,2,3]") + try XCTAssertEqual(Player.filter { $0.id == 1 }.databaseRegion(db).description, "player(id,name,score)[1]") + try XCTAssertEqual(Player.filter { 1 == $0.id }.databaseRegion(db).description, "player(id,name,score)[1]") + try XCTAssertEqual(Player.filter { $0.id == 1 || $0.id == 2 }.databaseRegion(db).description, "player(id,name,score)[1,2]") + try XCTAssertEqual(Player.filter { [1, 2, 3].contains($0.id) }.databaseRegion(db).description, "player(id,name,score)[1,2,3]") // Test specific column updates let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000]) @@ -63,8 +65,7 @@ class ColumnExpressionTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") // Test compound expression - let expression = Player.Columns.name == "foo" - let request = Player.select(expression) + let request = Player.select { $0.name == "foo" } try assertEqualSQL(db, request, "SELECT \"name\" = 'foo' FROM \"player\"") } } @@ -80,7 +81,9 @@ class ColumnExpressionTests: GRDBTestCase { } // Test databaseSelection - static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score] + static var databaseSelection: [any SQLSelectable] { + [Columns.id, Columns.name, Columns.score] + } init(row: Row) { // Test row subscript @@ -98,7 +101,7 @@ class ColumnExpressionTests: GRDBTestCase { static var testRequest: QueryInterfaceRequest { // Test expression derivation - return filter(Columns.name != nil).order(Columns.score.desc) + filter { $0.name != nil }.order { $0.score.desc } } } @@ -112,10 +115,10 @@ class ColumnExpressionTests: GRDBTestCase { // Test rowId column identification try XCTAssertEqual(Player.filter(key: 1).databaseRegion(db).description, "player(id,name,score)[1]") - try XCTAssertEqual(Player.filter(Player.Columns.id == 1).databaseRegion(db).description, "player(id,name,score)[1]") - try XCTAssertEqual(Player.filter(1 == Player.Columns.id).databaseRegion(db).description, "player(id,name,score)[1]") - try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).databaseRegion(db).description, "player(id,name,score)[1,2]") - try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "player(id,name,score)[1,2,3]") + try XCTAssertEqual(Player.filter { $0.id == 1 }.databaseRegion(db).description, "player(id,name,score)[1]") + try XCTAssertEqual(Player.filter { 1 == $0.id }.databaseRegion(db).description, "player(id,name,score)[1]") + try XCTAssertEqual(Player.filter { $0.id == 1 || $0.id == 2 }.databaseRegion(db).description, "player(id,name,score)[1,2]") + try XCTAssertEqual(Player.filter { [1, 2, 3].contains($0.id) }.databaseRegion(db).description, "player(id,name,score)[1,2,3]") // Test specific column updates let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000]) @@ -123,8 +126,7 @@ class ColumnExpressionTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") // Test compound expression - let expression = Player.Columns.name == "foo" - let request = Player.select(expression) + let request = Player.select { $0.name == "foo" } try assertEqualSQL(db, request, "SELECT \"name\" = 'foo' FROM \"player\"") } } @@ -148,11 +150,13 @@ class ColumnExpressionTests: GRDBTestCase { } // Test databaseSelection - static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score] + static var databaseSelection: [any SQLSelectable] { + [Columns.id, Columns.name, Columns.score] + } static var testRequest: QueryInterfaceRequest { // Test expression derivation - return filter(Columns.name != nil).order(Columns.score.desc) + filter { $0.name != nil }.order { $0.score.desc } } } @@ -166,10 +170,10 @@ class ColumnExpressionTests: GRDBTestCase { // Test rowId column identification try XCTAssertEqual(Player.filter(key: 1).databaseRegion(db).description, "player(full_name,id,score)[1]") - try XCTAssertEqual(Player.filter(Player.Columns.id == 1).databaseRegion(db).description, "player(full_name,id,score)[1]") - try XCTAssertEqual(Player.filter(1 == Player.Columns.id).databaseRegion(db).description, "player(full_name,id,score)[1]") - try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).databaseRegion(db).description, "player(full_name,id,score)[1,2]") - try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "player(full_name,id,score)[1,2,3]") + try XCTAssertEqual(Player.filter { $0.id == 1 }.databaseRegion(db).description, "player(full_name,id,score)[1]") + try XCTAssertEqual(Player.filter { 1 == $0.id }.databaseRegion(db).description, "player(full_name,id,score)[1]") + try XCTAssertEqual(Player.filter { $0.id == 1 || $0.id == 2 }.databaseRegion(db).description, "player(full_name,id,score)[1,2]") + try XCTAssertEqual(Player.filter { [1, 2, 3].contains($0.id) }.databaseRegion(db).description, "player(full_name,id,score)[1,2,3]") // Test specific column updates let player = try Player(row: ["id": 1, "full_name": "Arthur", "score": 1000]) @@ -177,8 +181,7 @@ class ColumnExpressionTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"full_name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1") // Test compound expression - let expression = Player.Columns.name == "foo" - let request = Player.select(expression) + let request = Player.select { $0.name == "foo" } try assertEqualSQL(db, request, "SELECT \"full_name\" = 'foo' FROM \"player\"") } } @@ -196,7 +199,9 @@ class ColumnExpressionTests: GRDBTestCase { } // Test databaseSelection - static let databaseSelection: [any SQLSelectable] = [CodingKeys.id, CodingKeys.name, CodingKeys.score] + static var databaseSelection: [any SQLSelectable] { + [CodingKeys.id, CodingKeys.name, CodingKeys.score] + } static var testRequest: QueryInterfaceRequest { // Test expression derivation diff --git a/Tests/GRDBTests/CommonTableExpressionTests.swift b/Tests/GRDBTests/CommonTableExpressionTests.swift index 448b06add..1d87105e4 100644 --- a/Tests/GRDBTests/CommonTableExpressionTests.swift +++ b/Tests/GRDBTests/CommonTableExpressionTests.swift @@ -26,7 +26,12 @@ class CommonTableExpressionTests: GRDBTestCase { } func testQuery() throws { - struct T: TableRecord { } + struct T: TableRecord { + enum Columns { + static let id = Column("id") + } + } + try makeDatabaseQueue().write { db in try db.create(table: "t") { t in t.autoIncrementedPrimaryKey("id") @@ -96,6 +101,20 @@ class CommonTableExpressionTests: GRDBTestCase { LEFT JOIN "cte" ON "t"."id" > "cte"."id" """) } + #if compiler(>=6.1) + do { + let cte = CommonTableExpression(named: "cte", request: T.all()) + let request = T.all() + .with(cte) + .including(optional: T.association(to: cte, on: { $0.id > $1.id })) + try assertEqualSQL(db, request, """ + WITH "cte" AS (SELECT * FROM "t") \ + SELECT "t".*, "cte".* \ + FROM "t" \ + LEFT JOIN "cte" ON "t"."id" > "cte"."id" + """) + } + #endif // Include SQL request as a CTE do { @@ -112,6 +131,22 @@ class CommonTableExpressionTests: GRDBTestCase { JOIN "cte" ON "t"."id" = "cte"."id" """) } + #if compiler(>=6.1) + do { + let cte = CommonTableExpression( + named: "cte", + literal: "SELECT 1 as id") + let request = T.all() + .with(cte) + .including(required: T.association(to: cte, on: { $0.id == $1["id"] })) + try assertEqualSQL(db, request, """ + WITH "cte" AS (SELECT 1 as id) \ + SELECT "t".*, "cte".* \ + FROM "t" \ + JOIN "cte" ON "t"."id" = "cte"."id" + """) + } + #endif // Include a filtered SQL request as a CTE do { @@ -145,6 +180,23 @@ class CommonTableExpressionTests: GRDBTestCase { JOIN "cte" ON "t"."id" = "cte"."id" """) } + #if compiler(>=6.1) + do { + let cte = CommonTableExpression( + named: "cte", + columns: [], + literal: "SELECT 1 AS id") + let request = T.all() + .with(cte) + .including(required: T.association(to: cte, on: { $0.id == $1["id"] })) + try assertEqualSQL(db, request, """ + WITH "cte" AS (SELECT 1 AS id) \ + SELECT "t".*, "cte".* \ + FROM "t" \ + JOIN "cte" ON "t"."id" = "cte"."id" + """) + } + #endif // Include SQL request as a CTE (custom column name) do { @@ -162,6 +214,23 @@ class CommonTableExpressionTests: GRDBTestCase { JOIN "cte" ON "t"."id" = "cte"."id" """) } + #if compiler(>=6.1) + do { + let cte = CommonTableExpression( + named: "cte", + columns: ["id", "a"], + literal: "SELECT 1, 2") + let request = T.all() + .with(cte) + .including(required: T.association(to: cte, on: { $0.id == $1["id"] })) + try assertEqualSQL(db, request, """ + WITH "cte"("id", "a") AS (SELECT 1, 2) \ + SELECT "t".*, "cte".* \ + FROM "t" \ + JOIN "cte" ON "t"."id" = "cte"."id" + """) + } + #endif // Include SQL request as a CTE (empty ON clause) do { @@ -192,6 +261,20 @@ class CommonTableExpressionTests: GRDBTestCase { JOIN "cte" ON "t"."id" > "cte"."id" """) } + #if compiler(>=6.1) + do { + let cte = CommonTableExpression(named: "cte", request: T.all()) + let request = T.all() + .with(cte) + .joining(required: T.association(to: cte, on: { $0.id > $1.id })) + try assertEqualSQL(db, request, """ + WITH "cte" AS (SELECT * FROM "t") \ + SELECT "t".* \ + FROM "t" \ + JOIN "cte" ON "t"."id" > "cte"."id" + """) + } + #endif // Include filtered CTE do { @@ -253,6 +336,21 @@ class CommonTableExpressionTests: GRDBTestCase { JOIN "cte" ON "t"."id" > "cte"."id" """) } + #if compiler(>=6.1) + do { + let cte = CommonTableExpression(named: "cte", request: T.all()) + let request = T.all() + .with(cte) + .including(required: T.association(to: cte, on: { $0.id > $1.id })) + .including(required: T.association(to: cte, on: { $0.id > $1.id })) + try assertEqualSQL(db, request, """ + WITH "cte" AS (SELECT * FROM "t") \ + SELECT "t".*, "cte".* \ + FROM "t" \ + JOIN "cte" ON "t"."id" > "cte"."id" + """) + } + #endif // Include one CTE twice with same key but different condition (last condition wins) do { @@ -268,6 +366,21 @@ class CommonTableExpressionTests: GRDBTestCase { JOIN "cte" ON ("t"."id" + "cte"."id") = 1 """) } + #if compiler(>=6.1) + do { + let cte = CommonTableExpression(named: "cte", request: T.all()) + let request = T.all() + .with(cte) + .including(required: T.association(to: cte, on: { $0.id > $1.id })) + .including(required: T.association(to: cte, on: { $0.id + $1.id == 1 })) + try assertEqualSQL(db, request, """ + WITH "cte" AS (SELECT * FROM "t") \ + SELECT "t".*, "cte".* \ + FROM "t" \ + JOIN "cte" ON ("t"."id" + "cte"."id") = 1 + """) + } + #endif // Include one CTE twice with different keys do { @@ -284,6 +397,22 @@ class CommonTableExpressionTests: GRDBTestCase { JOIN "cte" "cte2" ON "t"."id" < "cte2"."id" """) } + #if compiler(>=6.1) + do { + let cte = CommonTableExpression(named: "cte", request: T.all()) + let request = T.all() + .with(cte) + .including(required: T.association(to: cte, on: { $0.id > $1.id }).forKey("a")) + .including(required: T.association(to: cte, on: { $0.id < $1.id }).forKey("b")) + try assertEqualSQL(db, request, """ + WITH "cte" AS (SELECT * FROM "t") \ + SELECT "t".*, "cte1".*, "cte2".* \ + FROM "t" \ + JOIN "cte" "cte1" ON "t"."id" > "cte1"."id" \ + JOIN "cte" "cte2" ON "t"."id" < "cte2"."id" + """) + } + #endif // Chain CTE includes do { diff --git a/Tests/GRDBTests/DataMemoryTests.swift b/Tests/GRDBTests/DataMemoryTests.swift index a6f329298..3f572fc30 100644 --- a/Tests/GRDBTests/DataMemoryTests.swift +++ b/Tests/GRDBTests/DataMemoryTests.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import XCTest @testable import GRDB diff --git a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift index d6229e88d..1ac85a08f 100644 --- a/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift +++ b/Tests/GRDBTests/DatabaseAbortedTransactionTests.swift @@ -40,7 +40,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -85,7 +85,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(makeDatabasePool().makeSnapshotPool()) #endif } diff --git a/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift b/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift index 3daa8f55c..9e01b79a8 100644 --- a/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift +++ b/Tests/GRDBTests/DatabaseAfterNextTransactionCommitTests.swift @@ -42,7 +42,7 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in - var commitCount = 0 + let commitCountMutex = Mutex(0) weak var deallocationWitness: Witness? = nil do { let witness = Witness() @@ -51,19 +51,19 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { db.afterNextTransaction { _ in // use witness withExtendedLifetime(witness, { }) - commitCount += 1 + commitCountMutex.increment() } } XCTAssertNotNil(deallocationWitness) - XCTAssertEqual(commitCount, 0) + XCTAssertEqual(commitCountMutex.load(), 0) try db.execute(sql: startSQL) try db.execute(sql: endSQL) switch expectedCompletion { case .commit: - XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCountMutex.load(), 1, "\(startSQL); \(endSQL)") case .rollback: - XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCountMutex.load(), 0, "\(startSQL); \(endSQL)") } XCTAssertNil(deallocationWitness) @@ -73,9 +73,9 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { } switch expectedCompletion { case .commit: - XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCountMutex.load(), 1, "\(startSQL); \(endSQL)") case .rollback: - XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCountMutex.load(), 0, "\(startSQL); \(endSQL)") } } } @@ -85,8 +85,8 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in - var commitCount = 0 - var rollbackCount = 0 + let commitCountMutex = Mutex(0) + let rollbackCountMutex = Mutex(0) try db.execute(sql: startSQL) weak var deallocationWitness: Witness? = nil @@ -98,25 +98,25 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { onCommit: { _ in // use witness withExtendedLifetime(witness, { }) - commitCount += 1 + commitCountMutex.increment() }, onRollback: { _ in // use witness withExtendedLifetime(witness, { }) - rollbackCount += 1 + rollbackCountMutex.increment() }) } XCTAssertNotNil(deallocationWitness) - XCTAssertEqual(commitCount, 0) + XCTAssertEqual(commitCountMutex.load(), 0) try db.execute(sql: endSQL) switch expectedCompletion { case .commit: - XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") - XCTAssertEqual(rollbackCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCountMutex.load(), 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(rollbackCountMutex.load(), 0, "\(startSQL); \(endSQL)") case .rollback: - XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") - XCTAssertEqual(rollbackCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCountMutex.load(), 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(rollbackCountMutex.load(), 1, "\(startSQL); \(endSQL)") } XCTAssertNil(deallocationWitness) @@ -126,11 +126,11 @@ class DatabaseAfterNextTransactionCommitTests: GRDBTestCase { } switch expectedCompletion { case .commit: - XCTAssertEqual(commitCount, 1, "\(startSQL); \(endSQL)") - XCTAssertEqual(rollbackCount, 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCountMutex.load(), 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(rollbackCountMutex.load(), 0, "\(startSQL); \(endSQL)") case .rollback: - XCTAssertEqual(commitCount, 0, "\(startSQL); \(endSQL)") - XCTAssertEqual(rollbackCount, 1, "\(startSQL); \(endSQL)") + XCTAssertEqual(commitCountMutex.load(), 0, "\(startSQL); \(endSQL)") + XCTAssertEqual(rollbackCountMutex.load(), 1, "\(startSQL); \(endSQL)") } } } diff --git a/Tests/GRDBTests/DatabaseConfigurationTests.swift b/Tests/GRDBTests/DatabaseConfigurationTests.swift index 7ff0f4702..64a09cf51 100644 --- a/Tests/GRDBTests/DatabaseConfigurationTests.swift +++ b/Tests/GRDBTests/DatabaseConfigurationTests.swift @@ -6,40 +6,40 @@ class DatabaseConfigurationTests: GRDBTestCase { func testPrepareDatabase() throws { // prepareDatabase is called when connection opens - var connectionCount = 0 + let connectionCountMutex = Mutex(0) var configuration = Configuration() configuration.prepareDatabase { db in - connectionCount += 1 + connectionCountMutex.increment() } _ = try DatabaseQueue(configuration: configuration) - XCTAssertEqual(connectionCount, 1) + XCTAssertEqual(connectionCountMutex.load(), 1) _ = try makeDatabaseQueue(configuration: configuration) - XCTAssertEqual(connectionCount, 2) + XCTAssertEqual(connectionCountMutex.load(), 2) let pool = try makeDatabasePool(configuration: configuration) - XCTAssertEqual(connectionCount, 3) + XCTAssertEqual(connectionCountMutex.load(), 3) try pool.read { _ in } - XCTAssertEqual(connectionCount, 4) + XCTAssertEqual(connectionCountMutex.load(), 4) try pool.makeSnapshot().read { _ in } - XCTAssertEqual(connectionCount, 5) + XCTAssertEqual(connectionCountMutex.load(), 5) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try pool.makeSnapshotPool().read { _ in } - XCTAssertEqual(connectionCount, 6) + XCTAssertEqual(connectionCountMutex.load(), 6) #endif } func testPrepareDatabaseError() throws { struct TestError: Error { } - var error: TestError? + let errorMutex: Mutex = Mutex(nil) var configuration = Configuration() configuration.prepareDatabase { db in - if let error { + if let error = errorMutex.load() { throw error } } @@ -47,36 +47,36 @@ class DatabaseConfigurationTests: GRDBTestCase { // TODO: what about in-memory DatabaseQueue??? do { - error = TestError() + errorMutex.store(TestError()) _ = try makeDatabaseQueue(configuration: configuration) XCTFail("Expected TestError") } catch is TestError { } do { - error = TestError() + errorMutex.store(TestError()) _ = try makeDatabasePool(configuration: configuration) XCTFail("Expected TestError") } catch is TestError { } do { - error = nil + errorMutex.store(nil) let pool = try makeDatabasePool(configuration: configuration) do { - error = TestError() + errorMutex.store(TestError()) try pool.read { _ in } XCTFail("Expected TestError") } catch is TestError { } do { - error = TestError() + errorMutex.store(TestError()) _ = try pool.makeSnapshot() XCTFail("Expected TestError") } catch is TestError { } -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) do { - error = TestError() + errorMutex.store(TestError()) _ = try pool.makeSnapshotPool() XCTFail("Expected TestError") } catch is TestError { } @@ -130,14 +130,13 @@ 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") } } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) - XCTAssertEqual(error.message, "no such column: foo") XCTAssertEqual(error.sql, "SELECT \"foo\" FROM player") } @@ -146,15 +145,11 @@ 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 { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) - XCTAssert([ - "no such column: foo", - "table player has no column named foo"] - .contains(error.message)) XCTAssertEqual(error.sql, "CREATE INDEX i ON player(\"foo\")") } } diff --git a/Tests/GRDBTests/DatabaseCursorTests.swift b/Tests/GRDBTests/DatabaseCursorTests.swift index d18191488..6b43570b4 100644 --- a/Tests/GRDBTests/DatabaseCursorTests.swift +++ b/Tests/GRDBTests/DatabaseCursorTests.swift @@ -175,42 +175,49 @@ class DatabaseCursorTests: GRDBTestCase { // with raw C SQLite3 apis. The faulty line is the call to // sqlite3_set_authorizer during the statement iteration. -// if #available(OSX 10.14, *) { -// var connection: SQLiteConnection? = nil -// sqlite3_open_v2(":memory:", &connection, SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX, nil) -// sqlite3_extended_result_codes(connection, 1) +// var connection: SQLiteConnection? = nil +// sqlite3_open_v2(":memory:", &connection, SQLITE_OPEN_READWRITE | SQLITE_OPEN_NOMUTEX, nil) +// sqlite3_extended_result_codes(connection, 1) // -// sqlite3_exec(connection, """ -// CREATE TABLE user (username TEXT NOT NULL); -// CREATE TABLE flagUser (username TEXT NOT NULL); -// INSERT INTO flagUser (username) VALUES ('User1'); -// INSERT INTO flagUser (username) VALUES ('User2'); -// """, nil, nil, nil) +// sqlite3_exec(connection, """ +// CREATE TABLE user (username TEXT NOT NULL); +// CREATE TABLE flagUser (username TEXT NOT NULL); +// INSERT INTO flagUser (username) VALUES ('User1'); +// INSERT INTO flagUser (username) VALUES ('User2'); +// """, nil, nil, nil) // -// var statement: SQLiteStatement? = nil -// sqlite3_set_authorizer(connection, { (_, _, _, _, _, _) in SQLITE_OK }, nil) -// sqlite3_prepare_v3(connection, """ -// SELECT * FROM flagUser WHERE (SELECT COUNT(*) FROM user WHERE username = flagUser.username) = 0 -// """, -1, 0, &statement, nil) -// sqlite3_set_authorizer(connection, nil, nil) -// while true { -// let code = sqlite3_step(statement) -// if code == SQLITE_DONE { -// break -// } else if code == SQLITE_ROW { -// // part of the compilation of another statement, here -// // reduced to the strict minimum that reproduces -// // the error. -// sqlite3_set_authorizer(connection, nil, nil) -// } else { -// print(String(cString: sqlite3_errmsg(connection))) -// XCTFail("Error \(code)") -// break -// } +// var statement: SQLiteStatement? = nil +// sqlite3_set_authorizer(connection, { (_, _, _, _, _, _) in SQLITE_OK }, nil) +// sqlite3_prepare_v3(connection, """ +// SELECT * FROM flagUser WHERE (SELECT COUNT(*) FROM user WHERE username = flagUser.username) = 0 +// """, -1, 0, &statement, nil) +// sqlite3_set_authorizer(connection, nil, nil) +// while true { +// let code = sqlite3_step(statement) +// if code == SQLITE_DONE { +// break +// } else if code == SQLITE_ROW { +// // part of the compilation of another statement, here +// // reduced to the strict minimum that reproduces +// // the error. +// sqlite3_set_authorizer(connection, nil, nil) +// } else { +// print(String(cString: sqlite3_errmsg(connection))) +// XCTFail("Error \(code)") +// break // } -// sqlite3_finalize(statement) -// sqlite3_close_v2(connection) // } +// sqlite3_finalize(statement) +// sqlite3_close_v2(connection) + } + + // This test passes if it compiles + func testAssociatedType() throws { + func accept(_ cursor: some DatabaseCursor) { } + func useCursor(_ db: Database) throws { + let cursor = try String.fetchCursor(db, sql: "SELECT 'foo'") + accept(cursor) + } } // For profiling tests diff --git a/Tests/GRDBTests/DatabaseDataDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDataDecodingStrategyTests.swift index 8ff1da13b..a11493297 100644 --- a/Tests/GRDBTests/DatabaseDataDecodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDataDecodingStrategyTests.swift @@ -20,12 +20,18 @@ private enum StrategyCustom: StrategyProvider { } private struct RecordWithData: FetchableRecord, Decodable { - static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { Strategy.strategy } + static func databaseDataDecodingStrategy(for column: String) -> DatabaseDataDecodingStrategy { + Strategy.strategy + } + var data: Data } private struct RecordWithOptionalData: FetchableRecord, Decodable { - static var databaseDataDecodingStrategy: DatabaseDataDecodingStrategy { Strategy.strategy } + static func databaseDataDecodingStrategy(for column: String) -> DatabaseDataDecodingStrategy { + Strategy.strategy + } + var data: Data? } diff --git a/Tests/GRDBTests/DatabaseDataEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDataEncodingStrategyTests.swift index 6fdf7d875..61f42d751 100644 --- a/Tests/GRDBTests/DatabaseDataEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDataEncodingStrategyTests.swift @@ -19,21 +19,23 @@ private enum StrategyCustom: StrategyProvider { } private struct RecordWithData: EncodableRecord, Encodable { - static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { Strategy.strategy } + static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy { + Strategy.strategy + } var data: Data } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension RecordWithData: Identifiable { var id: Data { data } } private struct RecordWithOptionalData: EncodableRecord, Encodable { - static var databaseDataEncodingStrategy: DatabaseDataEncodingStrategy { Strategy.strategy } + static func databaseDataEncodingStrategy(for column: String) -> DatabaseDataEncodingStrategy { + Strategy.strategy + } var data: Data? } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension RecordWithOptionalData: Identifiable { var id: Data? { data } } @@ -150,10 +152,6 @@ extension DatabaseDataEncodingStrategyTests { } func testFilterID() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - try makeDatabaseQueue().write { db in try db.create(table: "t") { $0.primaryKey("id", .blob) } @@ -230,10 +228,6 @@ extension DatabaseDataEncodingStrategyTests { } func testDeleteID() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - try makeDatabaseQueue().write { db in try db.create(table: "t") { $0.primaryKey("id", .blob) } @@ -266,7 +260,7 @@ extension DatabaseDataEncodingStrategyTests { } do { - sqlQueries.removeAll() + clearSQLQueries() try Table>("t").deleteOne(db, id: nil) XCTAssertNil(lastSQLQuery) // Database not hit } @@ -286,7 +280,7 @@ extension DatabaseDataEncodingStrategyTests { } do { - sqlQueries.removeAll() + clearSQLQueries() try Table>("t").deleteOne(db, id: nil) XCTAssertNil(lastSQLQuery) // Database not hit } diff --git a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift index 5f920fe73..c813d377f 100644 --- a/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateDecodingStrategyTests.swift @@ -47,12 +47,18 @@ private enum StrategyCustom: StrategyProvider { } private struct RecordWithDate: FetchableRecord, Decodable { - static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { Strategy.strategy } + static func databaseDateDecodingStrategy(for column: String) -> DatabaseDateDecodingStrategy { + Strategy.strategy + } + var date: Date } private struct RecordWithOptionalDate: FetchableRecord, Decodable { - static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { Strategy.strategy } + static func databaseDateDecodingStrategy(for column: String) -> DatabaseDateDecodingStrategy { + Strategy.strategy + } + var date: Date? } diff --git a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift index 98b1ab605..90ab8c410 100644 --- a/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseDateEncodingStrategyTests.swift @@ -46,21 +46,23 @@ private enum StrategyCustom: StrategyProvider { } private struct RecordWithDate: EncodableRecord, Encodable { - static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { Strategy.strategy } + static func databaseDateEncodingStrategy(for column: String) -> DatabaseDateEncodingStrategy { + Strategy.strategy + } var date: Date } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension RecordWithDate: Identifiable { var id: Date { date } } private struct RecordWithOptionalDate: EncodableRecord, Encodable { - static var databaseDateEncodingStrategy: DatabaseDateEncodingStrategy { Strategy.strategy } + static func databaseDateEncodingStrategy(for column: String) -> DatabaseDateEncodingStrategy { + Strategy.strategy + } var date: Date? } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension RecordWithOptionalDate: Identifiable { var id: Date? { date } } @@ -260,10 +262,6 @@ extension DatabaseDateEncodingStrategyTests { } func testFilterID() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - try makeDatabaseQueue().write { db in try db.create(table: "t") { $0.primaryKey("id", .datetime) } @@ -340,10 +338,6 @@ extension DatabaseDateEncodingStrategyTests { } func testDeleteID() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - try makeDatabaseQueue().write { db in try db.create(table: "t") { $0.primaryKey("id", .datetime) } @@ -376,7 +370,7 @@ extension DatabaseDateEncodingStrategyTests { } do { - sqlQueries.removeAll() + clearSQLQueries() try Table>("t").deleteOne(db, id: nil) XCTAssertNil(lastSQLQuery) // Database not hit } @@ -396,7 +390,7 @@ extension DatabaseDateEncodingStrategyTests { } do { - sqlQueries.removeAll() + clearSQLQueries() try Table>("t").deleteOne(db, id: nil) XCTAssertNil(lastSQLQuery) // Database not hit } diff --git a/Tests/GRDBTests/DatabaseDumpTests.swift b/Tests/GRDBTests/DatabaseDumpTests.swift index 06d86ccb2..1013d713c 100644 --- a/Tests/GRDBTests/DatabaseDumpTests.swift +++ b/Tests/GRDBTests/DatabaseDumpTests.swift @@ -229,10 +229,6 @@ final class DatabaseDumpTests: GRDBTestCase { // MARK: - JSON func test_json_value_formatting() throws { - guard #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *) else { - throw XCTSkip("Skip because this test relies on JSONEncoder.OutputFormatting.withoutEscapingSlashes") - } - try makeValuesDatabase().read { db in let stream = TestStream() try db.dumpSQL("SELECT * FROM value ORDER BY name", format: .json(), to: stream) @@ -1277,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") } @@ -1481,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") } diff --git a/Tests/GRDBTests/DatabaseErrorTests.swift b/Tests/GRDBTests/DatabaseErrorTests.swift index 8bba886ff..e968b4407 100644 --- a/Tests/GRDBTests/DatabaseErrorTests.swift +++ b/Tests/GRDBTests/DatabaseErrorTests.swift @@ -17,7 +17,7 @@ class DatabaseErrorTests: GRDBTestCase { try dbQueue.inTransaction { db in try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)") try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)") - sqlQueries.removeAll() + clearSQLQueries() try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"]) XCTFail() return .commit @@ -44,7 +44,7 @@ class DatabaseErrorTests: GRDBTestCase { XCTAssertTrue(db.isInsideTransaction) try db.execute(sql: "CREATE TABLE persons (id INTEGER PRIMARY KEY)") try db.execute(sql: "CREATE TABLE pets (masterId INTEGER NOT NULL REFERENCES persons(id), name TEXT)") - sqlQueries.removeAll() + clearSQLQueries() try db.execute(sql: "INSERT INTO pets (masterId, name) VALUES (?, ?)", arguments: [1, "Bobby"]) XCTFail() return .commit diff --git a/Tests/GRDBTests/DatabaseFunctionTests.swift b/Tests/GRDBTests/DatabaseFunctionTests.swift index 8d252c6a8..4c670bbd8 100644 --- a/Tests/GRDBTests/DatabaseFunctionTests.swift +++ b/Tests/GRDBTests/DatabaseFunctionTests.swift @@ -347,13 +347,13 @@ class DatabaseFunctionTests: GRDBTestCase { func testFunctionsAreClosures() throws { let dbQueue = try makeDatabaseQueue() - var x = 123 + let mutex = Mutex(123) let fn = DatabaseFunction("f", argumentCount: 0) { dbValues in - return x + return mutex.load() } try dbQueue.inDatabase { db in db.add(function: fn) - x = 321 + mutex.store(321) XCTAssertEqual(try Int.fetchOne(db, sql: "SELECT f()")!, 321) } } diff --git a/Tests/GRDBTests/DatabaseMigratorTests.swift b/Tests/GRDBTests/DatabaseMigratorTests.swift index 9f9815824..b82d221d0 100644 --- a/Tests/GRDBTests/DatabaseMigratorTests.swift +++ b/Tests/GRDBTests/DatabaseMigratorTests.swift @@ -41,10 +41,6 @@ class DatabaseMigratorTests : GRDBTestCase { } func testEmptyMigratorPublisher() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(writer: some DatabaseWriter) throws { let migrator = DatabaseMigrator() let publisher = migrator.migratePublisher(writer) @@ -128,7 +124,7 @@ class DatabaseMigratorTests : GRDBTestCase { } let expectation = self.expectation(description: "") - migrator.asyncMigrate(writer, completion: { dbResult in + migrator.asyncMigrate(writer, completion: { [migrator2] dbResult in // No migration error let db = try! dbResult.get() @@ -153,10 +149,6 @@ class DatabaseMigratorTests : GRDBTestCase { } func testNonEmptyMigratorPublisher() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createPersons") { db in @@ -209,10 +201,6 @@ class DatabaseMigratorTests : GRDBTestCase { } func testEmptyMigratorPublisherIsAsynchronous() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(writer: some DatabaseWriter) throws { let migrator = DatabaseMigrator() let expectation = self.expectation(description: "") @@ -235,10 +223,6 @@ class DatabaseMigratorTests : GRDBTestCase { } func testNonEmptyMigratorPublisherIsAsynchronous() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(writer: some DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("first", migrate: { _ in }) @@ -262,10 +246,6 @@ class DatabaseMigratorTests : GRDBTestCase { } func testMigratorPublisherDefaultScheduler() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(writer: Writer) { var migrator = DatabaseMigrator() migrator.registerMigration("first", migrate: { _ in }) @@ -291,10 +271,6 @@ class DatabaseMigratorTests : GRDBTestCase { } func testMigratorPublisherCustomScheduler() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - func test(writer: Writer) { var migrator = DatabaseMigrator() migrator.registerMigration("first", migrate: { _ in }) @@ -679,9 +655,11 @@ class DatabaseMigratorTests : GRDBTestCase { var migrator = DatabaseMigrator() migrator.eraseDatabaseOnSchemaChange = true migrator.registerMigration("1", migrate: { _ in }) + try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges)) try migrator.migrate(dbQueue) migrator.registerMigration("2", migrate: { _ in }) + try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges)) try migrator.migrate(dbQueue) } @@ -693,12 +671,50 @@ class DatabaseMigratorTests : GRDBTestCase { var migrator = DatabaseMigrator() migrator.eraseDatabaseOnSchemaChange = true migrator.registerMigration("1", migrate: { _ in }) + try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges)) try migrator.migrate(dbQueue) migrator.registerMigration("2", migrate: { _ in }) + try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges)) try migrator.migrate(dbQueue) } + func testHasSchemaChangesWorksWithReadonlyConfig() throws { + // 1st version of the migrator + var migrator1 = DatabaseMigrator() + migrator1.registerMigration("1") { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + } + + // 2nd version of the migrator + var migrator2 = DatabaseMigrator() + migrator2.registerMigration("1") { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + t.column("score", .integer) // <- schema change, because reasons (development) + } + } + + let dbName = ProcessInfo.processInfo.globallyUniqueString + let dbQueue = try makeDatabaseQueue(filename: dbName) + + try XCTAssertFalse(dbQueue.read(migrator1.hasSchemaChanges)) + try migrator1.migrate(dbQueue) + try XCTAssertFalse(dbQueue.read(migrator1.hasSchemaChanges)) + try dbQueue.close() + + // check that the migrator doesn't fail for a readonly connection + dbConfiguration.readonly = true + let readonlyQueue = try makeDatabaseQueue(filename: dbName) + + try XCTAssertFalse(readonlyQueue.read(migrator1.hasSchemaChanges)) + try XCTAssertTrue(readonlyQueue.read(migrator2.hasSchemaChanges)) + } + func testEraseDatabaseOnSchemaChange() throws { // 1st version of the migrator var migrator1 = DatabaseMigrator() @@ -738,10 +754,58 @@ class DatabaseMigratorTests : GRDBTestCase { // ... unless database gets erased migrator2.eraseDatabaseOnSchemaChange = true + try XCTAssertTrue(dbQueue.read(migrator2.hasSchemaChanges)) try migrator2.migrate(dbQueue) + try XCTAssertFalse(dbQueue.read(migrator2.hasSchemaChanges)) try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1", "2"]) } + func testManualEraseDatabaseOnSchemaChange() throws { + // 1st version of the migrator + var migrator1 = DatabaseMigrator() + migrator1.registerMigration("1") { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + } + } + + // 2nd version of the migrator + var migrator2 = DatabaseMigrator() + migrator2.registerMigration("1") { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("name", .text) + t.column("score", .integer) // <- schema change, because reasons (development) + } + } + migrator2.registerMigration("2") { db in + try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)") + } + + // Apply 1st migrator + let dbQueue = try makeDatabaseQueue() + try migrator1.migrate(dbQueue) + + // Test than 2nd migrator can't run... + do { + try migrator2.migrate(dbQueue) + XCTFail("Expected DatabaseError") + } catch let error as DatabaseError { + XCTAssertEqual(error.resultCode, .SQLITE_ERROR) + XCTAssertEqual(error.message, "table player has no column named score") + } + try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1"]) + + // ... unless database gets erased + if try dbQueue.read(migrator2.hasSchemaChanges) { + try dbQueue.erase() + } + try migrator2.migrate(dbQueue) + try XCTAssertFalse(dbQueue.read(migrator2.hasSchemaChanges)) + try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1", "2"]) + } + func testEraseDatabaseOnSchemaChangeWithConfiguration() throws { // 1st version of the migrator var migrator1 = DatabaseMigrator() @@ -787,7 +851,9 @@ class DatabaseMigratorTests : GRDBTestCase { // ... unless database gets erased migrator2.eraseDatabaseOnSchemaChange = true + try XCTAssertTrue(dbQueue.read(migrator2.hasSchemaChanges)) try migrator2.migrate(dbQueue) + try XCTAssertFalse(dbQueue.read(migrator2.hasSchemaChanges)) try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1", "2"]) } @@ -795,13 +861,13 @@ class DatabaseMigratorTests : GRDBTestCase { var migrator = DatabaseMigrator() migrator.eraseDatabaseOnSchemaChange = true - var witness = 1 + let mutex = Mutex(0) migrator.registerMigration("1") { db in + let value = mutex.increment() try db.execute(sql: """ CREATE TABLE t1(id INTEGER PRIMARY KEY); INSERT INTO t1(id) VALUES (?) - """, arguments: [witness]) - witness += 1 + """, arguments: [value]) } let dbQueue = try makeDatabaseQueue() @@ -816,6 +882,7 @@ class DatabaseMigratorTests : GRDBTestCase { CREATE TABLE t2(id INTEGER PRIMARY KEY); """) } + try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges)) try migrator.migrate(dbQueue) try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, sql: "SELECT id FROM t1") }, 1) try XCTAssertTrue(dbQueue.read { try $0.tableExists("t2") }) @@ -842,6 +909,7 @@ class DatabaseMigratorTests : GRDBTestCase { } // Then 2nd migration does not erase database + try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges)) try migrator.migrate(dbQueue) try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, sql: "SELECT id FROM t") }, 1) } @@ -869,7 +937,9 @@ class DatabaseMigratorTests : GRDBTestCase { INSERT INTO t1(id) VALUES (2) """) } + try XCTAssertTrue(dbQueue.read(migrator2.hasSchemaChanges)) try migrator2.migrate(dbQueue) + try XCTAssertFalse(dbQueue.read(migrator2.hasSchemaChanges)) try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, sql: "SELECT id FROM t1") }, 2) } diff --git a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift index 7a329c38c..7d2478545 100644 --- a/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabasePoolConcurrencyTests.swift @@ -1074,85 +1074,17 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { try test(qos: .userInitiated) } - // MARK: - ConcurrentRead - - func testConcurrentReadOpensATransaction() throws { - let dbPool = try makeDatabasePool() - let future = dbPool.writeWithoutTransaction { db in - dbPool.concurrentRead { db in - XCTAssertTrue(db.isInsideTransaction) - do { - try db.execute(sql: "BEGIN DEFERRED TRANSACTION") - XCTFail("Expected error") - } catch { - } - } - } - try future.wait() - } - - func testConcurrentReadOutsideOfTransaction() throws { - let dbPool = try makeDatabasePool() - try dbPool.write { db in - try db.create(table: "persons") { t in - t.primaryKey("id", .integer) - } - } - - // Writer Reader - // dbPool.writeWithoutTransaction { - // > - // dbPool.concurrentRead { - // < - // INSERT INTO items (id) VALUES (NULL) - // > - let s1 = DispatchSemaphore(value: 0) - // } SELECT COUNT(*) FROM persons -> 0 - // < - // } - - let future: DatabaseFuture = try dbPool.writeWithoutTransaction { db in - let future: DatabaseFuture = dbPool.concurrentRead { db in - _ = s1.wait(timeout: .distantFuture) - return try! Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")! - } - try db.execute(sql: "INSERT INTO persons DEFAULT VALUES") - s1.signal() - return future - } - XCTAssertEqual(try future.wait(), 0) - } - - func testConcurrentReadError() throws { - // Necessary for this test to run as quickly as possible - dbConfiguration.readonlyBusyMode = .immediateError - let dbPool = try makeDatabasePool() - try dbPool.writeWithoutTransaction { db in - try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE") - try db.execute(sql: "CREATE TABLE items (id INTEGER PRIMARY KEY)") - let future = dbPool.concurrentRead { db in - fatalError("Should not run") - } - do { - try future.wait() - } catch let error as DatabaseError { - XCTAssertEqual(error.resultCode, .SQLITE_BUSY) - XCTAssertEqual(error.message!, "database is locked") - } - } - } - // MARK: - AsyncConcurrentRead func testAsyncConcurrentReadOpensATransaction() throws { let dbPool = try makeDatabasePool() - var isInsideTransaction: Bool? = nil + let isInsideTransactionMutex: Mutex = Mutex(nil) let expectation = self.expectation(description: "read") dbPool.writeWithoutTransaction { db in dbPool.asyncConcurrentRead { dbResult in do { let db = try dbResult.get() - isInsideTransaction = db.isInsideTransaction + isInsideTransactionMutex.store(db.isInsideTransaction) do { try db.execute(sql: "BEGIN DEFERRED TRANSACTION") XCTFail("Expected error") @@ -1165,7 +1097,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { } } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(isInsideTransaction, true) + XCTAssertEqual(isInsideTransactionMutex.load(), true) } func testAsyncConcurrentReadOutsideOfTransaction() throws { @@ -1179,7 +1111,7 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // Writer Reader // dbPool.writeWithoutTransaction { // > - // dbPool.concurrentRead { + // dbPool.asyncConcurrentRead { // < // INSERT INTO items (id) VALUES (NULL) // > @@ -1188,14 +1120,14 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { // < // } - var count: Int? = nil + let countMutex: Mutex = Mutex(nil) let expectation = self.expectation(description: "read") try dbPool.writeWithoutTransaction { db in dbPool.asyncConcurrentRead { dbResult in do { _ = s1.wait(timeout: .distantFuture) let db = try dbResult.get() - count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")! + try countMutex.store(Int.fetchOne(db, sql: "SELECT COUNT(*) FROM persons")!) } catch { XCTFail("Unexpected error: \(error)") } @@ -1205,14 +1137,14 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { s1.signal() } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 0) + XCTAssertEqual(countMutex.load(), 0) } func testAsyncConcurrentReadError() throws { // Necessary for this test to run as quickly as possible dbConfiguration.readonlyBusyMode = .immediateError let dbPool = try makeDatabasePool() - var readError: DatabaseError? = nil + let readErrorMutex: Mutex = Mutex(nil) let expectation = self.expectation(description: "read") try dbPool.writeWithoutTransaction { db in try db.execute(sql: "PRAGMA locking_mode=EXCLUSIVE") @@ -1224,12 +1156,12 @@ class DatabasePoolConcurrencyTests: GRDBTestCase { XCTFail("Unexpected result: \(dbResult)") return } - readError = dbError + readErrorMutex.store(dbError) expectation.fulfill() } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(readError!.resultCode, .SQLITE_BUSY) - XCTAssertEqual(readError!.message!, "database is locked") + XCTAssertEqual(readErrorMutex.load()!.resultCode, .SQLITE_BUSY) + XCTAssertEqual(readErrorMutex.load()!.message!, "database is locked") } } diff --git a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift index 9b6bb306c..afa8bd32a 100644 --- a/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabasePoolReleaseMemoryTests.swift @@ -1,24 +1,28 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import XCTest @testable import GRDB class DatabasePoolReleaseMemoryTests: GRDBTestCase { func testDatabasePoolDeinitClosesAllConnections() throws { - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - var totalOpenConnectionCount = 0 + let openConnectionCountMutex = Mutex(0) + let totalOpenConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - totalOpenConnectionCount += 1 - openConnectionCount += 1 - } + dbConfiguration.onConnectionDidOpen { + totalOpenConnectionCountMutex.increment() + openConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } + dbConfiguration.onConnectionDidClose { + openConnectionCountMutex.decrement() } // write & read @@ -35,19 +39,19 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { } // One reader, one writer - XCTAssertEqual(totalOpenConnectionCount, 2) + XCTAssertEqual(totalOpenConnectionCountMutex.load(), 2) // All connections are closed - XCTAssertEqual(openConnectionCount, 0) + XCTAssertEqual(openConnectionCountMutex.load(), 0) } - + #if os(iOS) func testDatabasePoolReleasesMemoryOnPressureEvent() throws { // Create a database pool, and expect a reader connection to be closed let expectation = self.expectation(description: "Reader connection closed") var configuration = Configuration() - configuration.SQLiteConnectionWillClose = { conn in + configuration.onConnectionWillClose { conn in if sqlite3_db_readonly(conn, nil) != 0 { expectation.fulfill() } @@ -67,7 +71,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { waitForExpectations(timeout: 0.5) } } - + func testDatabasePoolDoesNotReleaseMemoryOnPressureEventIfDisabled() throws { // Create a database pool, and do not expect any reader connection to be closed let expectation = self.expectation(description: "Reader connection closed") @@ -75,7 +79,7 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { var configuration = Configuration() configuration.automaticMemoryManagement = false - configuration.SQLiteConnectionWillClose = { conn in + configuration.onConnectionWillClose { conn in if sqlite3_db_readonly(conn, nil) != 0 { expectation.fulfill() } @@ -117,26 +121,21 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { // Cleanup semaphore.signal() } - + #endif - + func test_DatabasePool_releaseMemory_closes_reader_connections() throws { // A complicated test setup that opens multiple reader connections. - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - var totalOpenConnectionCount = 0 + let openConnectionCountMutex = Mutex(0) + let totalOpenConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - totalOpenConnectionCount += 1 - openConnectionCount += 1 - } + dbConfiguration.onConnectionDidOpen { + totalOpenConnectionCountMutex.increment() + openConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } + dbConfiguration.onConnectionDidClose { + openConnectionCountMutex.decrement() } let dbPool = try makeDatabasePool() @@ -192,74 +191,69 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { } // Two readers, one writer - XCTAssertEqual(totalOpenConnectionCount, 3) + XCTAssertEqual(totalOpenConnectionCountMutex.load(), 3) // Writer is still open - XCTAssertEqual(openConnectionCount, 1) + XCTAssertEqual(openConnectionCountMutex.load(), 1) } func test_DatabasePool_releaseMemory_closes_reader_connections_when_persistentReadOnlyConnections_is_false() throws { - var persistentConnectionCount = 0 + let persistentConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - persistentConnectionCount += 1 + dbConfiguration.onConnectionDidOpen { + persistentConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - persistentConnectionCount -= 1 + dbConfiguration.onConnectionDidClose { + persistentConnectionCountMutex.decrement() } dbConfiguration.persistentReadOnlyConnections = false let dbPool = try makeDatabasePool() - XCTAssertEqual(persistentConnectionCount, 1) // writer + XCTAssertEqual(persistentConnectionCountMutex.load(), 1) // writer try dbPool.read { _ in } - XCTAssertEqual(persistentConnectionCount, 2) // writer + reader + XCTAssertEqual(persistentConnectionCountMutex.load(), 2) // writer + reader dbPool.releaseMemory() - XCTAssertEqual(persistentConnectionCount, 1) // writer + XCTAssertEqual(persistentConnectionCountMutex.load(), 1) // writer } func test_DatabasePool_releaseMemory_does_not_close_reader_connections_when_persistentReadOnlyConnections_is_true() throws { - var persistentConnectionCount = 0 + let persistentConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - persistentConnectionCount += 1 + dbConfiguration.onConnectionDidOpen { + persistentConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - persistentConnectionCount -= 1 + dbConfiguration.onConnectionDidClose { + persistentConnectionCountMutex.decrement() } dbConfiguration.persistentReadOnlyConnections = true let dbPool = try makeDatabasePool() - XCTAssertEqual(persistentConnectionCount, 1) // writer + XCTAssertEqual(persistentConnectionCountMutex.load(), 1) // writer try dbPool.read { _ in } - XCTAssertEqual(persistentConnectionCount, 2) // writer + reader + XCTAssertEqual(persistentConnectionCountMutex.load(), 2) // writer + reader dbPool.releaseMemory() - XCTAssertEqual(persistentConnectionCount, 2) // writer + reader + XCTAssertEqual(persistentConnectionCountMutex.load(), 2) // writer + reader } - + func testBlocksRetainConnection() throws { - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - var totalOpenConnectionCount = 0 + let openConnectionCountMutex = Mutex(0) + let totalOpenConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - totalOpenConnectionCount += 1 - openConnectionCount += 1 - } + dbConfiguration.onConnectionDidOpen { + totalOpenConnectionCountMutex.increment() + openConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } + dbConfiguration.onConnectionDidClose { + openConnectionCountMutex.decrement() } // Block 1 Block 2 @@ -302,10 +296,10 @@ class DatabasePoolReleaseMemoryTests: GRDBTestCase { } // one writer, one reader - XCTAssertEqual(totalOpenConnectionCount, 2) + XCTAssertEqual(totalOpenConnectionCountMutex.load(), 2) // All connections are closed - XCTAssertEqual(openConnectionCount, 0) + XCTAssertEqual(openConnectionCountMutex.load(), 0) } func testStatementDoNotRetainDatabaseConnection() throws { diff --git a/Tests/GRDBTests/DatabasePoolTests.swift b/Tests/GRDBTests/DatabasePoolTests.swift index 7580b1a34..e1ab57bbd 100644 --- a/Tests/GRDBTests/DatabasePoolTests.swift +++ b/Tests/GRDBTests/DatabasePoolTests.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import XCTest import GRDB @@ -41,7 +50,7 @@ class DatabasePoolTests: GRDBTestCase { XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-wal")) XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-shm")) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) // A non-empty wal file makes sure ValueObservation can use wal snapshots. // See let walURL = URL(fileURLWithPath: dbPool.path + "-wal") @@ -65,7 +74,7 @@ class DatabasePoolTests: GRDBTestCase { XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-wal")) XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-shm")) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) // A non-empty wal file makes sure ValueObservation can use wal snapshots. // See let walURL = URL(fileURLWithPath: dbPool.path + "-wal") @@ -91,7 +100,7 @@ class DatabasePoolTests: GRDBTestCase { XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-wal")) XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-shm")) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) // A non-empty wal file makes sure ValueObservation can use wal snapshots. // See let walURL = URL(fileURLWithPath: dbPool.path + "-wal") @@ -114,7 +123,7 @@ class DatabasePoolTests: GRDBTestCase { XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-wal")) XCTAssertTrue(fm.fileExists(atPath: dbPool.path + "-shm")) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) // A non-empty wal file makes sure ValueObservation can use wal snapshots. // See let walURL = URL(fileURLWithPath: dbPool.path + "-wal") @@ -228,9 +237,7 @@ class DatabasePoolTests: GRDBTestCase { let group = DispatchGroup() // The maximum number of threads we could witness - var maxThreadCount: CInt = 0 - let lock = NSLock() - + let maxThreadCountMutex: Mutex = Mutex(0) for _ in (0.. = Mutex(0) for _ in (0.. + func test_releaseMemory_after_close() throws { + let dbPool = try makeDatabasePool() + try dbPool.read { _ in } // Create a reader + try dbPool.close() + dbPool.releaseMemory() + } } diff --git a/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift b/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift index 613d6b5ad..c525f9ef7 100644 --- a/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift +++ b/Tests/GRDBTests/DatabaseQueueConcurrencyTests.swift @@ -244,9 +244,9 @@ class ConcurrencyTests: GRDBTestCase { // BEGIN EXCLUSIVE TRANSACTION // COMMIT - var busyCallbackCalled = false + let busyCallbackCalledMutex = Mutex(false) self.busyCallback = { n in - busyCallbackCalled = true + busyCallbackCalledMutex.store(true) s2.signal() return true } @@ -283,7 +283,7 @@ class ConcurrencyTests: GRDBTestCase { _ = group.wait(timeout: .distantFuture) - XCTAssertTrue(busyCallbackCalled) + XCTAssertTrue(busyCallbackCalledMutex.load()) } func testReaderDuringDefaultTransaction() throws { @@ -334,22 +334,22 @@ class ConcurrencyTests: GRDBTestCase { } // Queue 2 - var rows1: [Row]? - var rows2: [Row]? + var count1: Int? + var count2: Int? queue.async(group: group) { try! dbQueue2.writeWithoutTransaction { db in _ = s1.wait(timeout: .distantFuture) - rows1 = try Row.fetchAll(db, sql: "SELECT * FROM stuffs") + count1 = try Row.fetchAll(db, sql: "SELECT * FROM stuffs").count s2.signal() _ = s3.wait(timeout: .distantFuture) - rows2 = try Row.fetchAll(db, sql: "SELECT * FROM stuffs") + count2 = try Row.fetchAll(db, sql: "SELECT * FROM stuffs").count } } _ = group.wait(timeout: .distantFuture) - XCTAssertEqual(rows1!.count, 0) // uncommitted changes are not visible - XCTAssertEqual(rows2!.count, 1) // committed changes are visible + XCTAssertEqual(count1, 0) // uncommitted changes are not visible + XCTAssertEqual(count2, 1) // committed changes are visible } func testReaderInDeferredTransactionDuringDefaultTransaction() throws { @@ -384,9 +384,9 @@ class ConcurrencyTests: GRDBTestCase { // COMMIT // COMMIT - var busyCallbackCalled = false + let busyCallbackCalledMutex = Mutex(false) self.busyCallback = { n in - busyCallbackCalled = true + busyCallbackCalledMutex.store(true) s3.signal() return true } @@ -431,6 +431,6 @@ class ConcurrencyTests: GRDBTestCase { _ = group.wait(timeout: .distantFuture) - XCTAssertTrue(busyCallbackCalled) + XCTAssertTrue(busyCallbackCalledMutex.load()) } } diff --git a/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift b/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift index 7c5b9428e..5a828b9e8 100644 --- a/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift +++ b/Tests/GRDBTests/DatabaseQueueReleaseMemoryTests.swift @@ -4,21 +4,16 @@ import XCTest class DatabaseQueueReleaseMemoryTests: GRDBTestCase { func testDatabaseQueueDeinitClosesConnection() throws { - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - var totalOpenConnectionCount = 0 + let openConnectionCountMutex = Mutex(0) + let totalOpenConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - totalOpenConnectionCount += 1 - openConnectionCount += 1 - } + dbConfiguration.onConnectionDidOpen { + totalOpenConnectionCountMutex.increment() + openConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } + dbConfiguration.onConnectionDidClose { + openConnectionCountMutex.decrement() } do { @@ -27,28 +22,23 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase { } // One reader, one writer - XCTAssertEqual(totalOpenConnectionCount, 1) + XCTAssertEqual(totalOpenConnectionCountMutex.load(), 1) // All connections are closed - XCTAssertEqual(openConnectionCount, 0) + XCTAssertEqual(openConnectionCountMutex.load(), 0) } - + func testBlocksRetainConnection() throws { - let countQueue = DispatchQueue(label: "GRDB") - var openConnectionCount = 0 - var totalOpenConnectionCount = 0 + let openConnectionCountMutex = Mutex(0) + let totalOpenConnectionCountMutex = Mutex(0) - dbConfiguration.SQLiteConnectionDidOpen = { - countQueue.sync { - totalOpenConnectionCount += 1 - openConnectionCount += 1 - } + dbConfiguration.onConnectionDidOpen { + totalOpenConnectionCountMutex.increment() + openConnectionCountMutex.increment() } - dbConfiguration.SQLiteConnectionDidClose = { - countQueue.sync { - openConnectionCount -= 1 - } + dbConfiguration.onConnectionDidClose { + openConnectionCountMutex.decrement() } // Block 1 Block 2 @@ -91,10 +81,10 @@ class DatabaseQueueReleaseMemoryTests: GRDBTestCase { } // one writer - XCTAssertEqual(totalOpenConnectionCount, 1) + XCTAssertEqual(totalOpenConnectionCountMutex.load(), 1) // All connections are closed - XCTAssertEqual(openConnectionCount, 0) + XCTAssertEqual(openConnectionCountMutex.load(), 0) } func testStatementDoNotRetainDatabaseConnection() throws { diff --git a/Tests/GRDBTests/DatabaseQueueSchemaCacheTests.swift b/Tests/GRDBTests/DatabaseQueueSchemaCacheTests.swift index 3f54530f6..cbd795bfa 100644 --- a/Tests/GRDBTests/DatabaseQueueSchemaCacheTests.swift +++ b/Tests/GRDBTests/DatabaseQueueSchemaCacheTests.swift @@ -388,12 +388,35 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase { try main.inDatabase { db in try db.execute(literal: "ATTACH DATABASE \(attached.path) AS attached") - let tableExists = try db.tableExists("t") - let viewExists = try db.viewExists("v") - let triggerExists = try db.triggerExists("tr") - XCTAssertTrue(tableExists) - XCTAssertTrue(viewExists) - XCTAssertTrue(triggerExists) + try XCTAssertTrue(db.tableExists("t")) + try XCTAssertTrue(db.viewExists("v")) + try XCTAssertTrue(db.triggerExists("tr")) + + try XCTAssertFalse(db.tableExists("t", in: "main")) + try XCTAssertFalse(db.viewExists("v", in: "main")) + try XCTAssertFalse(db.triggerExists("tr", in: "main")) + + try XCTAssertTrue(db.tableExists("t", in: "attached")) + try XCTAssertTrue(db.viewExists("v", in: "attached")) + try XCTAssertTrue(db.triggerExists("tr", in: "attached")) + } + } + + func testExistsWithUnspecifiedSchemaFindsTempSchema() throws { + try makeDatabaseQueue().inDatabase { db in + try db.execute(sql: """ + CREATE TEMPORARY TABLE t (id INTEGER); + CREATE TEMPORARY VIEW v AS SELECT * FROM t; + """) + + try XCTAssertTrue(db.tableExists("t")) + try XCTAssertTrue(db.viewExists("v")) + + try XCTAssertTrue(db.tableExists("t", in: "temp")) + try XCTAssertTrue(db.viewExists("v", in: "temp")) + + try XCTAssertFalse(db.tableExists("t", in: "main")) + try XCTAssertFalse(db.viewExists("v", in: "main")) } } } diff --git a/Tests/GRDBTests/DatabaseQueueTests.swift b/Tests/GRDBTests/DatabaseQueueTests.swift index 7bd5adf2b..c22be8326 100644 --- a/Tests/GRDBTests/DatabaseQueueTests.swift +++ b/Tests/GRDBTests/DatabaseQueueTests.swift @@ -369,8 +369,6 @@ class DatabaseQueueTests: GRDBTestCase { func test_busy_timeout_and_IMMEDIATE_transactions_do_prevent_SQLITE_BUSY() throws { var configuration = dbConfiguration! // Test fails when this line is commented - configuration.defaultTransactionKind = .immediate - // Test fails when this line is commented configuration.busyMode = .timeout(10) let dbQueue = try makeDatabaseQueue(filename: "test") @@ -380,7 +378,7 @@ class DatabaseQueueTests: GRDBTestCase { } let parallelWritesCount = 50 - DispatchQueue.concurrentPerform(iterations: parallelWritesCount) { index in + DispatchQueue.concurrentPerform(iterations: parallelWritesCount) { [configuration] index in let dbQueue = try! makeDatabaseQueue(filename: "test", configuration: configuration) try! dbQueue.write { db in _ = try Table("test").fetchCount(db) @@ -460,11 +458,18 @@ class DatabaseQueueTests: GRDBTestCase { XCTFail("Expected Error") } catch DatabaseError.SQLITE_BUSY { } } - XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master")) + XCTAssert(lastSQLiteDiagnostic!.message.contains("unfinalized statement: SELECT * FROM sqlite_master")) // Database is not closed: no error try dbQueue.inDatabase { db in try db.execute(sql: "SELECT * FROM sqlite_master") } } + + // Regression test for + func test_releaseMemory_after_close() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.close() + dbQueue.releaseMemory() + } } diff --git a/Tests/GRDBTests/DatabaseReaderTests.swift b/Tests/GRDBTests/DatabaseReaderTests.swift index bf2d51c3f..ab64b6e7a 100644 --- a/Tests/GRDBTests/DatabaseReaderTests.swift +++ b/Tests/GRDBTests/DatabaseReaderTests.swift @@ -44,12 +44,11 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue())) try test(setup(makeDatabasePool())) try test(setup(makeDatabasePool()).makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(setup(makeDatabasePool()).makeSnapshotPool()) #endif } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_ReadCanRead() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -67,7 +66,7 @@ class DatabaseReaderTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) try await test(setup(makeDatabasePool()).makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try await test(setup(makeDatabasePool()).makeSnapshotPool()) #endif } @@ -86,12 +85,11 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(makeDatabasePool().makeSnapshotPool()) #endif } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_ReadPreventsDatabaseModification() async throws { func test(_ dbReader: some DatabaseReader) async throws { do { @@ -106,7 +104,7 @@ class DatabaseReaderTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) try await test(makeDatabasePool().makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try await test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -130,12 +128,11 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue())) try test(setup(makeDatabasePool())) try test(setup(makeDatabasePool()).makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(setup(makeDatabasePool()).makeSnapshotPool()) #endif } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_UnsafeReadCanRead() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -153,7 +150,7 @@ class DatabaseReaderTests : GRDBTestCase { try await test(setup(makeDatabaseQueue())) try await test(setup(makeDatabasePool())) try await test(setup(makeDatabasePool()).makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try await test(setup(makeDatabasePool()).makeSnapshotPool()) #endif } @@ -177,7 +174,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue())) try test(setup(makeDatabasePool())) try test(setup(makeDatabasePool()).makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(setup(makeDatabasePool()).makeSnapshotPool()) #endif } @@ -197,7 +194,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -224,12 +221,12 @@ class DatabaseReaderTests : GRDBTestCase { func test(_ dbReader: some DatabaseReader) throws { let expectation = self.expectation(description: "updates") let semaphore = DispatchSemaphore(value: 0) - var count: Int? + let countMutex: Mutex = Mutex(nil) dbReader.asyncRead { dbResult in // Make sure this block executes asynchronously semaphore.wait() do { - count = try Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master") + try countMutex.store(Int.fetchOne(dbResult.get(), sql: "SELECT COUNT(*) FROM sqlite_master")) } catch { XCTFail("Unexpected error: \(error)") } @@ -238,13 +235,13 @@ class DatabaseReaderTests : GRDBTestCase { semaphore.signal() waitForExpectations(timeout: 1, handler: nil) - XCTAssertNotNil(count) + XCTAssertNotNil(countMutex.load()) } try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -273,7 +270,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -293,7 +290,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -313,7 +310,7 @@ class DatabaseReaderTests : GRDBTestCase { try test(makeDatabaseQueue()) try test(makeDatabasePool()) try test(makeDatabasePool().makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(makeDatabasePool().makeSnapshotPool()) #endif } @@ -340,8 +337,312 @@ class DatabaseReaderTests : GRDBTestCase { try test(setup(makeDatabaseQueue(configuration: Configuration()))) try test(setup(makeDatabasePool(configuration: Configuration()))) try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(setup(makeDatabasePool(configuration: Configuration())).makeSnapshotPool()) #endif } + + // MARK: - Task Cancellation + + func test_read_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbReader.read { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.read { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_read_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.read { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.read { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_statement_execution_from_read_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.read { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.read { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_cursor_iteration_from_read_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.read { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.read { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_unsafeRead_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbReader.unsafeRead { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.unsafeRead { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_unsafeRead_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.unsafeRead { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.unsafeRead { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_statement_execution_from_unsafeRead_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.unsafeRead { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.unsafeRead { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_cursor_iteration_from_unsafeRead_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbReader: some DatabaseReader) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbReader.unsafeRead { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbReader.unsafeRead { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(makeDatabasePool().makeSnapshot()) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) + try await test(makeDatabasePool().makeSnapshotPool()) +#endif + try await test(AnyDatabaseReader(makeDatabaseQueue())) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } } diff --git a/Tests/GRDBTests/DatabaseRegionObservationTests.swift b/Tests/GRDBTests/DatabaseRegionObservationTests.swift index 0625d91c6..3ffdfc39e 100644 --- a/Tests/GRDBTests/DatabaseRegionObservationTests.swift +++ b/Tests/GRDBTests/DatabaseRegionObservationTests.swift @@ -8,10 +8,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { let observation = DatabaseRegionObservation(tracking: .fullDatabase) _ = observation.start(in: writer, onError: { _ in }, onChange: { _ in }) - - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - _ = observation.publisher(in: writer) - } + _ = observation.publisher(in: writer) } func testDatabaseRegionObservation_FullDatabase() throws { @@ -27,12 +24,12 @@ class DatabaseRegionObservationTests: GRDBTestCase { let observation = DatabaseRegionObservation(tracking: .fullDatabase) - var count = 0 + let countMutex = Mutex(0) let cancellable = observation.start( in: dbQueue, onError: { XCTFail("Unexpected error: \($0)") }, onChange: { db in - count += 1 + countMutex.increment() notificationExpectation.fulfill() }) @@ -49,7 +46,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 3) + XCTAssertEqual(countMutex.load(), 3) } } @@ -96,12 +93,12 @@ class DatabaseRegionObservationTests: GRDBTestCase { let observation = DatabaseRegionObservation(tracking: request1, request2) - var count = 0 + let countMutex = Mutex(0) let cancellable = observation.start( in: dbQueue, onError: { XCTFail("Unexpected error: \($0)") }, onChange: { db in - count += 1 + countMutex.increment() notificationExpectation.fulfill() }) @@ -118,7 +115,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 3) + XCTAssertEqual(countMutex.load(), 3) } } @@ -138,12 +135,12 @@ class DatabaseRegionObservationTests: GRDBTestCase { let observation = DatabaseRegionObservation(tracking: [request1, request2]) - var count = 0 + let countMutex = Mutex(0) let cancellable = observation.start( in: dbQueue, onError: { XCTFail("Unexpected error: \($0)") }, onChange: { db in - count += 1 + countMutex.increment() notificationExpectation.fulfill() }) @@ -160,7 +157,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 3) + XCTAssertEqual(countMutex.load(), 3) } } @@ -174,13 +171,13 @@ class DatabaseRegionObservationTests: GRDBTestCase { let observation = DatabaseRegionObservation(tracking: SQLRequest(sql: "SELECT * FROM t ORDER BY id")) - var count = 0 + let countMutex = Mutex(0) do { let cancellable = observation.start( in: dbQueue, onError: { XCTFail("Unexpected error: \($0)") }, onChange: { db in - count += 1 + countMutex.increment() notificationExpectation.fulfill() }) @@ -199,7 +196,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 2) + XCTAssertEqual(countMutex.load(), 2) } func testDatabaseRegionExtentNextTransaction() throws { @@ -212,14 +209,14 @@ class DatabaseRegionObservationTests: GRDBTestCase { let observation = DatabaseRegionObservation(tracking: SQLRequest(sql: "SELECT * FROM t ORDER BY id")) - var count = 0 - var cancellable: AnyDatabaseCancellable? + let countMutex = Mutex(0) + nonisolated(unsafe) var cancellable: AnyDatabaseCancellable? cancellable = observation.start( in: dbQueue, onError: { XCTFail("Unexpected error: \($0)") }, onChange: { db in cancellable?.cancel() - count += 1 + countMutex.increment() notificationExpectation.fulfill() }) @@ -233,7 +230,7 @@ class DatabaseRegionObservationTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(count, 1) + XCTAssertEqual(countMutex.load(), 1) } } diff --git a/Tests/GRDBTests/DatabaseRegionTests.swift b/Tests/GRDBTests/DatabaseRegionTests.swift index 7044aa3a8..fc2cf29d4 100644 --- a/Tests/GRDBTests/DatabaseRegionTests.swift +++ b/Tests/GRDBTests/DatabaseRegionTests.swift @@ -556,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 diff --git a/Tests/GRDBTests/DatabaseSavepointTests.swift b/Tests/GRDBTests/DatabaseSavepointTests.swift index 1483d1a68..b2fe86d25 100644 --- a/Tests/GRDBTests/DatabaseSavepointTests.swift +++ b/Tests/GRDBTests/DatabaseSavepointTests.swift @@ -96,230 +96,12 @@ class DatabaseSavepointTests: GRDBTestCase { XCTAssertThrowsError(try db.execute(sql: "COMMIT")) } } - - func testReleaseTopLevelSavepointFromDatabaseWithDefaultDeferredTransactions() throws { - dbConfiguration.defaultTransactionKind = .deferred + + func testReleaseTopLevelSavepoint() throws { let dbQueue = try makeDatabaseQueue() let observer = Observer() dbQueue.add(transactionObserver: observer) - sqlQueries.removeAll() - try dbQueue.writeWithoutTransaction { db in - try insertItem(db, name: "item1") - try db.inSavepoint { - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item2") - return .commit - } - XCTAssertFalse(db.isInsideTransaction) - try insertItem(db, name: "item3") - } - - XCTAssertEqual(sqlQueries, [ - "INSERT INTO items (name) VALUES ('item1')", - "BEGIN DEFERRED TRANSACTION", - "INSERT INTO items (name) VALUES ('item2')", - "COMMIT TRANSACTION", - "INSERT INTO items (name) VALUES ('item3')" - ]) - XCTAssertEqual(try fetchAllItemNames(dbQueue), ["item1", "item2", "item3"]) - XCTAssertEqual(observer.allRecordedEvents.count, 3) - #if SQLITE_ENABLE_PREUPDATE_HOOK - XCTAssertEqual(observer.allRecordedPreUpdateEvents.count, 3) - #endif - } - - func testRollbackTopLevelSavepointFromDatabaseWithDefaultDeferredTransactions() throws { - dbConfiguration.defaultTransactionKind = .deferred - let dbQueue = try makeDatabaseQueue() - let observer = Observer() - dbQueue.add(transactionObserver: observer) - sqlQueries.removeAll() - try dbQueue.writeWithoutTransaction { db in - try insertItem(db, name: "item1") - try db.inSavepoint { - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item2") - return .rollback - } - XCTAssertFalse(db.isInsideTransaction) - try insertItem(db, name: "item3") - } - XCTAssertEqual(sqlQueries, [ - "INSERT INTO items (name) VALUES ('item1')", - "BEGIN DEFERRED TRANSACTION", - "INSERT INTO items (name) VALUES ('item2')", - "ROLLBACK TRANSACTION", - "INSERT INTO items (name) VALUES ('item3')" - ]) - XCTAssertEqual(try fetchAllItemNames(dbQueue), ["item1", "item3"]) - XCTAssertEqual(observer.allRecordedEvents.count, 3) - #if SQLITE_ENABLE_PREUPDATE_HOOK - XCTAssertEqual(observer.allRecordedPreUpdateEvents.count, 3) - #endif - } - - func testNestedSavepointFromDatabaseWithDefaultDeferredTransactions() throws { - dbConfiguration.defaultTransactionKind = .deferred - let dbQueue = try makeDatabaseQueue() - let observer = Observer() - dbQueue.add(transactionObserver: observer) - sqlQueries.removeAll() - try dbQueue.writeWithoutTransaction { db in - try insertItem(db, name: "item1") - try db.inSavepoint { - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item2") - try db.inSavepoint { - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item3") - return .commit - } - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item4") - return .commit - } - XCTAssertFalse(db.isInsideTransaction) - try insertItem(db, name: "item5") - } - XCTAssertEqual(sqlQueries, [ - "INSERT INTO items (name) VALUES ('item1')", - "BEGIN DEFERRED TRANSACTION", - "INSERT INTO items (name) VALUES ('item2')", - "SAVEPOINT grdb", - "INSERT INTO items (name) VALUES ('item3')", - "RELEASE SAVEPOINT grdb", - "INSERT INTO items (name) VALUES ('item4')", - "COMMIT TRANSACTION", - "INSERT INTO items (name) VALUES ('item5')" - ]) - XCTAssertEqual(try fetchAllItemNames(dbQueue), ["item1", "item2", "item3", "item4", "item5"]) - XCTAssertEqual(observer.allRecordedEvents.count, 5) - #if SQLITE_ENABLE_PREUPDATE_HOOK - XCTAssertEqual(observer.allRecordedPreUpdateEvents.count, 5) - #endif - try dbQueue.inDatabase { db in try db.execute(sql: "DELETE FROM items") } - observer.reset() - - sqlQueries.removeAll() - try dbQueue.writeWithoutTransaction { db in - try insertItem(db, name: "item1") - try db.inSavepoint { - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item2") - try db.inSavepoint { - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item3") - return .commit - } - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item4") - return .rollback - } - XCTAssertFalse(db.isInsideTransaction) - try insertItem(db, name: "item5") - } - XCTAssertEqual(sqlQueries, [ - "INSERT INTO items (name) VALUES ('item1')", - "BEGIN DEFERRED TRANSACTION", - "INSERT INTO items (name) VALUES ('item2')", - "SAVEPOINT grdb", - "INSERT INTO items (name) VALUES ('item3')", - "RELEASE SAVEPOINT grdb", - "INSERT INTO items (name) VALUES ('item4')", - "ROLLBACK TRANSACTION", - "INSERT INTO items (name) VALUES ('item5')" - ]) - XCTAssertEqual(try fetchAllItemNames(dbQueue), ["item1", "item5"]) - XCTAssertEqual(observer.allRecordedEvents.count, 5) - #if SQLITE_ENABLE_PREUPDATE_HOOK - XCTAssertEqual(observer.allRecordedPreUpdateEvents.count, 5) - #endif - try dbQueue.inDatabase { db in try db.execute(sql: "DELETE FROM items") } - observer.reset() - - sqlQueries.removeAll() - try dbQueue.writeWithoutTransaction { db in - try insertItem(db, name: "item1") - try db.inSavepoint { - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item2") - try db.inSavepoint { - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item3") - return .rollback - } - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item4") - return .commit - } - XCTAssertFalse(db.isInsideTransaction) - try insertItem(db, name: "item5") - } - XCTAssertEqual(sqlQueries, [ - "INSERT INTO items (name) VALUES ('item1')", - "BEGIN DEFERRED TRANSACTION", - "INSERT INTO items (name) VALUES ('item2')", - "SAVEPOINT grdb", - "INSERT INTO items (name) VALUES ('item3')", - "ROLLBACK TRANSACTION TO SAVEPOINT grdb", - "RELEASE SAVEPOINT grdb", - "INSERT INTO items (name) VALUES ('item4')", - "COMMIT TRANSACTION", - "INSERT INTO items (name) VALUES ('item5')" - ]) - XCTAssertEqual(try fetchAllItemNames(dbQueue), ["item1", "item2", "item4", "item5"]) - XCTAssertEqual(observer.allRecordedEvents.count, 4) - #if SQLITE_ENABLE_PREUPDATE_HOOK - XCTAssertEqual(observer.allRecordedPreUpdateEvents.count, 4) - #endif - try dbQueue.inDatabase { db in try db.execute(sql: "DELETE FROM items") } - observer.reset() - - sqlQueries.removeAll() - try dbQueue.writeWithoutTransaction { db in - try insertItem(db, name: "item1") - try db.inSavepoint { - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item2") - try db.inSavepoint { - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item3") - return .rollback - } - XCTAssertTrue(db.isInsideTransaction) - try insertItem(db, name: "item4") - return .rollback - } - XCTAssertFalse(db.isInsideTransaction) - try insertItem(db, name: "item5") - } - XCTAssertEqual(sqlQueries, [ - "INSERT INTO items (name) VALUES ('item1')", - "BEGIN DEFERRED TRANSACTION", - "INSERT INTO items (name) VALUES ('item2')", - "SAVEPOINT grdb", - "INSERT INTO items (name) VALUES ('item3')", - "ROLLBACK TRANSACTION TO SAVEPOINT grdb", - "RELEASE SAVEPOINT grdb", - "INSERT INTO items (name) VALUES ('item4')", - "ROLLBACK TRANSACTION", - "INSERT INTO items (name) VALUES ('item5')" - ]) - XCTAssertEqual(try fetchAllItemNames(dbQueue), ["item1", "item5"]) - XCTAssertEqual(observer.allRecordedEvents.count, 4) - #if SQLITE_ENABLE_PREUPDATE_HOOK - XCTAssertEqual(observer.allRecordedPreUpdateEvents.count, 4) - #endif - try dbQueue.inDatabase { db in try db.execute(sql: "DELETE FROM items") } - observer.reset() - } - - func testReleaseTopLevelSavepointFromDatabaseWithDefaultImmediateTransactions() throws { - dbConfiguration.defaultTransactionKind = .immediate - let dbQueue = try makeDatabaseQueue() - let observer = Observer() - dbQueue.add(transactionObserver: observer) - sqlQueries.removeAll() + clearSQLQueries() try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { @@ -344,12 +126,11 @@ class DatabaseSavepointTests: GRDBTestCase { #endif } - func testRollbackTopLevelSavepointFromDatabaseWithDefaultImmediateTransactions() throws { - dbConfiguration.defaultTransactionKind = .immediate + func testRollbackTopLevelSavepoint() throws { let dbQueue = try makeDatabaseQueue() let observer = Observer() dbQueue.add(transactionObserver: observer) - sqlQueries.removeAll() + clearSQLQueries() try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { @@ -374,12 +155,11 @@ class DatabaseSavepointTests: GRDBTestCase { #endif } - func testNestedSavepointFromDatabaseWithDefaultImmediateTransactions() throws { - dbConfiguration.defaultTransactionKind = .immediate + func testNestedSavepoint() throws { let dbQueue = try makeDatabaseQueue() let observer = Observer() dbQueue.add(transactionObserver: observer) - sqlQueries.removeAll() + clearSQLQueries() try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { @@ -416,7 +196,7 @@ class DatabaseSavepointTests: GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "DELETE FROM items") } observer.reset() - sqlQueries.removeAll() + clearSQLQueries() try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { @@ -453,7 +233,7 @@ class DatabaseSavepointTests: GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "DELETE FROM items") } observer.reset() - sqlQueries.removeAll() + clearSQLQueries() try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { @@ -491,7 +271,7 @@ class DatabaseSavepointTests: GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "DELETE FROM items") } observer.reset() - sqlQueries.removeAll() + clearSQLQueries() try dbQueue.writeWithoutTransaction { db in try insertItem(db, name: "item1") try db.inSavepoint { diff --git a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift index 6176865e8..3235f5db9 100644 --- a/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotPoolTests.swift @@ -1,4 +1,4 @@ -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) import XCTest import GRDB @@ -42,7 +42,14 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) // 0 try dbPool.write(counter.increment) // 1 - let snapshot = try dbPool.write { db in try DatabaseSnapshotPool(db) } // locked at 1 + // We can't open a DatabaseSnapshotPool from an IMMEDIATE + // transaction (as documented by sqlite3_snapshot_get). So we + // force a DEFERRED transaction: + var snapshot: DatabaseSnapshotPool! + try dbPool.writeInTransaction(.deferred) { db in + snapshot = try DatabaseSnapshotPool(db) // locked at 1 + return .commit + } try dbPool.write(counter.increment) // 2 try XCTAssertEqual(dbPool.read(counter.value), 2) @@ -55,7 +62,9 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) // 0 try dbPool.write(counter.increment) // 1 - let snapshot = try dbPool.writeWithoutTransaction { db in try DatabaseSnapshotPool(db) } // locked at 1 + let snapshot = try dbPool.writeWithoutTransaction { db in + try DatabaseSnapshotPool(db) // locked at 1 + } try dbPool.write(counter.increment) // 2 try XCTAssertEqual(dbPool.read(counter.value), 2) @@ -220,7 +229,6 @@ final class DatabaseSnapshotPoolTests: GRDBTestCase { try XCTAssertEqual(dbPool.read(counter.value), 2) } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func test_read_async() async throws { let dbPool = try makeDatabasePool() let counter = try Counter(dbPool: dbPool) // 0 diff --git a/Tests/GRDBTests/DatabaseSnapshotTests.swift b/Tests/GRDBTests/DatabaseSnapshotTests.swift index 6730a8984..1cb422ecd 100644 --- a/Tests/GRDBTests/DatabaseSnapshotTests.swift +++ b/Tests/GRDBTests/DatabaseSnapshotTests.swift @@ -424,7 +424,7 @@ class DatabaseSnapshotTests: GRDBTestCase { XCTFail("Expected Error") } catch DatabaseError.SQLITE_BUSY { } } - XCTAssert(lastMessage!.contains("unfinalized statement: SELECT * FROM sqlite_master")) + XCTAssert(lastSQLiteDiagnostic!.message.contains("unfinalized statement: SELECT * FROM sqlite_master")) // Database is not closed: no error try snapshot.read { db in diff --git a/Tests/GRDBTests/DatabaseSuspensionTests.swift b/Tests/GRDBTests/DatabaseSuspensionTests.swift index eea8a31c7..ce205c6cf 100644 --- a/Tests/GRDBTests/DatabaseSuspensionTests.swift +++ b/Tests/GRDBTests/DatabaseSuspensionTests.swift @@ -507,7 +507,7 @@ class DatabaseSuspensionTests : GRDBTestCase { try db.execute(sql: "SELECT * FROM sqlite_master") XCTAssertEqual(db.journalModeCache, "wal") } - try dbPool.write { db in + dbPool.writeWithoutTransaction { db in XCTAssertEqual(db.journalModeCache, "wal") } try dbPool.read { db in diff --git a/Tests/GRDBTests/DatabaseTests.swift b/Tests/GRDBTests/DatabaseTests.swift index 145340ab3..6b37ab2ad 100644 --- a/Tests/GRDBTests/DatabaseTests.swift +++ b/Tests/GRDBTests/DatabaseTests.swift @@ -505,16 +505,54 @@ class DatabaseTests : GRDBTestCase { try dbQueue.inTransaction { db in .commit } } + func testImplicitTransactionManagement() throws { + let dbQueue = try makeDatabaseQueue() + + try dbQueue.read { db in + XCTAssertEqual(lastSQLQuery, "BEGIN DEFERRED TRANSACTION") + } + + try dbQueue.write { db in + XCTAssertEqual(lastSQLQuery, "BEGIN IMMEDIATE TRANSACTION") + } + + try dbQueue.writeWithoutTransaction { db in + try db.beginTransaction() + XCTAssertEqual(lastSQLQuery, "BEGIN IMMEDIATE TRANSACTION") + try db.rollback() + XCTAssertEqual(lastSQLQuery, "ROLLBACK TRANSACTION") + + try db.inSavepoint { + XCTAssertEqual(lastSQLQuery, "BEGIN IMMEDIATE TRANSACTION") + return .commit + } + XCTAssertEqual(lastSQLQuery, "COMMIT TRANSACTION") + + try db.readOnly { + try db.beginTransaction() + XCTAssertEqual(lastSQLQuery, "BEGIN DEFERRED TRANSACTION") + try db.rollback() + XCTAssertEqual(lastSQLQuery, "ROLLBACK TRANSACTION") + + try db.inSavepoint { + XCTAssertEqual(lastSQLQuery, "BEGIN DEFERRED TRANSACTION") + return .rollback + } + XCTAssertEqual(lastSQLQuery, "ROLLBACK TRANSACTION") + } + } + } + func testExplicitTransactionManagement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.writeWithoutTransaction { db in - try db.beginTransaction() + try db.beginTransaction(.deferred) XCTAssertEqual(lastSQLQuery, "BEGIN DEFERRED TRANSACTION") - try db.rollback() - XCTAssertEqual(lastSQLQuery, "ROLLBACK TRANSACTION") - try db.beginTransaction(.immediate) - XCTAssertEqual(lastSQLQuery, "BEGIN IMMEDIATE TRANSACTION") + try db.commit() + XCTAssertEqual(lastSQLQuery, "COMMIT TRANSACTION") + try db.beginTransaction(.exclusive) + XCTAssertEqual(lastSQLQuery, "BEGIN EXCLUSIVE TRANSACTION") try db.commit() XCTAssertEqual(lastSQLQuery, "COMMIT TRANSACTION") } @@ -561,11 +599,10 @@ class DatabaseTests : GRDBTestCase { } func testReadOnlyTransaction() throws { - dbConfiguration.defaultTransactionKind = .immediate let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() try db.inSavepoint { .commit } try db.inTransaction { .commit } try db.inTransaction(.immediate) { .commit } @@ -573,7 +610,7 @@ class DatabaseTests : GRDBTestCase { } try db.readOnly { - sqlQueries.removeAll() + clearSQLQueries() try db.inSavepoint { .commit } try db.inTransaction { .commit } XCTAssertEqual(Set(sqlQueries), ["BEGIN DEFERRED TRANSACTION", "COMMIT TRANSACTION"]) diff --git a/Tests/GRDBTests/DatabaseTraceTests.swift b/Tests/GRDBTests/DatabaseTraceTests.swift index df9d73119..8ad6eedc7 100644 --- a/Tests/GRDBTests/DatabaseTraceTests.swift +++ b/Tests/GRDBTests/DatabaseTraceTests.swift @@ -114,11 +114,11 @@ class DatabaseTraceTests : GRDBTestCase { } func testTraceFromConfigurationWithDefaultOptions() throws { - var events: [String] = [] + let eventsMutex: Mutex<[String]> = Mutex([]) var configuration = Configuration() configuration.prepareDatabase { db in db.trace { event in - events.append("SQL: \(event)") + eventsMutex.withLock { $0.append("SQL: \(event)") } } } let dbQueue = try makeDatabaseQueue(configuration: configuration) @@ -127,19 +127,19 @@ class DatabaseTraceTests : GRDBTestCase { CREATE table t(a); INSERT INTO t (a) VALUES (?) """, arguments: [1]) - XCTAssertEqual(events.suffix(2), [ + XCTAssertEqual(eventsMutex.load().suffix(2), [ "SQL: CREATE table t(a)", "SQL: INSERT INTO t (a) VALUES (?)"]) } } func testTraceFromConfigurationWithPublicStatementArguments() throws { - var events: [String] = [] + let eventsMutex: Mutex<[String]> = Mutex([]) var configuration = Configuration() configuration.publicStatementArguments = true configuration.prepareDatabase { db in db.trace { event in - events.append("SQL: \(event)") + eventsMutex.withLock { $0.append("SQL: \(event)") } } } let dbQueue = try makeDatabaseQueue(configuration: configuration) @@ -148,7 +148,7 @@ class DatabaseTraceTests : GRDBTestCase { CREATE table t(a); INSERT INTO t (a) VALUES (?) """, arguments: [1]) - XCTAssertEqual(events.suffix(2), [ + XCTAssertEqual(eventsMutex.load().suffix(2), [ "SQL: CREATE table t(a)", "SQL: INSERT INTO t (a) VALUES (1)"]) } diff --git a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift index 2245a8be6..14dce9d84 100644 --- a/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift +++ b/Tests/GRDBTests/DatabaseUUIDEncodingStrategyTests.swift @@ -19,21 +19,25 @@ private enum StrategyLowercaseString: StrategyProvider { } private struct RecordWithUUID: EncodableRecord, Encodable { - static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { Strategy.strategy } + static func databaseUUIDEncodingStrategy(for column: String) -> DatabaseUUIDEncodingStrategy { + Strategy.strategy + } + var uuid: UUID } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension RecordWithUUID: Identifiable { var id: UUID { uuid } } private struct RecordWithOptionalUUID: EncodableRecord, Encodable { - static var databaseUUIDEncodingStrategy: DatabaseUUIDEncodingStrategy { Strategy.strategy } + static func databaseUUIDEncodingStrategy(for column: String) -> DatabaseUUIDEncodingStrategy { + Strategy.strategy + } + var uuid: UUID? } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension RecordWithOptionalUUID: Identifiable { var id: UUID? { uuid } } @@ -184,10 +188,6 @@ extension DatabaseUUIDEncodingStrategyTests { } func testFilterID() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - try makeDatabaseQueue().write { db in try db.create(table: "t") { $0.primaryKey("id", .blob) } let uuids = [ @@ -303,10 +303,6 @@ extension DatabaseUUIDEncodingStrategyTests { } func testDeleteID() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Identifiable not available") - } - try makeDatabaseQueue().write { db in try db.create(table: "t") { $0.primaryKey("id", .blob) } let uuids = [ @@ -357,7 +353,7 @@ extension DatabaseUUIDEncodingStrategyTests { } do { - sqlQueries.removeAll() + clearSQLQueries() try Table>("t").deleteOne(db, id: nil) XCTAssertNil(lastSQLQuery) // Database not hit } @@ -377,7 +373,7 @@ extension DatabaseUUIDEncodingStrategyTests { } do { - sqlQueries.removeAll() + clearSQLQueries() try Table>("t").deleteOne(db, id: nil) XCTAssertNil(lastSQLQuery) // Database not hit } @@ -397,7 +393,7 @@ extension DatabaseUUIDEncodingStrategyTests { } do { - sqlQueries.removeAll() + clearSQLQueries() try Table>("t").deleteOne(db, id: nil) XCTAssertNil(lastSQLQuery) // Database not hit } diff --git a/Tests/GRDBTests/DatabaseWriterTests.swift b/Tests/GRDBTests/DatabaseWriterTests.swift index 9139b1f9e..0fcc3b487 100644 --- a/Tests/GRDBTests/DatabaseWriterTests.swift +++ b/Tests/GRDBTests/DatabaseWriterTests.swift @@ -195,11 +195,11 @@ class DatabaseWriterTests : GRDBTestCase { } func testVacuumInto() throws { - guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else { + guard #available(iOS 14, macOS 10.16, tvOS 14, *) else { 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") } @@ -266,7 +266,6 @@ class DatabaseWriterTests : GRDBTestCase { try DatabaseQueue().backup(to: dbQueue) } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_write() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -286,7 +285,6 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabasePool())) } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_writeWithoutTransaction() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -309,7 +307,6 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabasePool())) } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_barrierWriteWithoutTransaction() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -332,7 +329,6 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabasePool())) } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_erase() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -350,7 +346,6 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabasePool())) } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_vacuum() async throws { func setup(_ dbWriter: T) throws -> T { try dbWriter.write { db in @@ -366,10 +361,10 @@ class DatabaseWriterTests : GRDBTestCase { try await test(setup(makeDatabasePool())) } - @available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) // async + vacuum into + @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") } @@ -397,7 +392,6 @@ class DatabaseWriterTests : GRDBTestCase { } /// A test related to - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncWriteThenRead() async throws { /// An async read performed after an async write should see the write. func test(_ dbWriter: some DatabaseWriter) async throws { @@ -418,4 +412,450 @@ class DatabaseWriterTests : GRDBTestCase { try await test(makeDatabaseQueue()) try await test(makeDatabasePool()) } + + // MARK: - Task Cancellation + + // Regression test for . + 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?>(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) + let task = Task { + await semaphore.wait() + try await dbWriter.writeWithoutTransaction { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.writeWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.writeWithoutTransaction { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.writeWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_statement_execution_from_writeWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.writeWithoutTransaction { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.writeWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_cursor_iteration_from_writeWithoutTransaction_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.writeWithoutTransaction { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.writeWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_write_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbWriter.write { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.write { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_write_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.write { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.write { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_statement_execution_from_write_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.write { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.write { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_cursor_iteration_from_write_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.write { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.write { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_barrierWriteWithoutTransaction_is_cancelled_by_Task_cancellation_performed_before_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let task = Task { + await semaphore.wait() + try await dbWriter.barrierWriteWithoutTransaction { db in + XCTFail("Should not be executed") + } + } + task.cancel() + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.barrierWriteWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_barrierWriteWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.barrierWriteWithoutTransaction { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.barrierWriteWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_statement_execution_from_barrierWriteWithoutTransaction_is_cancelled_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.barrierWriteWithoutTransaction { db in + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + try db.execute(sql: "SELECT 0") + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.barrierWriteWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } + + func test_cursor_iteration_from_barrierWriteWithoutTransaction_is_interrupted_by_Task_cancellation_performed_after_database_access() async throws { + func test(_ dbWriter: some DatabaseWriter) async throws { + let semaphore = AsyncSemaphore(value: 0) + let cancelledTaskMutex = Mutex?>(nil) + let task = Task { + await semaphore.wait() + try await dbWriter.barrierWriteWithoutTransaction { db in + let cursor = try Int.fetchCursor(db, sql: """ + SELECT 1 UNION ALL SELECT 2 + """) + _ = try cursor.next() + try XCTUnwrap(cancelledTaskMutex.load()).cancel() + _ = try cursor.next() + XCTFail("Expected error") + } + } + cancelledTaskMutex.store(task) + semaphore.signal() + + do { + try await task.value + XCTFail("Expected error") + } catch { + XCTAssert(error is CancellationError) + } + + // Database access is restored after cancellation (no error is thrown) + try await dbWriter.barrierWriteWithoutTransaction { db in + try db.execute(sql: "SELECT 0") + } + } + + try await test(makeDatabaseQueue()) + try await test(makeDatabasePool()) + try await test(AnyDatabaseWriter(makeDatabaseQueue())) + } } diff --git a/Tests/GRDBTests/DerivableRequestTests.swift b/Tests/GRDBTests/DerivableRequestTests.swift index 1cb5f91b2..60c120226 100644 --- a/Tests/GRDBTests/DerivableRequestTests.swift +++ b/Tests/GRDBTests/DerivableRequestTests.swift @@ -15,6 +15,12 @@ private struct Author: FetchableRecord, PersistableRecord, Codable { static let databaseTableName = "author" static let books = hasMany(Book.self) + enum Columns { + static let firstName = Column(CodingKeys.firstName) + static let lastName = Column(CodingKeys.lastName) + static let country = Column(CodingKeys.country) + } + var books: QueryInterfaceRequest { request(for: Author.books) } } @@ -30,6 +36,10 @@ private struct Book: FetchableRecord, PersistableRecord, Codable { static let bookFts5 = hasOne(BookFts5.self, using: ForeignKey([.rowID])) #endif + enum Columns { + static let title = Column(CodingKeys.title) + } + var author: QueryInterfaceRequest { request(for: Book.author) } } @@ -77,26 +87,27 @@ private var libraryMigrator: DatabaseMigrator = { extension DerivableRequest { // SelectionRequest func selectCountry() -> Self { - select(Column("country")) + select { $0.country } } // FilteredRequest func filter(country: String) -> Self { - filter(Column("country") == country) + filter { $0.country == country } } // OrderedRequest func orderByFullName() -> Self { - order( - Column("lastName").collating(.localizedCaseInsensitiveCompare), - Column("firstName").collating(.localizedCaseInsensitiveCompare)) + order { [ + $0.lastName.collating(.localizedCaseInsensitiveCompare), + $0.firstName.collating(.localizedCaseInsensitiveCompare), + ] } } } extension DerivableRequest { // OrderedRequest func orderByTitle() -> Self { - order(Column("title").collating(.localizedCaseInsensitiveCompare)) + order { $0.title.collating(.localizedCaseInsensitiveCompare) } } // JoinableRequest @@ -174,13 +185,13 @@ 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 - sqlQueries.removeAll() + clearSQLQueries() let authorNames = try Author.all() .orderByFullName() .fetchAll(db) @@ -192,7 +203,7 @@ class DerivableRequestTests: GRDBTestCase { "firstName" COLLATE swiftLocalizedCaseInsensitiveCompare """) - sqlQueries.removeAll() + clearSQLQueries() let reversedAuthorNames = try Author.all() .orderByFullName() .reversed() @@ -205,7 +216,7 @@ class DerivableRequestTests: GRDBTestCase { "firstName" COLLATE swiftLocalizedCaseInsensitiveCompare DESC """) - sqlQueries.removeAll() + clearSQLQueries() _ /* unorderedAuthors */ = try Author.all() .orderByFullName() .unordered() @@ -214,15 +225,15 @@ class DerivableRequestTests: GRDBTestCase { SELECT * FROM "author" """) - sqlQueries.removeAll() + clearSQLQueries() _ /* stableOrderAuthors */ = try Author.all() .withStableOrder() .fetchAll(db) XCTAssertEqual(lastSQLQuery, """ SELECT * FROM "author" ORDER BY "id" """) - - sqlQueries.removeAll() + + clearSQLQueries() _ /* stableOrderAuthors */ = try Author.all() .orderByFullName() .withStableOrder() @@ -232,7 +243,7 @@ class DerivableRequestTests: GRDBTestCase { """) // ... for one view - sqlQueries.removeAll() + clearSQLQueries() _ /* authorViewNames */ = try Table("authorView").all() .order(Column("fullName")) .fetchAll(db) @@ -241,7 +252,7 @@ class DerivableRequestTests: GRDBTestCase { ORDER BY "fullName" """) - sqlQueries.removeAll() + clearSQLQueries() _ /* reversedAuthorViewNames */ = try Table("authorView").all() .order(Column("fullName")) .reversed() @@ -251,7 +262,7 @@ class DerivableRequestTests: GRDBTestCase { ORDER BY "fullName" DESC """) - sqlQueries.removeAll() + clearSQLQueries() _ /* unorderedAuthorViews */ = try Table("authorView").all() .order(Column("fullName")) .unordered() @@ -260,15 +271,15 @@ class DerivableRequestTests: GRDBTestCase { SELECT * FROM "authorView" """) - sqlQueries.removeAll() + clearSQLQueries() _ /* stableOrderAuthorViews */ = try Table("authorView").all() .withStableOrder() .fetchAll(db) XCTAssertEqual(lastSQLQuery, """ SELECT * FROM "authorView" ORDER BY 1, 2, 3, 4, 5 """) - - sqlQueries.removeAll() + + clearSQLQueries() _ /* stableOrderAuthorViews */ = try Table("authorView").all() .order(Column("fullName")) .withStableOrder() @@ -278,7 +289,7 @@ class DerivableRequestTests: GRDBTestCase { """) // ... for two tables (2) - sqlQueries.removeAll() + clearSQLQueries() let bookTitles = try Book .joining(required: Book.author.orderByFullName()) .orderByTitle() @@ -294,7 +305,7 @@ class DerivableRequestTests: GRDBTestCase { "author"."firstName" COLLATE swiftLocalizedCaseInsensitiveCompare """) - sqlQueries.removeAll() + clearSQLQueries() let reversedBookTitles = try Book .joining(required: Book.author.orderByFullName()) .orderByTitle() @@ -311,7 +322,7 @@ class DerivableRequestTests: GRDBTestCase { "author"."firstName" COLLATE swiftLocalizedCaseInsensitiveCompare DESC """) - sqlQueries.removeAll() + clearSQLQueries() _ /* unorderedBooks */ = try Book .joining(required: Book.author.orderByFullName()) .orderByTitle() @@ -322,7 +333,7 @@ class DerivableRequestTests: GRDBTestCase { JOIN "author" ON "author"."id" = "book"."authorId" """) - sqlQueries.removeAll() + clearSQLQueries() _ /* stableOrderBooks */ = try Book .joining(required: Book.author.orderByFullName()) .orderByTitle() @@ -346,7 +357,7 @@ class DerivableRequestTests: GRDBTestCase { try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() let request = Author.all().selectCountry() let authorCountries = try Set(String.fetchAll(db, request)) XCTAssertEqual(authorCountries, ["FR", "US"]) @@ -356,7 +367,7 @@ class DerivableRequestTests: GRDBTestCase { } do { - sqlQueries.removeAll() + clearSQLQueries() let request = Book.including(required: Book.author.selectCountry()) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, """ @@ -373,7 +384,7 @@ class DerivableRequestTests: GRDBTestCase { try libraryMigrator.migrate(dbQueue) try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() let frenchBookTitles = try Book.all() .filter(authorCountry: "FR") .order(Column("title")) @@ -389,7 +400,7 @@ class DerivableRequestTests: GRDBTestCase { } do { - sqlQueries.removeAll() + clearSQLQueries() let frenchAuthorFullNames = try Author .joining(required: Author.books.filter(authorCountry: "FR")) .order(Column("firstName")) @@ -436,7 +447,7 @@ class DerivableRequestTests: GRDBTestCase { // matchingFts4 do { - sqlQueries.removeAll() + clearSQLQueries() let title = try Book.all() .matchingFts4(FTS3Pattern(rawPattern: "moby dick")) .fetchOne(db) @@ -448,7 +459,7 @@ class DerivableRequestTests: GRDBTestCase { LIMIT 1 """)) - sqlQueries.removeAll() + clearSQLQueries() let fullName = try Author .joining(required: Author.books.matchingFts4(FTS3Pattern(rawPattern: "moby dick"))) .fetchOne(db) @@ -465,7 +476,7 @@ class DerivableRequestTests: GRDBTestCase { #if SQLITE_ENABLE_FTS5 // matchingFts5 do { - sqlQueries.removeAll() + clearSQLQueries() let title = try Book.all() .matchingFts5(FTS3Pattern(rawPattern: "cote swann")) .fetchOne(db) @@ -477,7 +488,7 @@ class DerivableRequestTests: GRDBTestCase { LIMIT 1 """)) - sqlQueries.removeAll() + clearSQLQueries() let fullName = try Author .joining(required: Author.books.matchingFts5(FTS3Pattern(rawPattern: "cote swann"))) .fetchOne(db) diff --git a/Tests/GRDBTests/FTS3RecordTests.swift b/Tests/GRDBTests/FTS3RecordTests.swift index b37c08bb5..162532342 100644 --- a/Tests/GRDBTests/FTS3RecordTests.swift +++ b/Tests/GRDBTests/FTS3RecordTests.swift @@ -19,7 +19,7 @@ extension Book : FetchableRecord { extension Book : MutablePersistableRecord { static let databaseTableName = "books" - static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] + static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] } func encode(to container: inout PersistenceContainer) { container[.rowID] = id @@ -102,14 +102,14 @@ class FTS3RecordTests: GRDBTestCase { } do { - sqlQueries = [] + clearSQLQueries() let pattern = try FTS3Pattern(rawPattern: "Herman Melville") XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1) XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'Herman Melville'")) } do { - sqlQueries = [] + clearSQLQueries() XCTAssertEqual(try Book.fetchCount(db), 1) XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\"")) } diff --git a/Tests/GRDBTests/FTS3TableBuilderTests.swift b/Tests/GRDBTests/FTS3TableBuilderTests.swift index b2434da37..55ca5a8fc 100644 --- a/Tests/GRDBTests/FTS3TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS3TableBuilderTests.swift @@ -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()) @@ -76,7 +98,7 @@ class FTS3TableBuilderTests: GRDBTestCase { } #elseif !GRDBCIPHER func testUnicode61TokenizerDiacriticsRemove() throws { - guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else { + guard #available(iOS 14, macOS 10.16, tvOS 14, *) else { throw XCTSkip() } let dbQueue = try makeDatabaseQueue() diff --git a/Tests/GRDBTests/FTS4RecordTests.swift b/Tests/GRDBTests/FTS4RecordTests.swift index 646c3852e..ed3641c10 100644 --- a/Tests/GRDBTests/FTS4RecordTests.swift +++ b/Tests/GRDBTests/FTS4RecordTests.swift @@ -19,7 +19,7 @@ extension Book : FetchableRecord { extension Book : MutablePersistableRecord { static let databaseTableName = "books" - static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] + static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] } func encode(to container: inout PersistenceContainer) { container[.rowID] = id @@ -102,14 +102,14 @@ class FTS4RecordTests: GRDBTestCase { } do { - sqlQueries = [] + clearSQLQueries() let pattern = try FTS3Pattern(rawPattern: "Herman Melville") XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1) XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'Herman Melville'")) } do { - sqlQueries = [] + clearSQLQueries() XCTAssertEqual(try Book.fetchCount(db), 1) XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\"")) } diff --git a/Tests/GRDBTests/FTS4TableBuilderTests.swift b/Tests/GRDBTests/FTS4TableBuilderTests.swift index ad7287b4d..653ce0b7a 100644 --- a/Tests/GRDBTests/FTS4TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS4TableBuilderTests.swift @@ -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 @@ -272,16 +294,16 @@ class FTS4TableBuilderTests: GRDBTestCase { func testFTS4Compression() throws { // Based on https://github.com/groue/GRDB.swift/issues/369 - var compressCalled = false - var uncompressCalled = false + let compressCalledMutex = Mutex(false) + let uncompressCalledMutex = Mutex(false) dbConfiguration.prepareDatabase { db in db.add(function: DatabaseFunction("zipit", argumentCount: 1, pure: true, function: { dbValues in - compressCalled = true + compressCalledMutex.store(true) return dbValues[0] })) db.add(function: DatabaseFunction("unzipit", argumentCount: 1, pure: true, function: { dbValues in - uncompressCalled = true + uncompressCalledMutex.store(true) return dbValues[0] })) } @@ -296,12 +318,12 @@ class FTS4TableBuilderTests: GRDBTestCase { assertDidExecute(sql: "CREATE VIRTUAL TABLE \"documents\" USING fts4(content, compress=\"zipit\", uncompress=\"unzipit\")") try db.execute(sql: "INSERT INTO documents (content) VALUES (?)", arguments: ["abc"]) - XCTAssertTrue(compressCalled) + XCTAssertTrue(compressCalledMutex.load()) } try dbPool.read { db in _ = try Row.fetchOne(db, sql: "SELECT * FROM documents") - XCTAssertTrue(uncompressCalled) + XCTAssertTrue(uncompressCalledMutex.load()) } } } diff --git a/Tests/GRDBTests/FTS5PatternTests.swift b/Tests/GRDBTests/FTS5PatternTests.swift index fc7e1a0bf..4da8bf0de 100644 --- a/Tests/GRDBTests/FTS5PatternTests.swift +++ b/Tests/GRDBTests/FTS5PatternTests.swift @@ -43,9 +43,16 @@ class FTS5PatternTests: GRDBTestCase { ("title:brest", 1) ] for (rawPattern, expectedCount) in validRawPatterns { - let pattern = try db.makeFTS5Pattern(rawPattern: rawPattern, forTable: "books") - let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: [pattern])! - XCTAssertEqual(count, expectedCount, "Expected pattern \(String(reflecting: rawPattern)) to yield \(expectedCount) results") + do { + let pattern = try FTS5Pattern(rawPattern: rawPattern, allowedColumns: ["title"]) + let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: [pattern])! + XCTAssertEqual(count, expectedCount, "Expected pattern \(String(reflecting: rawPattern)) to yield \(expectedCount) results") + } + do { + let pattern = try db.makeFTS5Pattern(rawPattern: rawPattern, forTable: "books") + let count = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM books WHERE books MATCH ?", arguments: [pattern])! + XCTAssertEqual(count, expectedCount, "Expected pattern \(String(reflecting: rawPattern)) to yield \(expectedCount) results") + } } } } @@ -55,6 +62,14 @@ class FTS5PatternTests: GRDBTestCase { dbQueue.inDatabase { db in let invalidRawPatterns = ["", "?!", "^", "NOT", "(", "AND", "OR", "\"", "missing:foo"] for rawPattern in invalidRawPatterns { + do { + _ = try FTS5Pattern(rawPattern: rawPattern, allowedColumns: ["title"]) + XCTFail("Expected pattern to be invalid: \(String(reflecting: rawPattern))") + } catch is DatabaseError { + } catch { + XCTFail("Expected DatabaseError, not \(error)") + } + do { _ = try db.makeFTS5Pattern(rawPattern: rawPattern, forTable: "books") XCTFail("Expected pattern to be invalid: \(String(reflecting: rawPattern))") diff --git a/Tests/GRDBTests/FTS5RecordTests.swift b/Tests/GRDBTests/FTS5RecordTests.swift index b25b0a013..1415a5631 100644 --- a/Tests/GRDBTests/FTS5RecordTests.swift +++ b/Tests/GRDBTests/FTS5RecordTests.swift @@ -20,7 +20,7 @@ extension Book : FetchableRecord { extension Book : MutablePersistableRecord { static let databaseTableName = "books" - static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] + static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] } func encode(to container: inout PersistenceContainer) { container[.rowID] = id @@ -101,14 +101,14 @@ class FTS5RecordTests: GRDBTestCase { } do { - sqlQueries = [] + clearSQLQueries() let pattern = FTS5Pattern(matchingAllTokensIn: "Herman Melville")! XCTAssertEqual(try Book.matching(pattern).fetchCount(db), 1) XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\" WHERE \"books\" MATCH 'herman melville'")) } do { - sqlQueries = [] + clearSQLQueries() XCTAssertEqual(try Book.fetchCount(db), 1) XCTAssertTrue(sqlQueries.contains("SELECT COUNT(*) FROM \"books\"")) } diff --git a/Tests/GRDBTests/FTS5TableBuilderTests.swift b/Tests/GRDBTests/FTS5TableBuilderTests.swift index b44dc6589..9e9db3162 100644 --- a/Tests/GRDBTests/FTS5TableBuilderTests.swift +++ b/Tests/GRDBTests/FTS5TableBuilderTests.swift @@ -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 @@ -130,7 +156,7 @@ class FTS5TableBuilderTests: GRDBTestCase { } #elseif !GRDBCIPHER func testUnicode61TokenizerDiacriticsRemove() throws { - guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else { + guard #available(iOS 14, macOS 10.16, tvOS 14, *) else { throw XCTSkip() } @@ -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 func testIssue1390() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER - guard sqlite3_libversion_number() >= 3035000 else { + guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("UPSERT is not available") } #else diff --git a/Tests/GRDBTests/FTS5TokenizerTests.swift b/Tests/GRDBTests/FTS5TokenizerTests.swift index af88e7351..0837ee5c0 100644 --- a/Tests/GRDBTests/FTS5TokenizerTests.swift +++ b/Tests/GRDBTests/FTS5TokenizerTests.swift @@ -203,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") } @@ -363,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") } diff --git a/Tests/GRDBTests/FetchableRecordDecodableTests.swift b/Tests/GRDBTests/FetchableRecordDecodableTests.swift index 8c7d0c195..1cbba07d8 100644 --- a/Tests/GRDBTests/FetchableRecordDecodableTests.swift +++ b/Tests/GRDBTests/FetchableRecordDecodableTests.swift @@ -121,6 +121,92 @@ extension FetchableRecordDecodableTests { } } + func testSingleValueDataProperty() throws { + struct Value : Decodable { + let data: Data + + init(from decoder: Decoder) throws { + data = try decoder.singleValueContainer().decode(Data.self) + } + } + + struct Struct : FetchableRecord, Decodable { + static func databaseDataDecodingStrategy(for column: String) -> DatabaseDataDecodingStrategy { + if column == "value" { + return .custom { _ in Data([1, 2, 3]) } + } else { + return .deferredToData + } + } + let value: Value + let optionalValue: Value? + } + + do { + // No null values + let s = try Struct(row: ["value": "foo", "optionalValue": "bar"]) + XCTAssertEqual(s.value.data, Data([1, 2, 3])) + XCTAssertEqual(s.optionalValue?.data, Data([98, 97, 114])) + } + + do { + // Null values + let s = try Struct(row: ["value": "foo", "optionalValue": nil]) + XCTAssertEqual(s.value.data, Data([1, 2, 3])) + XCTAssertNil(s.optionalValue) + } + + do { + // Missing and extra values + let s = try Struct(row: ["value": "foo", "ignored": "?"]) + XCTAssertEqual(s.value.data, Data([1, 2, 3])) + XCTAssertNil(s.optionalValue) + } + } + + func testSingleValueDateProperty() throws { + struct Value : Decodable { + let date: Date + + init(from decoder: Decoder) throws { + date = try decoder.singleValueContainer().decode(Date.self) + } + } + + struct Struct : FetchableRecord, Decodable { + static func databaseDateDecodingStrategy(for column: String) -> DatabaseDateDecodingStrategy { + if column == "value" { + return .custom { _ in Date(timeIntervalSince1970: 0) } + } else { + return .deferredToDate + } + } + let value: Value + let optionalValue: Value? + } + + do { + // No null values + let s = try Struct(row: ["value": "foo", "optionalValue": "2001-01-01 00:00:00"]) + XCTAssertEqual(s.value.date, Date(timeIntervalSince1970: 0)) + XCTAssertEqual(s.optionalValue?.date, Date(timeIntervalSinceReferenceDate: 0)) + } + + do { + // Null values + let s = try Struct(row: ["value": "foo", "optionalValue": nil]) + XCTAssertEqual(s.value.date, Date(timeIntervalSince1970: 0)) + XCTAssertNil(s.optionalValue) + } + + do { + // Missing and extra values + let s = try Struct(row: ["value": "foo", "ignored": "?"]) + XCTAssertEqual(s.value.date, Date(timeIntervalSince1970: 0)) + XCTAssertNil(s.optionalValue) + } + } + func testNonTrivialSingleValueDecodableProperty() throws { struct NestedValue : Decodable { let string: String @@ -1275,9 +1361,12 @@ extension FetchableRecordDecodableTests { context = decoder.userInfo[testKeyRoot] as? String } - static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [ - testKeyRoot: "GRDB root", - testKeyNested: "GRDB column or scope"] + static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { + [ + testKeyRoot: "GRDB root", + testKeyNested: "GRDB column or scope", + ] + } static func databaseJSONDecoder(for column: String) -> JSONDecoder { let decoder = JSONDecoder() @@ -1580,7 +1669,9 @@ extension FetchableRecordDecodableTests { struct StructWithNestedType : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" - static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [CodingUserInfoKey.testKey: "correct"] + static var databaseDecodingUserInfo: [CodingUserInfoKey: Any] { + [CodingUserInfoKey.testKey: "correct"] + } let nested: NestedStruct? } diff --git a/Tests/GRDBTests/ForeignKeyDefinitionTests.swift b/Tests/GRDBTests/ForeignKeyDefinitionTests.swift index d6bacfc5a..8a4940476 100644 --- a/Tests/GRDBTests/ForeignKeyDefinitionTests.swift +++ b/Tests/GRDBTests/ForeignKeyDefinitionTests.swift @@ -20,7 +20,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { t.column("name", .text) } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent") @@ -99,7 +99,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { t.column("name", .text) } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child", options: .ifNotExists) { t in t.column("a") t.belongsTo("parent") @@ -155,7 +155,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { t.column("name", .text) } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent").unique() @@ -197,7 +197,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { t.column("name", .text) } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent", indexed: false) @@ -239,7 +239,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { t.column("name", .text) } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent").notNull() @@ -295,7 +295,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { t.column("name", .text) } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent", onDelete: .cascade, onUpdate: .setNull, deferred: true) @@ -411,7 +411,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { t.primaryKey("id", .integer) } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent") @@ -494,7 +494,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { t.primaryKey("id", .integer) } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child", options: .ifNotExists) { t in t.column("a") t.belongsTo("parent") @@ -556,7 +556,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { t.primaryKey("id", .integer) } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent").unique() @@ -604,7 +604,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { t.primaryKey("id", .integer) } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent", indexed: false) @@ -652,7 +652,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { t.primaryKey("id", .integer) } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent").notNull() @@ -714,7 +714,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { t.primaryKey("id", .integer) } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent", onDelete: .cascade, onUpdate: .setNull, deferred: true) @@ -757,7 +757,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { func testTable_belongsTo_singleColumnPrimaryKey_autoreference_singular() throws { try makeDatabaseQueue().inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "employee") { t in t.autoIncrementedPrimaryKey("id") t.column("a") @@ -786,7 +786,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { } do { - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "node") { t in t.primaryKey { t.column("code") } t.column("a") @@ -820,7 +820,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { func testTable_belongsTo_singleColumnPrimaryKey_autoreference_plural() throws { try makeDatabaseQueue().inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "employees") { t in t.autoIncrementedPrimaryKey("id") t.column("a") @@ -849,7 +849,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { } do { - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "nodes") { t in t.primaryKey { t.column("code") } t.column("a") @@ -913,7 +913,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { } } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent") @@ -1025,7 +1025,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { } } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child", options: .ifNotExists) { t in t.column("a") t.belongsTo("parent") @@ -1107,7 +1107,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { } } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent").unique() @@ -1189,7 +1189,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { } } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent", indexed: false) @@ -1257,7 +1257,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { } } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent").notNull() @@ -1339,7 +1339,7 @@ class ForeignKeyDefinitionTests: GRDBTestCase { } } - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "child") { t in t.column("a") t.belongsTo("parent", onDelete: .cascade, onUpdate: .setNull, deferred: true) diff --git a/Tests/GRDBTests/FoundationDateComponentsTests.swift b/Tests/GRDBTests/FoundationDateComponentsTests.swift index b336a7525..bf3b7b082 100644 --- a/Tests/GRDBTests/FoundationDateComponentsTests.swift +++ b/Tests/GRDBTests/FoundationDateComponentsTests.swift @@ -708,7 +708,7 @@ class FoundationDateComponentsTests : GRDBTestCase { } let record = Record(date: DatabaseDateComponents(DateComponents(year: 2018, month: 12, day: 31), format: .YMD)) let jsonData = try JSONEncoder().encode(record) - let json = String(data: jsonData, encoding: .utf8)! + let json = String(decoding: jsonData, as: UTF8.self) XCTAssertEqual(json, """ {"date":"2018-12-31"} """) diff --git a/Tests/GRDBTests/GRDBTestCase.swift b/Tests/GRDBTests/GRDBTestCase.swift index 9028d491f..c93a23ad5 100644 --- a/Tests/GRDBTests/GRDBTestCase.swift +++ b/Tests/GRDBTests/GRDBTestCase.swift @@ -1,17 +1,26 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import Foundation import XCTest @testable import GRDB // Support for Database.logError -var lastResultCode: ResultCode? = nil -var lastMessage: String? = nil +struct SQLiteDiagnostic { + var resultCode: ResultCode + var message: String +} +private let lastSQLiteDiagnosticMutex = Mutex(nil) +var lastSQLiteDiagnostic: SQLiteDiagnostic? { lastSQLiteDiagnosticMutex.load() } let logErrorSetup: Void = { - let lock = NSLock() Database.logError = { (resultCode, message) in - lock.lock() - defer { lock.unlock() } - lastResultCode = resultCode - lastMessage = message + lastSQLiteDiagnosticMutex.store(SQLiteDiagnostic(resultCode: resultCode, message: message)) } }() @@ -55,10 +64,12 @@ class GRDBTestCase: XCTestCase { // The default path for database pool directory private var dbDirectoryPath: String! - // Populated by default configuration - @LockedBox var sqlQueries: [String] = [] + let _sqlQueriesMutex: Mutex<[String]> = Mutex([]) - // Populated by default configuration + // Automatically updated by default dbConfiguration + var sqlQueries: [String] { _sqlQueriesMutex.load() } + + // Automatically updated by default dbConfiguration var lastSQLQuery: String? { sqlQueries.last } override func setUp() { @@ -73,7 +84,7 @@ class GRDBTestCase: XCTestCase { dbConfiguration = Configuration() // Test that database are deallocated in a clean state - dbConfiguration.SQLiteConnectionWillClose = { sqliteConnection in + dbConfiguration.onConnectionWillClose { sqliteConnection in // https://www.sqlite.org/capi3ref.html#sqlite3_close: // > If sqlite3_close_v2() is called on a database connection that still // > has outstanding prepared statements, BLOB handles, and/or @@ -103,9 +114,11 @@ class GRDBTestCase: XCTestCase { } } - dbConfiguration.prepareDatabase { db in + dbConfiguration.prepareDatabase { [_sqlQueriesMutex] db in db.trace { event in - self.sqlQueries.append(event.expandedDescription) + _sqlQueriesMutex.withLock { + $0.append(event.expandedDescription) + } } #if GRDBCIPHER_USE_ENCRYPTION @@ -113,7 +126,7 @@ class GRDBTestCase: XCTestCase { #endif } - sqlQueries = [] + clearSQLQueries() } override func tearDown() { @@ -121,6 +134,10 @@ class GRDBTestCase: XCTestCase { do { try FileManager.default.removeItem(atPath: dbDirectoryPath) } catch { } } + func clearSQLQueries() { + _sqlQueriesMutex.store([]) + } + func assertNoError(file: StaticString = #file, line: UInt = #line, _ test: () throws -> Void) { do { try test() @@ -218,26 +235,41 @@ extension FetchRequest { } /// A type-erased ValueReducer. -public struct AnyValueReducer: ValueReducer { - private var __fetch: (Database) throws -> Fetched +struct AnyValueReducer: ValueReducer { + private var __fetch: @Sendable (Database) throws -> Fetched private var __value: (Fetched) -> Value? - public init( - fetch: @escaping (Database) throws -> Fetched, + init( + fetch: @escaping @Sendable (Database) throws -> Fetched, value: @escaping (Fetched) -> Value?) { self.__fetch = fetch self.__value = value } - public func _fetch(_ db: Database) throws -> Fetched { - try __fetch(db) + func _makeFetcher() -> AnyValueReducerFetcher { + AnyValueReducerFetcher(fetch: __fetch) } - public func _value(_ fetched: Fetched) -> Value? { + func _value(_ fetched: Fetched) -> Value? { __value(fetched) } } -// Assume this is correct :-/ +/// A type-erased _ValueReducerFetcher. +struct AnyValueReducerFetcher: _ValueReducerFetcher { + private var _fetch: @Sendable (Database) throws -> Fetched + + init(fetch: @escaping @Sendable (Database) throws -> Fetched) { + self._fetch = fetch + } + + func fetch(_ db: Database) throws -> Fetched { + try _fetch(db) + } +} + +#if compiler(<6.1) +// XCTestExpectation is Sendable starting Xcode 16.3 beta. extension XCTestExpectation: @unchecked Sendable { } +#endif diff --git a/Tests/GRDBTests/InflectionsTests.json b/Tests/GRDBTests/InflectionsTests.json index 872132256..98f5c5860 100644 --- a/Tests/GRDBTests/InflectionsTests.json +++ b/Tests/GRDBTests/InflectionsTests.json @@ -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": { diff --git a/Tests/GRDBTests/JSONColumnTests.swift b/Tests/GRDBTests/JSONColumnTests.swift index b73c21128..763eed4ae 100644 --- a/Tests/GRDBTests/JSONColumnTests.swift +++ b/Tests/GRDBTests/JSONColumnTests.swift @@ -5,11 +5,11 @@ 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -28,7 +28,7 @@ final class JSONColumnTests: GRDBTestCase { static let info = JSONColumn(CodingKeys.info) } - static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.info] + static var databaseSelection: [any SQLSelectable] { [Columns.id, Columns.info] } } let dbQueue = try makeDatabaseQueue() @@ -47,11 +47,11 @@ 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON_EXTRACT is not available") } #endif @@ -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 diff --git a/Tests/GRDBTests/JSONExpressionsTests.swift b/Tests/GRDBTests/JSONExpressionsTests.swift index f0b439092..0e9ed40e9 100644 --- a/Tests/GRDBTests/JSONExpressionsTests.swift +++ b/Tests/GRDBTests/JSONExpressionsTests.swift @@ -2,14 +2,17 @@ import XCTest import GRDB final class JSONExpressionsTests: GRDBTestCase { + /// The SQL function used to build JSON expressions + private let jsonFunction = (Database.sqliteLibVersionNumber >= 3045000) ? "JSONB" : "JSON" + func test_Database_json() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -37,14 +40,47 @@ final class JSONExpressionsTests: GRDBTestCase { } } + func test_Database_jsonb() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonb) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonb(#" { "a": [ "test" ] } "#), """ + JSONB(' { "a": [ "test" ] } ') + """) + + try assertEqualSQL(db, player.select(Database.jsonb(nameColumn)), """ + SELECT JSONB("name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonb(infoColumn)), """ + SELECT JSONB("info") FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + func test_asJSON() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -87,12 +123,12 @@ final class JSONExpressionsTests: GRDBTestCase { ]) ]), """ SELECT JSON_ARRAY(\ - JSON('[1, 2, 3]'), \ + \(jsonFunction)('[1, 2, 3]'), \ NULL, \ - JSON("name"), \ - JSON("info"), \ - JSON(ABS("name")), \ - JSON(ABS("info"))\ + \(jsonFunction)("name"), \ + \(jsonFunction)("info"), \ + \(jsonFunction)(ABS("name")), \ + \(jsonFunction)(ABS("info"))\ ) FROM "player" """) } @@ -101,11 +137,11 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonArray() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -144,10 +180,10 @@ final class JSONExpressionsTests: GRDBTestCase { ), """ SELECT JSON_ARRAY(\ "name", \ - JSON("name"), \ - JSON("info"), \ + \(jsonFunction)("name"), \ + \(jsonFunction)("info"), \ JSON_EXTRACT("info", 'address'), \ - JSON(JSON_EXTRACT("info", 'address'))\ + \(jsonFunction)(JSON_EXTRACT("info", 'address'))\ ) FROM "player" """) } @@ -156,7 +192,7 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonArray_from_SQLJSONExpressible() 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 @@ -191,12 +227,12 @@ final class JSONExpressionsTests: GRDBTestCase { ), """ SELECT JSON_ARRAY(\ "name", \ - JSON("name"), \ - JSON("info"), \ + \(jsonFunction)("name"), \ + \(jsonFunction)("info"), \ "info" ->> 'score', \ - JSON("info" ->> 'score'), \ + \(jsonFunction)("info" ->> 'score'), \ JSON_EXTRACT("info", 'address'), \ - JSON(JSON_EXTRACT("info", 'address')), \ + \(jsonFunction)(JSON_EXTRACT("info", 'address')), \ "info" -> 'address', \ "info" -> 'address'\ ) FROM "player" @@ -220,8 +256,8 @@ final class JSONExpressionsTests: GRDBTestCase { ), """ SELECT JSON_ARRAY(\ "p"."name", \ - JSON("p"."name"), \ - JSON("p"."info"), \ + \(jsonFunction)("p"."name"), \ + \(jsonFunction)("p"."info"), \ "p"."info" ->> 'score', \ JSON_EXTRACT("p"."info", 'address'), \ "p"."info" -> 'address'\ @@ -242,8 +278,8 @@ final class JSONExpressionsTests: GRDBTestCase { ), """ SELECT JSON_ARRAY(\ "p"."name", \ - JSON("p"."name"), \ - JSON("p"."info"), \ + \(jsonFunction)("p"."name"), \ + \(jsonFunction)("p"."info"), \ "p"."info" ->> 'score', \ JSON_EXTRACT("p"."info", 'address'), \ "p"."info" -> 'address'\ @@ -264,8 +300,8 @@ final class JSONExpressionsTests: GRDBTestCase { ), """ SELECT JSON_ARRAY(\ "p"."name", \ - JSON("p"."name"), \ - JSON("p"."info"), \ + \(jsonFunction)("p"."name"), \ + \(jsonFunction)("p"."info"), \ "p"."info" ->> 'score', \ JSON_EXTRACT("p"."info", 'address'), \ "p"."info" -> 'address'\ @@ -274,14 +310,186 @@ final class JSONExpressionsTests: GRDBTestCase { } } + func test_Database_jsonbArray() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonbArray(1...4), """ + JSONB_ARRAY(1, 2, 3, 4) + """) + + try assertEqualSQL(db, Database.jsonbArray([1, 2, 3, 4]), """ + JSONB_ARRAY(1, 2, 3, 4) + """) + + try assertEqualSQL(db, Database.jsonbArray([1, 2, "3", 4]), """ + JSONB_ARRAY(1, 2, '3', 4) + """) + + // Note: this JSON(JSON_EXTRACT(...)) is useful, when the extracted value is a string that contains JSON + try assertEqualSQL(db, player + .select( + Database.jsonbArray([ + nameColumn, + nameColumn.asJSON, + infoColumn, + infoColumn.jsonExtract(atPath: "address"), + infoColumn.jsonExtract(atPath: "address").asJSON, + ] as [any SQLExpressible]) + ), """ + SELECT JSONB_ARRAY(\ + "name", \ + JSONB("name"), \ + JSONB("info"), \ + JSON_EXTRACT("info", 'address'), \ + JSONB(JSON_EXTRACT("info", 'address'))\ + ) FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + + func test_Database_jsonbArray_from_SQLJSONExpressible() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + // Note: this JSON(JSON_EXTRACT(...)) is useful, when the extracted value is a string that contains JSON + try assertEqualSQL(db, player + .select( + Database.jsonbArray([ + nameColumn, + nameColumn.asJSON, + infoColumn, + infoColumn["score"], + infoColumn["score"].asJSON, + infoColumn.jsonExtract(atPath: "address"), + infoColumn.jsonExtract(atPath: "address").asJSON, + infoColumn.jsonRepresentation(atPath: "address"), + infoColumn.jsonRepresentation(atPath: "address").asJSON, + ] as [any SQLExpressible]) + ), """ + SELECT JSONB_ARRAY(\ + "name", \ + JSONB("name"), \ + JSONB("info"), \ + "info" ->> 'score', \ + JSONB("info" ->> 'score'), \ + JSON_EXTRACT("info", 'address'), \ + JSONB(JSON_EXTRACT("info", 'address')), \ + "info" -> 'address', \ + "info" -> 'address'\ + ) FROM "player" + """) + + let alias = TableAlias(name: "p") + + try assertEqualSQL(db, player + .aliased(alias) + .select( + alias[ + Database.jsonbArray([ + nameColumn, + nameColumn.asJSON, + infoColumn, + infoColumn["score"], + infoColumn.jsonExtract(atPath: "address"), + infoColumn.jsonRepresentation(atPath: "address"), + ] as [any SQLExpressible]) + ] + ), """ + SELECT JSONB_ARRAY(\ + "p"."name", \ + JSONB("p"."name"), \ + JSONB("p"."info"), \ + "p"."info" ->> 'score', \ + JSON_EXTRACT("p"."info", 'address'), \ + "p"."info" -> 'address'\ + ) FROM "player" "p" + """) + + try assertEqualSQL(db, player + .aliased(alias) + .select( + Database.jsonbArray([ + alias[nameColumn], + alias[nameColumn.asJSON], + alias[infoColumn], + alias[infoColumn["score"]], + alias[infoColumn.jsonExtract(atPath: "address")], + alias[infoColumn.jsonRepresentation(atPath: "address")], + ] as [any SQLExpressible]) + ), """ + SELECT JSONB_ARRAY(\ + "p"."name", \ + JSONB("p"."name"), \ + JSONB("p"."info"), \ + "p"."info" ->> 'score', \ + JSON_EXTRACT("p"."info", 'address'), \ + "p"."info" -> 'address'\ + ) FROM "player" "p" + """) + + try assertEqualSQL(db, player + .aliased(alias) + .select( + Database.jsonbArray([ + alias[nameColumn], + alias[nameColumn].asJSON, + alias[infoColumn], + alias[infoColumn]["score"], + alias[infoColumn].jsonExtract(atPath: "address"), + alias[infoColumn].jsonRepresentation(atPath: "address"), + ] as [any SQLExpressible]) + ), """ + SELECT JSONB_ARRAY(\ + "p"."name", \ + JSONB("p"."name"), \ + JSONB("p"."info"), \ + "p"."info" ->> 'score', \ + JSON_EXTRACT("p"."info", 'address'), \ + "p"."info" -> 'address'\ + ) FROM "player" "p" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + func test_Database_jsonArrayLength() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -312,11 +520,11 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonArrayLength_atPath() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -355,7 +563,7 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonErrorPosition() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER // Prevent SQLCipher failures - guard sqlite3_libversion_number() >= 3042000 else { + guard Database.sqliteLibVersionNumber >= 3042000 else { throw XCTSkip("JSON_ERROR_JSON is not available") } @@ -388,11 +596,11 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonExtract_atPath() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -431,11 +639,11 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonExtract_atPaths() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -463,14 +671,88 @@ final class JSONExpressionsTests: GRDBTestCase { } } + func test_Database_jsonbExtract_atPath() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonbExtract(#"{"a":123}"#, atPath: "$.a"), """ + JSONB_EXTRACT('{"a":123}', '$.a') + """) + + try assertEqualSQL(db, player.select(Database.jsonbExtract(nameColumn, atPath: "$.a")), """ + SELECT JSONB_EXTRACT("name", '$.a') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbExtract(infoColumn, atPath: "$.a")), """ + SELECT JSONB_EXTRACT("info", '$.a') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbExtract(#"{"a":123}"#, atPath: nameColumn)), """ + SELECT JSONB_EXTRACT('{"a":123}', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbExtract(#"{"a":123}"#, atPath: infoColumn)), """ + SELECT JSONB_EXTRACT('{"a":123}', "info") FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + + func test_Database_jsonbExtract_atPaths() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonbExtract(#"{"a":2,"c":[4,5]}"#, atPaths: ["$.c", "$.a"]), """ + JSONB_EXTRACT('{"a":2,"c":[4,5]}', '$.c', '$.a') + """) + + try assertEqualSQL(db, player.select(Database.jsonbExtract(nameColumn, atPaths: ["$.c", "$.a"])), """ + SELECT JSONB_EXTRACT("name", '$.c', '$.a') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbExtract(infoColumn, atPaths: ["$.c", "$.a"])), """ + SELECT JSONB_EXTRACT("info", '$.c', '$.a') FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + func test_Database_jsonInsert() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -489,7 +771,7 @@ final class JSONExpressionsTests: GRDBTestCase { """) try assertEqualSQL(db, Database.jsonInsert("[1,2,3,4]", ["$[#]": #"{"e":5}"#.databaseValue.asJSON]), """ - JSON_INSERT('[1,2,3,4]', '$[#]', JSON('{"e":5}')) + JSON_INSERT('[1,2,3,4]', '$[#]', \(jsonFunction)('{"e":5}')) """) try assertEqualSQL(db, Database.jsonInsert("[1,2,3,4]", ["$[#]": Database.json(#"{"e":5}"#)]), """ @@ -513,19 +795,80 @@ final class JSONExpressionsTests: GRDBTestCase { """) try assertEqualSQL(db, player.select(Database.jsonInsert("[1,2,3,4]", ["$[#]": infoColumn])), """ - SELECT JSON_INSERT('[1,2,3,4]', '$[#]', JSON("info")) FROM "player" + SELECT JSON_INSERT('[1,2,3,4]', '$[#]', \(jsonFunction)("info")) FROM "player" """) } } + func test_Database_jsonbInsert() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonbInsert("[1,2,3,4]", ["$[#]": #"{"e":5}"#]), """ + JSONB_INSERT('[1,2,3,4]', '$[#]', '{"e":5}') + """) + + try assertEqualSQL(db, Database.jsonbInsert("[1,2,3,4]", ["$[#]": #"{"e":5}"#.databaseValue.asJSON]), """ + JSONB_INSERT('[1,2,3,4]', '$[#]', JSONB('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonbInsert("[1,2,3,4]", ["$[#]": Database.json(#"{"e":5}"#)]), """ + JSONB_INSERT('[1,2,3,4]', '$[#]', JSON('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonbInsert("[1,2,3,4]", ["$[#]": Database.jsonb(#"{"e":5}"#)]), """ + JSONB_INSERT('[1,2,3,4]', '$[#]', JSONB('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonbInsert("[1,2,3,4]", ["$[#]": Database.jsonObject(["e": 5])]), """ + JSONB_INSERT('[1,2,3,4]', '$[#]', JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL(db, Database.jsonbInsert("[1,2,3,4]", ["$[#]": Database.jsonbObject(["e": 5])]), """ + JSONB_INSERT('[1,2,3,4]', '$[#]', JSONB_OBJECT('e', 5)) + """) + + try assertEqualSQL(db, player.select(Database.jsonbInsert(nameColumn, ["$[#]": 99])), """ + SELECT JSONB_INSERT("name", '$[#]', 99) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbInsert(infoColumn, ["$[#]": 99])), """ + SELECT JSONB_INSERT("info", '$[#]', 99) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbInsert("[1,2,3,4]", ["$[#]": nameColumn])), """ + SELECT JSONB_INSERT('[1,2,3,4]', '$[#]', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbInsert("[1,2,3,4]", ["$[#]": infoColumn])), """ + SELECT JSONB_INSERT('[1,2,3,4]', '$[#]', JSONB("info")) FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + func test_Database_jsonReplace() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -544,7 +887,7 @@ final class JSONExpressionsTests: GRDBTestCase { """) try assertEqualSQL(db, Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": #"{"e":5}"#.databaseValue.asJSON]), """ - JSON_REPLACE('{"a":2,"c":4}', '$.a', JSON('{"e":5}')) + JSON_REPLACE('{"a":2,"c":4}', '$.a', \(jsonFunction)('{"e":5}')) """) try assertEqualSQL(db, Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": Database.json(#"{"e":5}"#)]), """ @@ -568,19 +911,80 @@ final class JSONExpressionsTests: GRDBTestCase { """) try assertEqualSQL(db, player.select(Database.jsonReplace(#"{"a":2,"c":4}"#, ["$.a": infoColumn])), """ - SELECT JSON_REPLACE('{"a":2,"c":4}', '$.a', JSON("info")) FROM "player" + SELECT JSON_REPLACE('{"a":2,"c":4}', '$.a', \(jsonFunction)("info")) FROM "player" """) } } + func test_Database_jsonbReplace() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonbReplace(#"{"a":2,"c":4}"#, ["$.a": #"{"e":5}"#]), """ + JSONB_REPLACE('{"a":2,"c":4}', '$.a', '{"e":5}') + """) + + try assertEqualSQL(db, Database.jsonbReplace(#"{"a":2,"c":4}"#, ["$.a": #"{"e":5}"#.databaseValue.asJSON]), """ + JSONB_REPLACE('{"a":2,"c":4}', '$.a', JSONB('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonbReplace(#"{"a":2,"c":4}"#, ["$.a": Database.json(#"{"e":5}"#)]), """ + JSONB_REPLACE('{"a":2,"c":4}', '$.a', JSON('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonbReplace(#"{"a":2,"c":4}"#, ["$.a": Database.jsonb(#"{"e":5}"#)]), """ + JSONB_REPLACE('{"a":2,"c":4}', '$.a', JSONB('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonbReplace(#"{"a":2,"c":4}"#, ["$.a": Database.jsonObject(["e": 5])]), """ + JSONB_REPLACE('{"a":2,"c":4}', '$.a', JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL(db, Database.jsonbReplace(#"{"a":2,"c":4}"#, ["$.a": Database.jsonbObject(["e": 5])]), """ + JSONB_REPLACE('{"a":2,"c":4}', '$.a', JSONB_OBJECT('e', 5)) + """) + + try assertEqualSQL(db, player.select(Database.jsonbReplace(nameColumn, ["$.a": 99])), """ + SELECT JSONB_REPLACE("name", '$.a', 99) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbReplace(infoColumn, ["$.a": 99])), """ + SELECT JSONB_REPLACE("info", '$.a', 99) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbReplace(#"{"a":2,"c":4}"#, ["$.a": nameColumn])), """ + SELECT JSONB_REPLACE('{"a":2,"c":4}', '$.a', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbReplace(#"{"a":2,"c":4}"#, ["$.a": infoColumn])), """ + SELECT JSONB_REPLACE('{"a":2,"c":4}', '$.a', JSONB("info")) FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + func test_Database_jsonSet() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -599,7 +1003,7 @@ final class JSONExpressionsTests: GRDBTestCase { """) try assertEqualSQL(db, Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": #"{"e":5}"#.databaseValue.asJSON]), """ - JSON_SET('{"a":2,"c":4}', '$.a', JSON('{"e":5}')) + JSON_SET('{"a":2,"c":4}', '$.a', \(jsonFunction)('{"e":5}')) """) try assertEqualSQL(db, Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": Database.json(#"{"e":5}"#)]), """ @@ -623,19 +1027,80 @@ final class JSONExpressionsTests: GRDBTestCase { """) try assertEqualSQL(db, player.select(Database.jsonSet(#"{"a":2,"c":4}"#, ["$.a": infoColumn])), """ - SELECT JSON_SET('{"a":2,"c":4}', '$.a', JSON("info")) FROM "player" + SELECT JSON_SET('{"a":2,"c":4}', '$.a', \(jsonFunction)("info")) FROM "player" """) } } + func test_Database_jsonbSet() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonbSet(#"{"a":2,"c":4}"#, ["$.a": #"{"e":5}"#]), """ + JSONB_SET('{"a":2,"c":4}', '$.a', '{"e":5}') + """) + + try assertEqualSQL(db, Database.jsonbSet(#"{"a":2,"c":4}"#, ["$.a": #"{"e":5}"#.databaseValue.asJSON]), """ + JSONB_SET('{"a":2,"c":4}', '$.a', JSONB('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonbSet(#"{"a":2,"c":4}"#, ["$.a": Database.json(#"{"e":5}"#)]), """ + JSONB_SET('{"a":2,"c":4}', '$.a', JSON('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonbSet(#"{"a":2,"c":4}"#, ["$.a": Database.jsonb(#"{"e":5}"#)]), """ + JSONB_SET('{"a":2,"c":4}', '$.a', JSONB('{"e":5}')) + """) + + try assertEqualSQL(db, Database.jsonbSet(#"{"a":2,"c":4}"#, ["$.a": Database.jsonObject(["e": 5])]), """ + JSONB_SET('{"a":2,"c":4}', '$.a', JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL(db, Database.jsonbSet(#"{"a":2,"c":4}"#, ["$.a": Database.jsonbObject(["e": 5])]), """ + JSONB_SET('{"a":2,"c":4}', '$.a', JSONB_OBJECT('e', 5)) + """) + + try assertEqualSQL(db, player.select(Database.jsonbSet(nameColumn, ["$.a": 99])), """ + SELECT JSONB_SET("name", '$.a', 99) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbSet(infoColumn, ["$.a": 99])), """ + SELECT JSONB_SET("info", '$.a', 99) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbSet(#"{"a":2,"c":4}"#, ["$.a": nameColumn])), """ + SELECT JSONB_SET('{"a":2,"c":4}', '$.a', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbSet(#"{"a":2,"c":4}"#, ["$.a": infoColumn])), """ + SELECT JSONB_SET('{"a":2,"c":4}', '$.a', JSONB("info")) FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + func test_Database_jsonObject_from_Dictionary() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -670,7 +1135,7 @@ final class JSONExpressionsTests: GRDBTestCase { Database.jsonObject([ "c": #"{"e":5}"#.databaseValue.asJSON, ] as [String: any SQLExpressible]), """ - JSON_OBJECT('c', JSON('{"e":5}')) + JSON_OBJECT('c', \(jsonFunction)('{"e":5}')) """) try assertEqualSQL( @@ -706,7 +1171,7 @@ final class JSONExpressionsTests: GRDBTestCase { "c": infoColumn, ]) ), """ - SELECT JSON_OBJECT('c', JSON("info")) FROM "player" + SELECT JSON_OBJECT('c', \(jsonFunction)("info")) FROM "player" """) try assertEqualSQL( @@ -734,11 +1199,11 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonObject_from_Array() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -769,7 +1234,7 @@ final class JSONExpressionsTests: GRDBTestCase { (key: "a", value: 2), (key: "c", value: #"{"e":5}"#.databaseValue.asJSON), ] as [(key: String, value: any SQLExpressible)]), """ - JSON_OBJECT('a', 2, 'c', JSON('{"e":5}')) + JSON_OBJECT('a', 2, 'c', \(jsonFunction)('{"e":5}')) """) try assertEqualSQL( @@ -798,7 +1263,7 @@ final class JSONExpressionsTests: GRDBTestCase { (key: "c", value: infoColumn), ] as [(key: String, value: any SQLExpressible)]) ), """ - SELECT JSON_OBJECT('a', "name", 'c', JSON("info")) FROM "player" + SELECT JSON_OBJECT('a', "name", 'c', \(jsonFunction)("info")) FROM "player" """) try assertEqualSQL( @@ -817,11 +1282,11 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonObject_from_KeyValuePairs() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -852,7 +1317,7 @@ final class JSONExpressionsTests: GRDBTestCase { "a": 2, "c": #"{"e":5}"#.databaseValue.asJSON, ] as KeyValuePairs), """ - JSON_OBJECT('a', 2, 'c', JSON('{"e":5}')) + JSON_OBJECT('a', 2, 'c', \(jsonFunction)('{"e":5}')) """) try assertEqualSQL( @@ -881,7 +1346,7 @@ final class JSONExpressionsTests: GRDBTestCase { "c": infoColumn, ] as KeyValuePairs) ), """ - SELECT JSON_OBJECT('a', "name", 'c', JSON("info")) FROM "player" + SELECT JSON_OBJECT('a', "name", 'c', \(jsonFunction)("info")) FROM "player" """) try assertEqualSQL( @@ -897,14 +1362,371 @@ final class JSONExpressionsTests: GRDBTestCase { } } + func test_Database_jsonbObject_from_Dictionary() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL( + db, + Database.jsonbObject([ + "a": 2, + ] as [String: Int]), """ + JSONB_OBJECT('a', 2) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + "c": #"{"e":5}"#, + ] as [String: any SQLExpressible]), """ + JSONB_OBJECT('c', '{"e":5}') + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + "c": #"{"e":5}"#.databaseValue.asJSON, + ] as [String: any SQLExpressible]), """ + JSONB_OBJECT('c', JSONB('{"e":5}')) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + "c": Database.jsonObject(["e": 5]), + ]), """ + JSONB_OBJECT('c', JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + "c": Database.jsonbObject(["e": 5]), + ]), """ + JSONB_OBJECT('c', JSONB_OBJECT('e', 5)) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + "c": Database.json(#"{"e":5}"#), + ]), """ + JSONB_OBJECT('c', JSON('{"e":5}')) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + "c": Database.jsonb(#"{"e":5}"#), + ]), """ + JSONB_OBJECT('c', JSONB('{"e":5}')) + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonbObject([ + "a": nameColumn, + ]) + ), """ + SELECT JSONB_OBJECT('a', "name") FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonbObject([ + "c": infoColumn, + ]) + ), """ + SELECT JSONB_OBJECT('c', JSONB("info")) FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonbObject([ + "a": Database.json(nameColumn), + ]) + ), """ + SELECT JSONB_OBJECT('a', JSON("name")) FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonbObject([ + "a": Database.jsonb(nameColumn), + ]) + ), """ + SELECT JSONB_OBJECT('a', JSONB("name")) FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonbObject([ + "c": Database.json(infoColumn), + ]) + ), """ + SELECT JSONB_OBJECT('c', JSON("info")) FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonbObject([ + "c": Database.jsonb(infoColumn), + ]) + ), """ + SELECT JSONB_OBJECT('c', JSONB("info")) FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + + func test_Database_jsonbObject_from_Array() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + // Ordered Array + + try assertEqualSQL( + db, + Database.jsonbObject([ + (key: "a", value: 2), + (key: "c", value: #"{"e":5}"#), + ] as [(key: String, value: any SQLExpressible)]), """ + JSONB_OBJECT('a', 2, 'c', '{"e":5}') + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + (key: "a", value: 2), + (key: "c", value: #"{"e":5}"#.databaseValue.asJSON), + ] as [(key: String, value: any SQLExpressible)]), """ + JSONB_OBJECT('a', 2, 'c', JSONB('{"e":5}')) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + (key: "a", value: 2), + (key: "c", value: Database.jsonObject(["e": 5])), + ] as [(key: String, value: any SQLExpressible)]), """ + JSONB_OBJECT('a', 2, 'c', JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + (key: "a", value: 2), + (key: "c", value: Database.jsonbObject(["e": 5])), + ] as [(key: String, value: any SQLExpressible)]), """ + JSONB_OBJECT('a', 2, 'c', JSONB_OBJECT('e', 5)) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + (key: "a", value: 2), + (key: "c", value: Database.json(#"{"e":5}"#)), + ] as [(key: String, value: any SQLExpressible)]), """ + JSONB_OBJECT('a', 2, 'c', JSON('{"e":5}')) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + (key: "a", value: 2), + (key: "c", value: Database.jsonb(#"{"e":5}"#)), + ] as [(key: String, value: any SQLExpressible)]), """ + JSONB_OBJECT('a', 2, 'c', JSONB('{"e":5}')) + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonbObject([ + (key: "a", value: nameColumn), + (key: "c", value: infoColumn), + ] as [(key: String, value: any SQLExpressible)]) + ), """ + SELECT JSONB_OBJECT('a', "name", 'c', JSONB("info")) FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonbObject([ + (key: "a", value: Database.json(nameColumn)), + (key: "c", value: Database.json(infoColumn)), + ] as [(key: String, value: SQLExpression)]) + ), """ + SELECT JSONB_OBJECT('a', JSON("name"), 'c', JSON("info")) FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonbObject([ + (key: "a", value: Database.jsonb(nameColumn)), + (key: "c", value: Database.jsonb(infoColumn)), + ] as [(key: String, value: SQLExpression)]) + ), """ + SELECT JSONB_OBJECT('a', JSONB("name"), 'c', JSONB("info")) FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + + func test_Database_jsonbObject_from_KeyValuePairs() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + // Ordered Array + + try assertEqualSQL( + db, + Database.jsonbObject([ + "a": 2, + "c": #"{"e":5}"#, + ] as KeyValuePairs), """ + JSONB_OBJECT('a', 2, 'c', '{"e":5}') + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + "a": 2, + "c": #"{"e":5}"#.databaseValue.asJSON, + ] as KeyValuePairs), """ + JSONB_OBJECT('a', 2, 'c', JSONB('{"e":5}')) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + "a": 2, + "c": Database.jsonObject(["e": 5]), + ] as KeyValuePairs), """ + JSONB_OBJECT('a', 2, 'c', JSON_OBJECT('e', 5)) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + "a": 2, + "c": Database.jsonbObject(["e": 5]), + ] as KeyValuePairs), """ + JSONB_OBJECT('a', 2, 'c', JSONB_OBJECT('e', 5)) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + "a": 2, + "c": Database.json(#"{"e":5}"#), + ] as KeyValuePairs), """ + JSONB_OBJECT('a', 2, 'c', JSON('{"e":5}')) + """) + + try assertEqualSQL( + db, + Database.jsonbObject([ + "a": 2, + "c": Database.jsonb(#"{"e":5}"#), + ] as KeyValuePairs), """ + JSONB_OBJECT('a', 2, 'c', JSONB('{"e":5}')) + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonbObject([ + "a": nameColumn, + "c": infoColumn, + ] as KeyValuePairs) + ), """ + SELECT JSONB_OBJECT('a', "name", 'c', JSONB("info")) FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonbObject([ + "a": Database.json(nameColumn), + "c": Database.json(infoColumn), + ] as KeyValuePairs) + ), """ + SELECT JSONB_OBJECT('a', JSON("name"), 'c', JSON("info")) FROM "player" + """) + + try assertEqualSQL( + db, + player.select( + Database.jsonbObject([ + "a": Database.jsonb(nameColumn), + "c": Database.jsonb(infoColumn), + ] as KeyValuePairs) + ), """ + SELECT JSONB_OBJECT('a', JSONB("name"), 'c', JSONB("info")) FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + func test_Database_jsonPatch() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -940,14 +1762,55 @@ final class JSONExpressionsTests: GRDBTestCase { } } + func test_Database_jsonbPatch() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonbPatch(#"{"a":1,"b":2}"#, with: #"{"c":3,"d":4}"#), """ + JSONB_PATCH('{"a":1,"b":2}', '{"c":3,"d":4}') + """) + + try assertEqualSQL(db, player.select(Database.jsonbPatch(#"{"a":1,"b":2}"#, with: nameColumn)), """ + SELECT JSONB_PATCH('{"a":1,"b":2}', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbPatch(#"{"a":1,"b":2}"#, with: infoColumn)), """ + SELECT JSONB_PATCH('{"a":1,"b":2}', "info") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbPatch(nameColumn, with: #"{"c":3,"d":4}"#)), """ + SELECT JSONB_PATCH("name", '{"c":3,"d":4}') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbPatch(infoColumn, with: #"{"c":3,"d":4}"#)), """ + SELECT JSONB_PATCH("info", '{"c":3,"d":4}') FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + func test_Database_jsonRemove_atPath() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -986,11 +1849,11 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonRemove_atPaths() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -1018,14 +1881,88 @@ final class JSONExpressionsTests: GRDBTestCase { } } + func test_Database_jsonbRemove_atPath() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonbRemove("[0,1,2,3,4]", atPath: "$[2]"), """ + JSONB_REMOVE('[0,1,2,3,4]', '$[2]') + """) + + try assertEqualSQL(db, player.select(Database.jsonbRemove(nameColumn, atPath: "$[2]")), """ + SELECT JSONB_REMOVE("name", '$[2]') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbRemove("[0,1,2,3,4]", atPath: nameColumn)), """ + SELECT JSONB_REMOVE('[0,1,2,3,4]', "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbRemove(infoColumn, atPath: "$[2]")), """ + SELECT JSONB_REMOVE("info", '$[2]') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbRemove("[0,1,2,3,4]", atPath: infoColumn)), """ + SELECT JSONB_REMOVE('[0,1,2,3,4]', "info") FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + + func test_Database_jsonbRemove_atPaths() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, Database.jsonbRemove("[0,1,2,3,4]", atPaths: ["$[2]", "$[0]"]), """ + JSONB_REMOVE('[0,1,2,3,4]', '$[2]', '$[0]') + """) + + try assertEqualSQL(db, player.select(Database.jsonbRemove(nameColumn, atPaths: ["$[2]", "$[0]"])), """ + SELECT JSONB_REMOVE("name", '$[2]', '$[0]') FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbRemove(infoColumn, atPaths: ["$[2]", "$[0]"])), """ + SELECT JSONB_REMOVE("info", '$[2]', '$[0]') FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + func test_Database_jsonType() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -1056,11 +1993,11 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonType_atPath() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -1099,11 +2036,11 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonIsValid() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -1131,14 +2068,48 @@ final class JSONExpressionsTests: GRDBTestCase { } } + func test_Database_jsonIsValid_options() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSON_VALID options are not available") + } + + try makeDatabaseQueue().inDatabase { db in + try assertEqualSQL(db, Database.jsonIsValid(#"{"x":35""#, options: .json), """ + JSON_VALID('{"x":35"', 1) + """) + + try assertEqualSQL(db, Database.jsonIsValid(#"{"x":35""#, options: .json5), """ + JSON_VALID('{"x":35"', 2) + """) + + try assertEqualSQL(db, Database.jsonIsValid(#"{"x":35""#, options: .probablyJSONB), """ + JSON_VALID('{"x":35"', 4) + """) + + try assertEqualSQL(db, Database.jsonIsValid(#"{"x":35""#, options: .jsonb), """ + JSON_VALID('{"x":35"', 8) + """) + + try assertEqualSQL(db, Database.jsonIsValid(#"{"x":35""#, options: [.json, .jsonb]), """ + JSON_VALID('{"x":35"', 9) + """) + + } +#else + throw XCTSkip("JSON_VALID options are not available") +#endif + } + func test_Database_jsonQuote() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -1157,7 +2128,7 @@ final class JSONExpressionsTests: GRDBTestCase { """) try assertEqualSQL(db, Database.jsonQuote(#"{"e":5}"#.databaseValue.asJSON), """ - JSON_QUOTE(JSON('{"e":5}')) + JSON_QUOTE(\(jsonFunction)('{"e":5}')) """) try assertEqualSQL(db, Database.jsonQuote(Database.json(#"{"e":5}"#)), """ @@ -1173,7 +2144,7 @@ final class JSONExpressionsTests: GRDBTestCase { """) try assertEqualSQL(db, player.select(Database.jsonQuote(infoColumn)), """ - SELECT JSON_QUOTE(JSON("info")) FROM "player" + SELECT JSON_QUOTE(\(jsonFunction)("info")) FROM "player" """) } } @@ -1181,11 +2152,11 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonGroupArray() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -1204,19 +2175,73 @@ final class JSONExpressionsTests: GRDBTestCase { """) try assertEqualSQL(db, player.select(Database.jsonGroupArray(infoColumn)), """ - SELECT JSON_GROUP_ARRAY(JSON("info")) FROM "player" + SELECT JSON_GROUP_ARRAY(\(jsonFunction)("info")) FROM "player" """) } } + func test_Database_jsonGroupArray_from_JSON() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3038000 else { + throw XCTSkip("JSON support is not available") + } +#else + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { + throw XCTSkip("JSON support is not available") + } +#endif + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + try db.execute(sql: """ + INSERT INTO player (info) VALUES ('{"foo": "bar"}') + """) + let player = Table("player") + let infoColumn = JSONColumn("info") + let request = player.select(Database.jsonGroupArray(infoColumn)) + let json = try String.fetchOne(db, request) + XCTAssertEqual(json, #"[{"foo":"bar"}]"#) + } + } + + func test_Database_jsonGroupArray_from_JSONB() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + try db.execute(sql: """ + INSERT INTO player (info) VALUES (JSONB('{"foo": "bar"}')) + """) + let player = Table("player") + let infoColumn = JSONColumn("info") + let request = player.select(Database.jsonGroupArray(infoColumn)) + let json = try String.fetchOne(db, request) + XCTAssertEqual(json, #"[{"foo":"bar"}]"#) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + func test_Database_jsonGroupArray_filter() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -1235,15 +2260,15 @@ final class JSONExpressionsTests: GRDBTestCase { """) try assertEqualSQL(db, player.select(Database.jsonGroupArray(infoColumn, filter: length(nameColumn) > 0)), """ - SELECT JSON_GROUP_ARRAY(JSON("info")) FILTER (WHERE LENGTH("name") > 0) FROM "player" + SELECT JSON_GROUP_ARRAY(\(jsonFunction)("info")) FILTER (WHERE LENGTH("name") > 0) FROM "player" """) } } -#if GRDBCUSTOMSQLITE || GRDBCIPHER func test_Database_jsonGroupArray_order() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER // Prevent SQLCipher failures - guard sqlite3_libversion_number() >= 3044000 else { + guard Database.sqliteLibVersionNumber >= 3044000 else { throw XCTSkip("JSON support is not available") } @@ -1261,28 +2286,125 @@ final class JSONExpressionsTests: GRDBTestCase { """) try assertEqualSQL(db, player.select(Database.jsonGroupArray(infoColumn, orderBy: nameColumn.desc)), """ - SELECT JSON_GROUP_ARRAY(JSON("info") ORDER BY "name" DESC) FROM "player" + SELECT JSON_GROUP_ARRAY(\(jsonFunction)("info") ORDER BY "name" DESC) FROM "player" """) - + try assertEqualSQL(db, player.select(Database.jsonGroupArray(nameColumn, orderBy: nameColumn, filter: length(nameColumn) > 0)), """ SELECT JSON_GROUP_ARRAY("name" ORDER BY "name") FILTER (WHERE LENGTH("name") > 0) FROM "player" """) try assertEqualSQL(db, player.select(Database.jsonGroupArray(infoColumn, orderBy: nameColumn.desc, filter: length(nameColumn) > 0)), """ - SELECT JSON_GROUP_ARRAY(JSON("info") ORDER BY "name" DESC) FILTER (WHERE LENGTH("name") > 0) FROM "player" + SELECT JSON_GROUP_ARRAY(\(jsonFunction)("info") ORDER BY "name" DESC) FILTER (WHERE LENGTH("name") > 0) FROM "player" """) } - } +#else + throw XCTSkip("JSON_GROUP_ARRAY(ORDER) is not available") #endif + } + + func test_Database_jsonbGroupArray() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, player.select(Database.jsonbGroupArray(nameColumn)), """ + SELECT JSONB_GROUP_ARRAY("name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbGroupArray(infoColumn)), """ + SELECT JSONB_GROUP_ARRAY(JSONB("info")) FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + + func test_Database_jsonbGroupArray_filter() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, player.select(Database.jsonbGroupArray(nameColumn, filter: length(nameColumn) > 0)), """ + SELECT JSONB_GROUP_ARRAY("name") FILTER (WHERE LENGTH("name") > 0) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbGroupArray(infoColumn, filter: length(nameColumn) > 0)), """ + SELECT JSONB_GROUP_ARRAY(JSONB("info")) FILTER (WHERE LENGTH("name") > 0) FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + + func test_Database_jsonbGroupArray_order() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("name", .text) + t.column("info", .jsonText) + } + let player = Table("player") + let nameColumn = Column("name") + let infoColumn = JSONColumn("info") + + try assertEqualSQL(db, player.select(Database.jsonbGroupArray(nameColumn, orderBy: nameColumn)), """ + SELECT JSONB_GROUP_ARRAY("name" ORDER BY "name") FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbGroupArray(infoColumn, orderBy: nameColumn.desc)), """ + SELECT JSONB_GROUP_ARRAY(JSONB("info") ORDER BY "name" DESC) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbGroupArray(nameColumn, orderBy: nameColumn, filter: length(nameColumn) > 0)), """ + SELECT JSONB_GROUP_ARRAY("name" ORDER BY "name") FILTER (WHERE LENGTH("name") > 0) FROM "player" + """) + + try assertEqualSQL(db, player.select(Database.jsonbGroupArray(infoColumn, orderBy: nameColumn.desc, filter: length(nameColumn) > 0)), """ + SELECT JSONB_GROUP_ARRAY(JSONB("info") ORDER BY "name" DESC) FILTER (WHERE LENGTH("name") > 0) FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } func test_Database_jsonGroupObject() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -1297,7 +2419,7 @@ final class JSONExpressionsTests: GRDBTestCase { let valueColumn = JSONColumn("value") try assertEqualSQL(db, player.select(Database.jsonGroupObject(key: keyColumn, value: valueColumn)), """ - SELECT JSON_GROUP_OBJECT("key", JSON("value")) FROM "player" + SELECT JSON_GROUP_OBJECT("key", \(jsonFunction)("value")) FROM "player" """) } } @@ -1305,11 +2427,11 @@ final class JSONExpressionsTests: GRDBTestCase { func test_Database_jsonGroupObject_filter() 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 - guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { + guard #available(iOS 16, tvOS 17, watchOS 9, *) else { throw XCTSkip("JSON support is not available") } #endif @@ -1324,15 +2446,65 @@ final class JSONExpressionsTests: GRDBTestCase { let valueColumn = JSONColumn("value") try assertEqualSQL(db, player.select(Database.jsonGroupObject(key: keyColumn, value: valueColumn, filter: length(valueColumn) > 0)), """ - SELECT JSON_GROUP_OBJECT("key", JSON("value")) FILTER (WHERE LENGTH("value") > 0) FROM "player" + SELECT JSON_GROUP_OBJECT("key", \(jsonFunction)("value")) FILTER (WHERE LENGTH("value") > 0) FROM "player" """) } } - func test_index_and_generated_columns() throws { + func test_Database_jsonbGroupObject() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER // Prevent SQLCipher failures - guard sqlite3_libversion_number() >= 3038000 else { + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("key", .text) + t.column("value", .jsonText) + } + let player = Table("player") + let keyColumn = Column("key") + let valueColumn = JSONColumn("value") + + try assertEqualSQL(db, player.select(Database.jsonbGroupObject(key: keyColumn, value: valueColumn)), """ + SELECT JSONB_GROUP_OBJECT("key", \(jsonFunction)("value")) FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + + func test_Database_jsonbGroupObject_filter() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.column("key", .text) + t.column("value", .jsonText) + } + let player = Table("player") + let keyColumn = Column("key") + let valueColumn = JSONColumn("value") + + try assertEqualSQL(db, player.select(Database.jsonbGroupObject(key: keyColumn, value: valueColumn, filter: length(valueColumn) > 0)), """ + SELECT JSONB_GROUP_OBJECT("key", \(jsonFunction)("value")) FILTER (WHERE LENGTH("value") > 0) FROM "player" + """) + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + + func test_JSON_index_and_generated_columns() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3038000 else { throw XCTSkip("JSON support is not available") } #else @@ -1389,15 +2561,72 @@ final class JSONExpressionsTests: GRDBTestCase { } } + func test_JSONB_index_and_generated_columns() throws { +#if GRDBCUSTOMSQLITE || GRDBCIPHER + // Prevent SQLCipher failures + guard Database.sqliteLibVersionNumber >= 3045000 else { + throw XCTSkip("JSONB is not available") + } + + try makeDatabaseQueue().inDatabase { db in + try db.create(table: "player") { t in + t.primaryKey("id", .integer) + t.column("address", .jsonb) + t.column("country", .text) + .generatedAs(JSONColumn("address").jsonExtract(atPath: "$.country")) + .indexed() + } + + XCTAssertEqual(Array(sqlQueries.suffix(2)), [ + """ + CREATE TABLE "player" (\ + "id" INTEGER PRIMARY KEY, \ + "address" BLOB, \ + "country" TEXT GENERATED ALWAYS AS (JSON_EXTRACT("address", '$.country')) VIRTUAL\ + ) + """, + """ + CREATE INDEX "player_on_country" ON "player"("country") + """, + ]) + + try db.create(index: "player_on_address", on: "player", expressions: [ + JSONColumn("address").jsonExtract(atPath: "$.country"), + JSONColumn("address").jsonExtract(atPath: "$.city"), + JSONColumn("address").jsonExtract(atPath: "$.street"), + ]) + + XCTAssertEqual(lastSQLQuery, """ + CREATE INDEX "player_on_address" ON "player"(\ + JSON_EXTRACT("address", '$.country'), \ + JSON_EXTRACT("address", '$.city'), \ + JSON_EXTRACT("address", '$.street')\ + ) + """) + + try db.execute(literal: """ + INSERT INTO player VALUES ( + NULL, + JSONB('{"street": "Rue de Belleville", "city": "Paris", "country": "France"}') + ) + """) + + try XCTAssertEqual(String.fetchOne(db, sql: "SELECT country FROM player"), "France") + } +#else + throw XCTSkip("JSONB is not available") +#endif + } + // TODO: Enable when those apis are ready. // func test_ColumnAssignment() 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 -// guard #available(iOS 16, macOS 10.15, tvOS 17, watchOS 9, *) else { +// guard #available(iOS 16, tvOS 17, watchOS 9, *) else { // throw XCTSkip("JSON support is not available") // } // #endif diff --git a/Tests/GRDBTests/JoinSupportTests.swift b/Tests/GRDBTests/JoinSupportTests.swift index b2ae7eeea..81ec2c3ab 100644 --- a/Tests/GRDBTests/JoinSupportTests.swift +++ b/Tests/GRDBTests/JoinSupportTests.swift @@ -50,7 +50,7 @@ private struct T2: Codable, FetchableRecord, TableRecord { private struct T3: Codable, FetchableRecord, TableRecord { static let databaseTableName = "t3" - static let databaseSelection: [any SQLSelectable] = [Column("t1id"), Column("name")] + static var databaseSelection: [any SQLSelectable] { [Column("t1id"), Column("name")] } var t1id: Int64 var name: String } @@ -92,7 +92,6 @@ private struct FlatModel: FetchableRecord { self.t5count = row.scopes[Scopes.suffix]!["t5count"] } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) static func modernAll() -> some FetchRequest { all() } @@ -138,7 +137,6 @@ private struct CodableFlatModel: FetchableRecord, Codable { var t3: T3? var t5count: Int - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) static func modernAll() -> some FetchRequest { all() } @@ -186,7 +184,6 @@ private struct CodableNestedModel: FetchableRecord, Codable { var t3: T3? var t5count: Int - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) static func modernAll() -> some FetchRequest { all() } diff --git a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift index f530149f8..e3a348503 100644 --- a/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordChangesTests.swift @@ -319,14 +319,14 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { try record.insert(db) do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { _ in } XCTAssertFalse(modified) XCTAssert(sqlQueries.isEmpty) } do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { $0.firstName = "Arthur" } @@ -335,7 +335,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { $0.firstName = nil } @@ -346,7 +346,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { $0.firstName = "Bob" $0.lastName = "Johnson" @@ -391,14 +391,14 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { try record.insert(db) do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { _ in } XCTAssertFalse(modified) XCTAssert(sqlQueries.isEmpty) } do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { $0.firstName = "Arthur" } @@ -407,7 +407,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { $0.firstName = nil } @@ -418,7 +418,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { $0.firstName = "Bob" $0.lastName = "Johnson" @@ -457,14 +457,14 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { try record.insert(db) do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { _ in } XCTAssertFalse(modified) XCTAssert(sqlQueries.isEmpty) } do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { $0.firstName = "Arthur" } @@ -473,7 +473,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { $0.firstName = nil } @@ -484,7 +484,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { $0.firstName = "Bob" $0.lastName = "Johnson" @@ -519,14 +519,14 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { try record.insert(db) do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { _ in } XCTAssertFalse(modified) XCTAssert(sqlQueries.isEmpty) } do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { $0.firstName = "Arthur" } @@ -535,7 +535,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { $0.firstName = nil } @@ -546,7 +546,7 @@ class MutablePersistableRecordChangesTests: GRDBTestCase { } do { - sqlQueries = [] + clearSQLQueries() let modified = try record.updateChanges(db) { $0.firstName = "Bob" $0.lastName = "Johnson" diff --git a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift index 339a4a497..93552bcde 100644 --- a/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordEncodableTests.swift @@ -746,9 +746,12 @@ extension MutablePersistableRecordEncodableTests { case nestedKeyed, nestedSingle, nestedUnkeyed, key, context } - static let databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [ - testKeyRoot: "GRDB root", - testKeyNested: "GRDB nested"] + static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { + [ + testKeyRoot: "GRDB root", + testKeyNested: "GRDB nested", + ] + } static func databaseJSONEncoder(for column: String) -> JSONEncoder { let encoder = JSONEncoder() @@ -779,7 +782,7 @@ extension MutablePersistableRecordEncodableTests { let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys, .prettyPrinted] - let json = try String(data: encoder.encode(record), encoding: .utf8)! + let json = try String(decoding: encoder.encode(record), as: UTF8.self) XCTAssertEqual(json, """ { "nestedKeyed" : { @@ -805,7 +808,7 @@ extension MutablePersistableRecordEncodableTests { let encoder = JSONEncoder() encoder.userInfo = [testKeyRoot: "root", testKeyNested: "nested"] encoder.outputFormatting = [.sortedKeys, .prettyPrinted] - let json = try String(data: encoder.encode(record), encoding: .utf8) + let json = try String(decoding: encoder.encode(record), as: UTF8.self) XCTAssertEqual(json, """ { "context" : "root", @@ -905,7 +908,9 @@ extension MutablePersistableRecordEncodableTests { struct StructWithNestedType : PersistableRecord, FetchableRecord, Codable { static let databaseTableName = "t1" - static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] = [CodingUserInfoKey.testKey: "correct"] + static var databaseEncodingUserInfo: [CodingUserInfoKey: Any] { + [CodingUserInfoKey.testKey: "correct"] + } let nested: NestedStruct? } diff --git a/Tests/GRDBTests/MutablePersistableRecordTests.swift b/Tests/GRDBTests/MutablePersistableRecordTests.swift index 18a15c1ee..a35fb7833 100644 --- a/Tests/GRDBTests/MutablePersistableRecordTests.swift +++ b/Tests/GRDBTests/MutablePersistableRecordTests.swift @@ -172,6 +172,8 @@ private struct PartialPlayer: Codable, MutablePersistableRecord, FetchableRecord case id, name } + typealias Columns = FullPlayer.Columns + mutating func willInsert(_ db: Database) throws { callbacks.willInsertCount += 1 } @@ -240,6 +242,12 @@ private struct FullPlayer: Codable, MutablePersistableRecord, FetchableRecord { case id, name, score } + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + static let score = Column(CodingKeys.score) + } + let callbacks = Callbacks() mutating func willInsert(_ db: Database) throws { @@ -1249,7 +1257,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 @@ -1261,7 +1269,7 @@ extension MutablePersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let player = FullPlayer(id: nil, name: "Arthur", score: 1000) - let insertedPlayer = try XCTUnwrap(player.insertAndFetch(db)) + let insertedPlayer = try player.insertAndFetch(db) XCTAssertEqual(insertedPlayer.id, 1) XCTAssertEqual(insertedPlayer.name, "Arthur") XCTAssertEqual(insertedPlayer.score, 1000) @@ -1270,7 +1278,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 @@ -1282,9 +1290,9 @@ extension MutablePersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() var partialPlayer = PartialPlayer(name: "Arthur") - let fullPlayer = try XCTUnwrap(partialPlayer.insertAndFetch(db, as: FullPlayer.self)) + let fullPlayer = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) XCTAssert(sqlQueries.contains(""" INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING * @@ -1320,7 +1328,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 @@ -1332,7 +1340,7 @@ extension MutablePersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() var partialPlayer = PartialPlayer(name: "Arthur") let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { (statement: Statement) in try Int.fetchOne(statement)! @@ -1368,7 +1376,7 @@ extension MutablePersistableRecordTests { do { // Test onConflict: .ignore - sqlQueries.removeAll() + clearSQLQueries() var player = FullPlayer(id: 1, name: "Barbara", score: 100) try XCTAssertTrue(player.exists(db)) let score = try player.insertAndFetch(db, onConflict: .ignore, selection: [Column("score")]) { (statement: Statement) in @@ -1404,6 +1412,97 @@ extension MutablePersistableRecordTests { } } } + + func test_insertAndFetch_fetch_select() 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() + var partialPlayer = PartialPlayer(name: "Arthur") + let score = try partialPlayer.insertAndFetch(db) { (statement: Statement) in + try Int.fetchOne(statement)! + } select: { + [$0.score] + } + + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(partialPlayer.id, 1) + XCTAssertEqual(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 { + // Test onConflict: .ignore + clearSQLQueries() + var player = FullPlayer(id: 1, name: "Barbara", score: 100) + try XCTAssertTrue(player.exists(db)) + let score = try player.insertAndFetch(db, onConflict: .ignore) { (statement: Statement) in + try Int.fetchOne(statement) + } select: { + [$0.score] + } + + XCTAssert(sqlQueries.contains(""" + INSERT OR IGNORE INTO "player" ("id", "name", "score") VALUES (1,'Barbara',100) RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(player.id, 1) + XCTAssertNil(score) + + XCTAssertEqual(player.callbacks.willInsertCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundInsertExitCount, 1) + XCTAssertEqual(player.callbacks.didInsertCount, 1) + + XCTAssertEqual(player.callbacks.willUpdateCount, 0) + XCTAssertEqual(player.callbacks.aroundUpdateEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundUpdateExitCount, 0) + XCTAssertEqual(player.callbacks.didUpdateCount, 0) + + XCTAssertEqual(player.callbacks.willSaveCount, 1) + XCTAssertEqual(player.callbacks.aroundSaveEnterCount, 1) + XCTAssertEqual(player.callbacks.aroundSaveExitCount, 1) + XCTAssertEqual(player.callbacks.didSaveCount, 1) + + XCTAssertEqual(player.callbacks.willDeleteCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteEnterCount, 0) + XCTAssertEqual(player.callbacks.aroundDeleteExitCount, 0) + XCTAssertEqual(player.callbacks.didDeleteCount, 0) + } + } + } } // MARK: - Save and Fetch @@ -1411,7 +1510,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 @@ -1423,7 +1522,7 @@ extension MutablePersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let player = FullPlayer(id: nil, name: "Arthur", score: 1000) - let savedPlayer = try XCTUnwrap(player.saveAndFetch(db)) + let savedPlayer = try player.saveAndFetch(db) XCTAssertEqual(savedPlayer.id, 1) XCTAssertEqual(savedPlayer.name, "Arthur") XCTAssertEqual(savedPlayer.score, 1000) @@ -1432,7 +1531,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 @@ -1444,9 +1543,9 @@ extension MutablePersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() var partialPlayer = PartialPlayer(name: "Arthur") - let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + let fullPlayer = try partialPlayer.saveAndFetch(db, as: FullPlayer.self) XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") }) XCTAssert(sqlQueries.contains(""" @@ -1482,8 +1581,8 @@ extension MutablePersistableRecordTests { do { var partialPlayer = PartialPlayer(id: 1, name: "Arthur") try partialPlayer.delete(db) - sqlQueries.removeAll() - let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + clearSQLQueries() + let fullPlayer = try partialPlayer.saveAndFetch(db, as: FullPlayer.self) XCTAssert(sqlQueries.contains(""" UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING * @@ -1519,9 +1618,9 @@ extension MutablePersistableRecordTests { } do { - sqlQueries.removeAll() + clearSQLQueries() var partialPlayer = PartialPlayer(id: 1, name: "Arthur") - let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + let fullPlayer = try partialPlayer.saveAndFetch(db, as: FullPlayer.self) XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") }) XCTAssert(sqlQueries.contains(""" @@ -1558,7 +1657,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 @@ -1570,7 +1669,7 @@ extension MutablePersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() var partialPlayer = PartialPlayer(name: "Arthur") let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in try Int.fetchOne(statement) @@ -1608,7 +1707,7 @@ extension MutablePersistableRecordTests { do { var partialPlayer = PartialPlayer(id: 1, name: "Arthur") try partialPlayer.delete(db) - sqlQueries.removeAll() + clearSQLQueries() let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in try Int.fetchOne(statement) } @@ -1645,7 +1744,7 @@ extension MutablePersistableRecordTests { } do { - sqlQueries.removeAll() + clearSQLQueries() var partialPlayer = PartialPlayer(id: 1, name: "Arthur") let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in try Int.fetchOne(statement) @@ -1688,7 +1787,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 @@ -1709,7 +1808,7 @@ extension MutablePersistableRecordTests { player.name = "Barbara" do { - let updatedPlayer = try XCTUnwrap(player.updateAndFetch(db)) + let updatedPlayer = try player.updateAndFetch(db) XCTAssertEqual(updatedPlayer.id, 1) XCTAssertEqual(updatedPlayer.name, "Barbara") XCTAssertEqual(updatedPlayer.score, 1000) @@ -1739,7 +1838,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 @@ -1760,7 +1859,7 @@ extension MutablePersistableRecordTests { player.name = "Barbara" do { - let updatedPlayer = try XCTUnwrap(player.updateAndFetch(db, as: PartialPlayer.self)) + let updatedPlayer = try player.updateAndFetch(db, as: PartialPlayer.self) XCTAssertEqual(updatedPlayer.id, 1) XCTAssertEqual(updatedPlayer.name, "Barbara") } @@ -1789,7 +1888,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 +1901,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 +1912,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 +1942,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 +1955,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 +1966,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 +1996,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 +2057,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 +2117,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 +2131,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") @@ -2041,16 +2140,20 @@ extension MutablePersistableRecordTests { try player.insert(db) do { - let updatedRow = try player.updateChangesAndFetch( - db, selection: [AllColumns()], - fetch: { statement in try Row.fetchOne(statement) }, + // Update with no change + let update = try player.updateChangesAndFetch( + db, selection: [.allColumns], + fetch: { statement in + XCTFail("Should not be called") + return "ignored" + }, modify: { $0.name = "Barbara" }) - XCTAssertNil(updatedRow) + XCTAssertNil(update) } 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]) @@ -2084,7 +2187,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 @@ -2233,7 +2336,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 @@ -2389,7 +2492,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 @@ -2401,7 +2504,7 @@ extension MutablePersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() var player = FullPlayer(id: 1, name: "Arthur", score: 1000) let upsertedPlayer = try player.upsertAndFetch(db) @@ -2445,7 +2548,7 @@ extension MutablePersistableRecordTests { } do { - sqlQueries.removeAll() + clearSQLQueries() var player = FullPlayer(id: 1, name: "Barbara", score: 100) let upsertedPlayer = try player.upsertAndFetch(db) @@ -2492,7 +2595,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 @@ -2504,7 +2607,7 @@ extension MutablePersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() var partialPlayer = PartialPlayer(name: "Arthur") let fullPlayer = try partialPlayer.upsertAndFetch(db, as: FullPlayer.self) diff --git a/Tests/GRDBTests/Mutex.swift b/Tests/GRDBTests/Mutex.swift new file mode 100644 index 000000000..1fb69c2e2 --- /dev/null +++ b/Tests/GRDBTests/Mutex.swift @@ -0,0 +1,54 @@ +import Foundation + +/// A Mutex protects a value with an NSLock. +/// +/// We'll replace it with the SE-0433 Mutex when it is available. +/// +final class Mutex { + private var _value: T + private var lock = NSLock() + + init(_ value: T) { + _value = value + } + + /// Runs the provided closure while holding a lock on the value. + /// + /// - parameter body: A closure that can modify the value. + func withLock(_ body: (inout T) throws -> U) rethrows -> U { + lock.lock() + defer { lock.unlock() } + return try body(&_value) + } +} + +// Inspired by +extension Mutex { + func load() -> T { + withLock { $0 } + } + + func store(_ value: T) { + withLock { $0 = value } + } +} + +extension Mutex where T: Numeric { + @discardableResult + func increment() -> T { + withLock { n in + n += 1 + return n + } + } + + @discardableResult + func decrement() -> T { + withLock { n in + n -= 1 + return n + } + } +} + +extension Mutex: @unchecked Sendable where T: Sendable { } diff --git a/Tests/GRDBTests/PersistableRecordTests.swift b/Tests/GRDBTests/PersistableRecordTests.swift index d919eeb98..80dfaa9ee 100644 --- a/Tests/GRDBTests/PersistableRecordTests.swift +++ b/Tests/GRDBTests/PersistableRecordTests.swift @@ -183,6 +183,8 @@ private struct PartialPlayer: Codable, PersistableRecord, FetchableRecord { case id, name } + typealias Columns = FullPlayer.Columns + func willInsert(_ db: Database) throws { callbacks.willInsertCount += 1 } @@ -250,6 +252,12 @@ private struct FullPlayer: Codable, PersistableRecord, FetchableRecord { case id, name, score } + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + static let score = Column(CodingKeys.score) + } + let callbacks = Callbacks() func willInsert(_ db: Database) throws { @@ -1328,7 +1336,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 @@ -1340,9 +1348,9 @@ extension PersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() let partialPlayer = PartialPlayer(name: "Arthur") - let fullPlayer = try XCTUnwrap(partialPlayer.insertAndFetch(db, as: FullPlayer.self)) + let fullPlayer = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) XCTAssert(sqlQueries.contains(""" INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING * @@ -1375,9 +1383,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 @@ -1389,7 +1397,7 @@ extension PersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() let partialPlayer = PartialPlayer(name: "Arthur") let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { (statement: Statement) in try Int.fetchOne(statement)! @@ -1423,14 +1431,10 @@ extension PersistableRecordTests { } } } -} - -// MARK: - Save and Fetch - -extension PersistableRecordTests { - func test_saveAndFetch_as() throws { + + func test_insertAndFetch_selection_fetch_column_DatabaseComponents() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER - guard sqlite3_libversion_number() >= 3035000 else { + guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") } #else @@ -1442,9 +1446,264 @@ extension PersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() let partialPlayer = PartialPlayer(name: "Arthur") - let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + let score = try partialPlayer.insertAndFetch(db) { (statement: Statement) in + try Int.fetchOne(statement)! + } select: { + [$0.score] + } + + XCTAssert(sqlQueries.contains(""" + INSERT INTO "player" ("id", "name") VALUES (NULL,'Arthur') RETURNING "score" + """), sqlQueries.joined(separator: "\n")) + + XCTAssertEqual(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() 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_DatabaseComponents() 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) { (statement: Statement) in + try Row.fetchOne(statement)! + } select: { _ in + [.allColumns] + } + + 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) + } + } + } + + func test_insertAndFetch_selection_fetch_allColumns_excluding_DatabaseComponents() 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) { (statement: Statement) in + try Row.fetchOne(statement)! + } select: { _ in + [.allColumns(excluding: ["score"])] + } + + 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 + +extension PersistableRecordTests { + func test_saveAndFetch_as() 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 fullPlayer = try partialPlayer.saveAndFetch(db, as: FullPlayer.self) XCTAssert(sqlQueries.allSatisfy { !$0.contains("UPDATE") }) XCTAssert(sqlQueries.contains(""" @@ -1479,8 +1738,8 @@ extension PersistableRecordTests { do { let partialPlayer = PartialPlayer(id: 1, name: "Arthur") try partialPlayer.delete(db) - sqlQueries.removeAll() - let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + clearSQLQueries() + let fullPlayer = try partialPlayer.saveAndFetch(db, as: FullPlayer.self) XCTAssert(sqlQueries.contains(""" UPDATE "player" SET "name"='Arthur' WHERE "id"=1 RETURNING * @@ -1515,9 +1774,9 @@ extension PersistableRecordTests { } do { - sqlQueries.removeAll() + clearSQLQueries() let partialPlayer = PartialPlayer(id: 1, name: "Arthur") - let fullPlayer = try XCTUnwrap(partialPlayer.saveAndFetch(db, as: FullPlayer.self)) + let fullPlayer = try partialPlayer.saveAndFetch(db, as: FullPlayer.self) XCTAssert(sqlQueries.allSatisfy { !$0.contains("INSERT") }) XCTAssert(sqlQueries.contains(""" @@ -1551,9 +1810,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 @@ -1565,7 +1824,7 @@ extension PersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() let partialPlayer = PartialPlayer(name: "Arthur") let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in try Int.fetchOne(statement) @@ -1602,7 +1861,7 @@ extension PersistableRecordTests { do { let partialPlayer = PartialPlayer(id: 1, name: "Arthur") try partialPlayer.delete(db) - sqlQueries.removeAll() + clearSQLQueries() let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in try Int.fetchOne(statement) } @@ -1638,7 +1897,7 @@ extension PersistableRecordTests { } do { - sqlQueries.removeAll() + clearSQLQueries() let partialPlayer = PartialPlayer(id: 1, name: "Arthur") let score = try partialPlayer.saveAndFetch(db, selection: [Column("score")]) { (statement: Statement) in try Int.fetchOne(statement) @@ -1673,6 +1932,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 +2189,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 +2326,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 +2471,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 @@ -1974,7 +2483,7 @@ extension PersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() let player = FullPlayer(id: 1, name: "Arthur", score: 1000) let upsertedPlayer = try player.upsertAndFetch(db) @@ -2018,7 +2527,7 @@ extension PersistableRecordTests { } do { - sqlQueries.removeAll() + clearSQLQueries() let player = FullPlayer(id: 1, name: "Barbara", score: 100) let upsertedPlayer = try player.upsertAndFetch(db) @@ -2065,7 +2574,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 @@ -2077,7 +2586,7 @@ extension PersistableRecordTests { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - sqlQueries.removeAll() + clearSQLQueries() let partialPlayer = PartialPlayer(name: "Arthur") let fullPlayer = try partialPlayer.upsertAndFetch(db, as: FullPlayer.self) diff --git a/Tests/GRDBTests/PoolTests.swift b/Tests/GRDBTests/PoolTests.swift index 29c8fcaf7..8729ae817 100644 --- a/Tests/GRDBTests/PoolTests.swift +++ b/Tests/GRDBTests/PoolTests.swift @@ -4,8 +4,10 @@ import XCTest class PoolTests: XCTestCase { /// Returns a Pool whose elements are incremented integers: 1, 2, 3... private func makeCounterPool(maximumCount: Int) -> Pool { - let count = ReadWriteBox(wrappedValue: 0) - return Pool(maximumCount: maximumCount, makeElement: count.increment) + let countMutex = Mutex(0) + return Pool(maximumCount: maximumCount, makeElement: { _ in + countMutex.increment() + }) } func testElementsAreReused() throws { diff --git a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift index e2e50cb24..93592c7c6 100644 --- a/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift +++ b/Tests/GRDBTests/QueryInterfaceExpressionsTests.swift @@ -1,16 +1,17 @@ import XCTest @testable import GRDB -private struct Col { - static let id = Column("id") - static let name = Column("name") - static let age = Column("age") - static let readerId = Column("readerId") -} - private struct Reader : TableRecord { static let databaseTableName = "readers" + + struct Columns { + static let id = Column("id") + static let name = Column("name") + static let age = Column("age") + static let readerId = Column("readerId") + } } +private typealias Columns = Reader.Columns private let tableRequest = Reader.all() class QueryInterfaceExpressionsTests: GRDBTestCase { @@ -53,112 +54,178 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { // emptyArray.contains(): 0 XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Int]().contains(Col.id))), + sql(dbQueue, tableRequest.filter([Int]().contains(Columns.id))), "SELECT * FROM \"readers\" WHERE 0") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { [Int]().contains($0.id) }), + "SELECT * FROM \"readers\" WHERE 0") + // !emptyArray.contains(): 0 XCTAssertEqual( - sql(dbQueue, tableRequest.filter(![Int]().contains(Col.id))), + sql(dbQueue, tableRequest.filter(![Int]().contains(Columns.id))), "SELECT * FROM \"readers\" WHERE 1") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { ![Int]().contains($0.id) }), + "SELECT * FROM \"readers\" WHERE 1") + // Array.contains(): = operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter([1].contains(Col.id))), + sql(dbQueue, tableRequest.filter([1].contains(Columns.id))), "SELECT * FROM \"readers\" WHERE \"id\" = 1") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { [1].contains($0.id) }), + "SELECT * FROM \"readers\" WHERE \"id\" = 1") + // Array.contains(): IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter([1,2,3].contains(Col.id))), + sql(dbQueue, tableRequest.filter([1,2,3].contains(Columns.id))), "SELECT * FROM \"readers\" WHERE \"id\" IN (1, 2, 3)") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { [1,2,3].contains($0.id) }), + "SELECT * FROM \"readers\" WHERE \"id\" IN (1, 2, 3)") + // Array.contains(): IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id].contains(Col.id))), + sql(dbQueue, tableRequest.filter([Columns.id].contains(Columns.id))), "SELECT * FROM \"readers\" WHERE \"id\" = \"id\"") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { [$0.id].contains($0.id) }), + "SELECT * FROM \"readers\" WHERE \"id\" = \"id\"") + // EmptyCollection.contains(): 0 XCTAssertEqual( - sql(dbQueue, tableRequest.filter(EmptyCollection().contains(Col.id))), + sql(dbQueue, tableRequest.filter(EmptyCollection().contains(Columns.id))), "SELECT * FROM \"readers\" WHERE 0") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { EmptyCollection().contains($0.id) }), + "SELECT * FROM \"readers\" WHERE 0") + // !EmptyCollection.contains(): 1 XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!EmptyCollection().contains(Col.id))), + sql(dbQueue, tableRequest.filter(!EmptyCollection().contains(Columns.id))), "SELECT * FROM \"readers\" WHERE 1") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !EmptyCollection().contains($0.id) }), + "SELECT * FROM \"readers\" WHERE 1") + // Sequence.contains(): = operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(AnySequence([1]).contains(Col.id))), + sql(dbQueue, tableRequest.filter(AnySequence([1]).contains(Columns.id))), "SELECT * FROM \"readers\" WHERE \"id\" = 1") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { AnySequence([1]).contains($0.id) }), + "SELECT * FROM \"readers\" WHERE \"id\" = 1") + // Sequence.contains(): IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(AnySequence([1,2,3]).contains(Col.id))), + sql(dbQueue, tableRequest.filter(AnySequence([1,2,3]).contains(Columns.id))), "SELECT * FROM \"readers\" WHERE \"id\" IN (1, 2, 3)") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { AnySequence([1,2,3]).contains($0.id) }), + "SELECT * FROM \"readers\" WHERE \"id\" IN (1, 2, 3)") + // Sequence.contains(): IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(AnySequence([Col.id]).contains(Col.id))), + sql(dbQueue, tableRequest.filter(AnySequence([Columns.id]).contains(Columns.id))), "SELECT * FROM \"readers\" WHERE \"id\" = \"id\"") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { AnySequence([$0.id]).contains($0.id) }), + "SELECT * FROM \"readers\" WHERE \"id\" = \"id\"") + // !Sequence.contains(): <> operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(![1].contains(Col.id))), + sql(dbQueue, tableRequest.filter(![1].contains(Columns.id))), "SELECT * FROM \"readers\" WHERE \"id\" <> 1") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { ![1].contains($0.id) }), + "SELECT * FROM \"readers\" WHERE \"id\" <> 1") + // !Sequence.contains(): NOT IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(![1,2,3].contains(Col.id))), + sql(dbQueue, tableRequest.filter(![1,2,3].contains(Columns.id))), "SELECT * FROM \"readers\" WHERE \"id\" NOT IN (1, 2, 3)") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { ![1,2,3].contains($0.id) }), + "SELECT * FROM \"readers\" WHERE \"id\" NOT IN (1, 2, 3)") + // !!Sequence.contains(): = operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(![1].contains(Col.id)))), + sql(dbQueue, tableRequest.filter(!(![1].contains(Columns.id)))), "SELECT * FROM \"readers\" WHERE \"id\" = 1") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !(![1].contains($0.id)) }), + "SELECT * FROM \"readers\" WHERE \"id\" = 1") + // !!Sequence.contains(): IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(![1,2,3].contains(Col.id)))), + sql(dbQueue, tableRequest.filter(!(![1,2,3].contains(Columns.id)))), "SELECT * FROM \"readers\" WHERE \"id\" IN (1, 2, 3)") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !(![1,2,3].contains($0.id)) }), + "SELECT * FROM \"readers\" WHERE \"id\" IN (1, 2, 3)") + // CountableRange.contains(): min <= x < max XCTAssertEqual( - sql(dbQueue, tableRequest.filter((1..<10).contains(Col.id))), + sql(dbQueue, tableRequest.filter((1..<10).contains(Columns.id))), "SELECT * FROM \"readers\" WHERE (\"id\" >= 1) AND (\"id\" < 10)") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { (1..<10).contains($0.id) }), + "SELECT * FROM \"readers\" WHERE (\"id\" >= 1) AND (\"id\" < 10)") + // CountableClosedRange.contains(): BETWEEN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter((1...10).contains(Col.id))), + sql(dbQueue, tableRequest.filter((1...10).contains(Columns.id))), "SELECT * FROM \"readers\" WHERE \"id\" BETWEEN 1 AND 10") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { (1...10).contains($0.id) }), + "SELECT * FROM \"readers\" WHERE \"id\" BETWEEN 1 AND 10") + // !CountableClosedRange.contains(): BETWEEN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(1...10).contains(Col.id))), + sql(dbQueue, tableRequest.filter(!(1...10).contains(Columns.id))), "SELECT * FROM \"readers\" WHERE \"id\" NOT BETWEEN 1 AND 10") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !(1...10).contains($0.id) }), + "SELECT * FROM \"readers\" WHERE \"id\" NOT BETWEEN 1 AND 10") + // Range.contains(): min <= x < max XCTAssertEqual( - sql(dbQueue, tableRequest.filter((1.1..<10.9).contains(Col.id))), + sql(dbQueue, tableRequest.filter((1.1..<10.9).contains(Columns.id))), "SELECT * FROM \"readers\" WHERE (\"id\" >= 1.1) AND (\"id\" < 10.9)") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { (1.1..<10.9).contains($0.id) }), + "SELECT * FROM \"readers\" WHERE (\"id\" >= 1.1) AND (\"id\" < 10.9)") + // Range.contains(): min <= x < max XCTAssertEqual( - sql(dbQueue, tableRequest.filter(("A"..<"z").contains(Col.name))), + sql(dbQueue, tableRequest.filter(("A"..<"z").contains(Columns.name))), "SELECT * FROM \"readers\" WHERE (\"name\" >= 'A') AND (\"name\" < 'z')") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { ("A"..<"z").contains($0.name) }), + "SELECT * FROM \"readers\" WHERE (\"name\" >= 'A') AND (\"name\" < 'z')") + // ClosedRange.contains(): BETWEEN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter((1.1...10.9).contains(Col.id))), + sql(dbQueue, tableRequest.filter((1.1...10.9).contains(Columns.id))), "SELECT * FROM \"readers\" WHERE \"id\" BETWEEN 1.1 AND 10.9") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { (1.1...10.9).contains($0.id) }), + "SELECT * FROM \"readers\" WHERE \"id\" BETWEEN 1.1 AND 10.9") + // ClosedRange.contains(): BETWEEN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(("A"..."z").contains(Col.name))), + sql(dbQueue, tableRequest.filter(("A"..."z").contains(Columns.name))), "SELECT * FROM \"readers\" WHERE \"name\" BETWEEN 'A' AND 'z'") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { ("A"..."z").contains($0.name) }), + "SELECT * FROM \"readers\" WHERE \"name\" BETWEEN 'A' AND 'z'") + // !ClosedRange.contains(): NOT BETWEEN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!("A"..."z").contains(Col.name))), + sql(dbQueue, tableRequest.filter(!("A"..."z").contains(Columns.name))), + "SELECT * FROM \"readers\" WHERE \"name\" NOT BETWEEN 'A' AND 'z'") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !("A"..."z").contains($0.name) }), "SELECT * FROM \"readers\" WHERE \"name\" NOT BETWEEN 'A' AND 'z'") } @@ -177,42 +244,66 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { // Array.contains(): IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(["arthur", "barbara"].contains(Col.name.collating(.nocase)))), + sql(dbQueue, tableRequest.filter(["arthur", "barbara"].contains(Columns.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!["arthur", "barbara"].contains(Col.name.collating(.nocase)))), + sql(dbQueue, tableRequest.filter { ["arthur", "barbara"].contains($0.name.collating(.nocase)) }), + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!["arthur", "barbara"].contains(Columns.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) NOT IN ('arthur', 'barbara')") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [any SQLExpressible]).contains(Col.name.collating(.nocase)))), + sql(dbQueue, tableRequest.filter { !["arthur", "barbara"].contains($0.name.collating(.nocase)) }), + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) NOT IN ('arthur', 'barbara')") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [any SQLExpressible]).contains(Columns.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { (["arthur", "barbara"] as [any SQLExpressible]).contains($0.name.collating(.nocase)) }), + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") + // Sequence.contains(): IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(AnySequence(["arthur", "barbara"]).contains(Col.name.collating(.nocase)))), + sql(dbQueue, tableRequest.filter(AnySequence(["arthur", "barbara"]).contains(Columns.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { AnySequence(["arthur", "barbara"]).contains($0.name.collating(.nocase)) }), + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") + // Sequence.contains(): = operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(AnySequence([Col.name]).contains(Col.name.collating(.nocase)))), + sql(dbQueue, tableRequest.filter(AnySequence([Columns.name]).contains(Columns.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE \"name\" = \"name\" COLLATE NOCASE") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { AnySequence([$0.name]).contains($0.name.collating(.nocase)) }), + "SELECT * FROM \"readers\" WHERE \"name\" = \"name\" COLLATE NOCASE") + // Sequence.contains(): false XCTAssertEqual( - sql(dbQueue, tableRequest.filter(EmptyCollection().contains(Col.name.collating(.nocase)))), + sql(dbQueue, tableRequest.filter(EmptyCollection().contains(Columns.name.collating(.nocase)))), + "SELECT * FROM \"readers\" WHERE 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { EmptyCollection().contains($0.name.collating(.nocase)) }), "SELECT * FROM \"readers\" WHERE 0") // ClosedInterval: BETWEEN operator let closedInterval = "A"..."z" XCTAssertEqual( - sql(dbQueue, tableRequest.filter(closedInterval.contains(Col.name.collating(.nocase)))), + sql(dbQueue, tableRequest.filter(closedInterval.contains(Columns.name.collating(.nocase)))), "SELECT * FROM \"readers\" WHERE \"name\" BETWEEN 'A' AND 'z' COLLATE NOCASE") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { closedInterval.contains($0.name.collating(.nocase)) }), + "SELECT * FROM \"readers\" WHERE \"name\" BETWEEN 'A' AND 'z' COLLATE NOCASE") + // HalfOpenInterval: min <= x < max let halfOpenInterval = "A"..<"z" XCTAssertEqual( - sql(dbQueue, tableRequest.filter(halfOpenInterval.contains(Col.name.collating(.nocase)))), + sql(dbQueue, tableRequest.filter(halfOpenInterval.contains(Columns.name.collating(.nocase)))), + "SELECT * FROM \"readers\" WHERE (\"name\" >= 'A' COLLATE NOCASE) AND (\"name\" < 'z' COLLATE NOCASE)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { halfOpenInterval.contains($0.name.collating(.nocase)) }), "SELECT * FROM \"readers\" WHERE (\"name\" >= 'A' COLLATE NOCASE) AND (\"name\" < 'z' COLLATE NOCASE)") } @@ -231,42 +322,66 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { // Array.contains(): IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(["arthur", "barbara"].contains(Col.name).collating(.nocase))), + sql(dbQueue, tableRequest.filter(["arthur", "barbara"].contains(Columns.name).collating(.nocase))), "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!["arthur", "barbara"].contains(Col.name).collating(.nocase))), + sql(dbQueue, tableRequest.filter { ["arthur", "barbara"].contains($0.name).collating(.nocase) }), + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!["arthur", "barbara"].contains(Columns.name).collating(.nocase))), "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) NOT IN ('arthur', 'barbara')") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [any SQLExpressible]).contains(Col.name).collating(.nocase))), + sql(dbQueue, tableRequest.filter { !["arthur", "barbara"].contains($0.name).collating(.nocase) }), + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) NOT IN ('arthur', 'barbara')") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [any SQLExpressible]).contains(Columns.name).collating(.nocase))), "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { (["arthur", "barbara"] as [any SQLExpressible]).contains($0.name).collating(.nocase) }), + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") + // Sequence.contains(): IN operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(AnySequence(["arthur", "barbara"]).contains(Col.name).collating(.nocase))), + sql(dbQueue, tableRequest.filter(AnySequence(["arthur", "barbara"]).contains(Columns.name).collating(.nocase))), "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { AnySequence(["arthur", "barbara"]).contains($0.name).collating(.nocase) }), + "SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')") + // Sequence.contains(): = operator XCTAssertEqual( - sql(dbQueue, tableRequest.filter(AnySequence([Col.name]).contains(Col.name).collating(.nocase))), + sql(dbQueue, tableRequest.filter(AnySequence([Columns.name]).contains(Columns.name).collating(.nocase))), "SELECT * FROM \"readers\" WHERE \"name\" = \"name\" COLLATE NOCASE") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { AnySequence([$0.name]).contains($0.name).collating(.nocase) }), + "SELECT * FROM \"readers\" WHERE \"name\" = \"name\" COLLATE NOCASE") + // Sequence.contains(): false XCTAssertEqual( - sql(dbQueue, tableRequest.filter(EmptyCollection().contains(Col.name).collating(.nocase))), + sql(dbQueue, tableRequest.filter(EmptyCollection().contains(Columns.name).collating(.nocase))), "SELECT * FROM \"readers\" WHERE 0 COLLATE NOCASE") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { EmptyCollection().contains($0.name).collating(.nocase) }), + "SELECT * FROM \"readers\" WHERE 0 COLLATE NOCASE") + // ClosedInterval: BETWEEN operator let closedInterval = "A"..."z" XCTAssertEqual( - sql(dbQueue, tableRequest.filter(closedInterval.contains(Col.name).collating(.nocase))), + sql(dbQueue, tableRequest.filter(closedInterval.contains(Columns.name).collating(.nocase))), "SELECT * FROM \"readers\" WHERE \"name\" BETWEEN 'A' AND 'z' COLLATE NOCASE") - + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { closedInterval.contains($0.name).collating(.nocase) }), + "SELECT * FROM \"readers\" WHERE \"name\" BETWEEN 'A' AND 'z' COLLATE NOCASE") + // HalfOpenInterval: min <= x < max let halfOpenInterval = "A"..<"z" XCTAssertEqual( - sql(dbQueue, tableRequest.filter(halfOpenInterval.contains(Col.name).collating(.nocase))), + sql(dbQueue, tableRequest.filter(halfOpenInterval.contains(Columns.name).collating(.nocase))), + "SELECT * FROM \"readers\" WHERE (\"name\" >= 'A' COLLATE NOCASE) AND (\"name\" < 'z' COLLATE NOCASE)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { halfOpenInterval.contains($0.name).collating(.nocase) }), "SELECT * FROM \"readers\" WHERE (\"name\" >= 'A' COLLATE NOCASE) AND (\"name\" < 'z' COLLATE NOCASE)") } @@ -274,9 +389,19 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() do { - let subquery = tableRequest.select(Col.age).filter(Col.name != nil).distinct() + let subquery = tableRequest.select(Columns.age).filter(Columns.name != nil).distinct() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(subquery.contains(Col.age))), + sql(dbQueue, tableRequest.filter(subquery.contains(Columns.age))), + """ + SELECT * FROM "readers" WHERE "age" IN \ + (SELECT DISTINCT "age" FROM "readers" WHERE "name" IS NOT NULL) + """) + } + + do { + let subquery = tableRequest.select { $0.age }.filter { $0.name != nil }.distinct() + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { subquery.contains($0.age) }), """ SELECT * FROM "readers" WHERE "age" IN \ (SELECT DISTINCT "age" FROM "readers" WHERE "name" IS NOT NULL) @@ -286,17 +411,38 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { do { let subquery = SQLRequest(sql: "SELECT ? UNION SELECT ?", arguments: [1, 2]) XCTAssertEqual( - sql(dbQueue, tableRequest.filter(subquery.contains(Col.age + 1))), + sql(dbQueue, tableRequest.filter(subquery.contains(Columns.age + 1))), """ SELECT * FROM "readers" WHERE ("age" + 1) IN (SELECT 1 UNION SELECT 2) """) } do { - let subquery1 = tableRequest.select(max(Col.age)) - let subquery2 = tableRequest.filter(Col.age == subquery1) + let subquery = SQLRequest(sql: "SELECT ? UNION SELECT ?", arguments: [1, 2]) XCTAssertEqual( - sql(dbQueue, tableRequest.filter(subquery2.select(Col.id).contains(Col.id))), + sql(dbQueue, tableRequest.filter { subquery.contains($0.age + 1) }), + """ + SELECT * FROM "readers" WHERE ("age" + 1) IN (SELECT 1 UNION SELECT 2) + """) + } + + do { + let subquery1 = tableRequest.select(max(Columns.age)) + let subquery2 = tableRequest.filter(Columns.age == subquery1) + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(subquery2.select(Columns.id).contains(Columns.id))), + """ + SELECT * FROM "readers" WHERE "id" IN (\ + SELECT "id" FROM "readers" WHERE "age" = (\ + SELECT MAX("age") FROM "readers")) + """) + } + + do { + let subquery1 = tableRequest.select { max($0.age) } + let subquery2 = tableRequest.filter { $0.age == subquery1 } + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { subquery2.select($0.id).contains($0.id) }), """ SELECT * FROM "readers" WHERE "id" IN (\ SELECT "id" FROM "readers" WHERE "age" = (\ @@ -316,20 +462,41 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { try db.create(table: "player") { t in t.column("teamID", .integer).references("team") } - struct Player: TableRecord { } - struct Team: TableRecord { } - let teamAlias = TableAlias() - let player = Player.filter(Column("teamID") == teamAlias[Column("id")]) - let teams = Team.aliased(teamAlias).filter(player.exists()) - try assertEqualSQL(db, teams, """ - SELECT * FROM "team" WHERE EXISTS (SELECT * FROM "player" WHERE "teamID" = "team"."id") - """) + struct Player: TableRecord { + enum Columns { + static let teamID = Column("teamID") + } + } + struct Team: TableRecord { + enum Columns { + static let id = Column("id") + } + } + + do { + let teamAlias = TableAlias() + let player = Player.filter(Column("teamID") == teamAlias[Column("id")]) + let teams = Team.aliased(teamAlias).filter(player.exists()) + try assertEqualSQL(db, teams, """ + SELECT * FROM "team" WHERE EXISTS (SELECT * FROM "player" WHERE "teamID" = "team"."id") + """) + } + #if compiler(>=6.1) + do { + let teamAlias = TableAlias() + let player = Player.filter { $0.teamID == teamAlias.id } + let teams = Team.aliased(teamAlias).filter(player.exists()) + try assertEqualSQL(db, teams, """ + SELECT * FROM "team" WHERE EXISTS (SELECT * FROM "player" WHERE "teamID" = "team"."id") + """) + } + #endif } } do { let alias = TableAlias(name: "r") - let subquery = tableRequest.filter(Col.age > alias[Col.age]) + let subquery = tableRequest.filter(Columns.age > alias[Columns.age]) XCTAssertEqual( sql(dbQueue, tableRequest.aliased(alias).filter(subquery.exists())), """ @@ -339,7 +506,17 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { do { let alias = TableAlias(name: "r") - let subquery = tableRequest.filter(Col.age > alias[Col.age]) + let subquery = tableRequest.filter { $0.age > alias[$0.age] } + XCTAssertEqual( + sql(dbQueue, tableRequest.aliased(alias).filter(subquery.exists())), + """ + SELECT "r".* FROM "readers" "r" WHERE EXISTS (SELECT * FROM "readers" WHERE "age" > "r"."age") + """) + } + + do { + let alias = TableAlias(name: "r") + let subquery = tableRequest.filter(Columns.age > alias[Columns.age]) XCTAssertEqual( sql(dbQueue, tableRequest.aliased(alias).filter(!subquery.exists())), """ @@ -349,7 +526,17 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { do { let alias = TableAlias(name: "r") - let subquery = SQLRequest("SELECT * FROM readers WHERE age > \(alias[Col.age])") + let subquery = tableRequest.filter { $0.age > alias[$0.age] } + XCTAssertEqual( + sql(dbQueue, tableRequest.aliased(alias).filter(!subquery.exists())), + """ + SELECT "r".* FROM "readers" "r" WHERE NOT EXISTS (SELECT * FROM "readers" WHERE "age" > "r"."age") + """) + } + + do { + let alias = TableAlias(name: "r") + let subquery = SQLRequest("SELECT * FROM readers WHERE age > \(alias[Columns.age])") XCTAssertEqual( sql(dbQueue, tableRequest.aliased(alias).filter(subquery.exists())), """ @@ -362,33 +549,54 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age > 10)), + sql(dbQueue, tableRequest.filter(Columns.age > 10)), "SELECT * FROM \"readers\" WHERE \"age\" > 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(10 > Col.age)), + sql(dbQueue, tableRequest.filter { $0.age > 10 }), + "SELECT * FROM \"readers\" WHERE \"age\" > 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(10 > Columns.age)), + "SELECT * FROM \"readers\" WHERE 10 > \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 10 > $0.age }), "SELECT * FROM \"readers\" WHERE 10 > \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 10 > 10 }), "SELECT * FROM \"readers\" WHERE 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age > Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age > Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" > \"age\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name > "B")), + sql(dbQueue, tableRequest.filter { $0.age > $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" > \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name > "B")), "SELECT * FROM \"readers\" WHERE \"name\" > 'B'") XCTAssertEqual( - sql(dbQueue, tableRequest.filter("B" > Col.name)), + sql(dbQueue, tableRequest.filter { $0.name > "B" }), + "SELECT * FROM \"readers\" WHERE \"name\" > 'B'") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter("B" > Columns.name)), + "SELECT * FROM \"readers\" WHERE 'B' > \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { "B" > $0.name }), "SELECT * FROM \"readers\" WHERE 'B' > \"name\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in "B" > "B" }), "SELECT * FROM \"readers\" WHERE 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name > Col.name)), + sql(dbQueue, tableRequest.filter(Columns.name > Columns.name)), "SELECT * FROM \"readers\" WHERE \"name\" > \"name\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.group(Col.name).having(average(Col.age) + 10 > 20)), + sql(dbQueue, tableRequest.filter { $0.name > $0.name }), + "SELECT * FROM \"readers\" WHERE \"name\" > \"name\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.group(Columns.name).having(average(Columns.age) + 10 > 20)), + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (AVG(\"age\") + 10) > 20") + XCTAssertEqual( + sql(dbQueue, tableRequest.group { $0.name }.having { average($0.age) + 10 > 20 }), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (AVG(\"age\") + 10) > 20") } @@ -396,10 +604,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) > "fOo")), + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) > "fOo")), "SELECT * FROM \"readers\" WHERE \"name\" > 'fOo' COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(collation) > "fOo")), + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) > "fOo" }), + "SELECT * FROM \"readers\" WHERE \"name\" > 'fOo' COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.collating(collation) > "fOo")), + "SELECT * FROM \"readers\" WHERE \"name\" > 'fOo' COLLATE localized_case_insensitive") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.collating(collation) > "fOo" }), "SELECT * FROM \"readers\" WHERE \"name\" > 'fOo' COLLATE localized_case_insensitive") } @@ -407,33 +621,54 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age >= 10)), + sql(dbQueue, tableRequest.filter(Columns.age >= 10)), "SELECT * FROM \"readers\" WHERE \"age\" >= 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(10 >= Col.age)), + sql(dbQueue, tableRequest.filter { $0.age >= 10 }), + "SELECT * FROM \"readers\" WHERE \"age\" >= 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(10 >= Columns.age)), + "SELECT * FROM \"readers\" WHERE 10 >= \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 10 >= $0.age }), "SELECT * FROM \"readers\" WHERE 10 >= \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 10 >= 10 }), "SELECT * FROM \"readers\" WHERE 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age >= Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age >= Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" >= \"age\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name >= "B")), + sql(dbQueue, tableRequest.filter { $0.age >= Columns.age }), + "SELECT * FROM \"readers\" WHERE \"age\" >= \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name >= "B")), "SELECT * FROM \"readers\" WHERE \"name\" >= 'B'") XCTAssertEqual( - sql(dbQueue, tableRequest.filter("B" >= Col.name)), + sql(dbQueue, tableRequest.filter { $0.name >= "B" }), + "SELECT * FROM \"readers\" WHERE \"name\" >= 'B'") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter("B" >= Columns.name)), + "SELECT * FROM \"readers\" WHERE 'B' >= \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { "B" >= $0.name }), "SELECT * FROM \"readers\" WHERE 'B' >= \"name\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in "B" >= "B" }), "SELECT * FROM \"readers\" WHERE 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name >= Col.name)), + sql(dbQueue, tableRequest.filter(Columns.name >= Columns.name)), "SELECT * FROM \"readers\" WHERE \"name\" >= \"name\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.group(Col.name).having(average(Col.age) + 10 >= 20)), + sql(dbQueue, tableRequest.filter { $0.name >= $0.name }), + "SELECT * FROM \"readers\" WHERE \"name\" >= \"name\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.group(Columns.name).having(average(Columns.age) + 10 >= 20)), + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (AVG(\"age\") + 10) >= 20") + XCTAssertEqual( + sql(dbQueue, tableRequest.group { $0.name }.having { average($0.age) + 10 >= 20 }), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (AVG(\"age\") + 10) >= 20") } @@ -441,10 +676,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) >= "fOo")), + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) >= "fOo")), "SELECT * FROM \"readers\" WHERE \"name\" >= 'fOo' COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(collation) >= "fOo")), + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) >= "fOo" }), + "SELECT * FROM \"readers\" WHERE \"name\" >= 'fOo' COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.collating(collation) >= "fOo")), + "SELECT * FROM \"readers\" WHERE \"name\" >= 'fOo' COLLATE localized_case_insensitive") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.collating(collation) >= "fOo" }), "SELECT * FROM \"readers\" WHERE \"name\" >= 'fOo' COLLATE localized_case_insensitive") } @@ -452,33 +693,54 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age < 10)), + sql(dbQueue, tableRequest.filter(Columns.age < 10)), "SELECT * FROM \"readers\" WHERE \"age\" < 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(10 < Col.age)), + sql(dbQueue, tableRequest.filter { $0.age < 10 }), + "SELECT * FROM \"readers\" WHERE \"age\" < 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(10 < Columns.age)), + "SELECT * FROM \"readers\" WHERE 10 < \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 10 < $0.age }), "SELECT * FROM \"readers\" WHERE 10 < \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 10 < 10 }), "SELECT * FROM \"readers\" WHERE 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age < Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age < Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" < \"age\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name < "B")), + sql(dbQueue, tableRequest.filter { $0.age < $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" < \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name < "B")), "SELECT * FROM \"readers\" WHERE \"name\" < 'B'") XCTAssertEqual( - sql(dbQueue, tableRequest.filter("B" < Col.name)), + sql(dbQueue, tableRequest.filter { $0.name < "B" }), + "SELECT * FROM \"readers\" WHERE \"name\" < 'B'") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter("B" < Columns.name)), + "SELECT * FROM \"readers\" WHERE 'B' < \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { "B" < $0.name }), "SELECT * FROM \"readers\" WHERE 'B' < \"name\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in "B" < "B" }), "SELECT * FROM \"readers\" WHERE 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name < Col.name)), + sql(dbQueue, tableRequest.filter(Columns.name < Columns.name)), "SELECT * FROM \"readers\" WHERE \"name\" < \"name\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.group(Col.name).having(average(Col.age) + 10 < 20)), + sql(dbQueue, tableRequest.filter { $0.name < $0.name }), + "SELECT * FROM \"readers\" WHERE \"name\" < \"name\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.group(Columns.name).having(average(Columns.age) + 10 < 20)), + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (AVG(\"age\") + 10) < 20") + XCTAssertEqual( + sql(dbQueue, tableRequest.group { $0.name }.having { average($0.age) + 10 < 20 }), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (AVG(\"age\") + 10) < 20") } @@ -486,10 +748,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) < "fOo")), + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) < "fOo")), "SELECT * FROM \"readers\" WHERE \"name\" < 'fOo' COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(collation) < "fOo")), + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) < "fOo" }), + "SELECT * FROM \"readers\" WHERE \"name\" < 'fOo' COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.collating(collation) < "fOo")), + "SELECT * FROM \"readers\" WHERE \"name\" < 'fOo' COLLATE localized_case_insensitive") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.collating(collation) < "fOo" }), "SELECT * FROM \"readers\" WHERE \"name\" < 'fOo' COLLATE localized_case_insensitive") } @@ -497,33 +765,54 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age <= 10)), + sql(dbQueue, tableRequest.filter(Columns.age <= 10)), "SELECT * FROM \"readers\" WHERE \"age\" <= 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(10 <= Col.age)), + sql(dbQueue, tableRequest.filter { $0.age <= 10 }), + "SELECT * FROM \"readers\" WHERE \"age\" <= 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(10 <= Columns.age)), + "SELECT * FROM \"readers\" WHERE 10 <= \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 10 <= $0.age }), "SELECT * FROM \"readers\" WHERE 10 <= \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 10 <= 10 }), "SELECT * FROM \"readers\" WHERE 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age <= Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age <= Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" <= \"age\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name <= "B")), + sql(dbQueue, tableRequest.filter { $0.age <= $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" <= \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name <= "B")), "SELECT * FROM \"readers\" WHERE \"name\" <= 'B'") XCTAssertEqual( - sql(dbQueue, tableRequest.filter("B" <= Col.name)), + sql(dbQueue, tableRequest.filter { $0.name <= "B" }), + "SELECT * FROM \"readers\" WHERE \"name\" <= 'B'") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter("B" <= Columns.name)), + "SELECT * FROM \"readers\" WHERE 'B' <= \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { "B" <= $0.name }), "SELECT * FROM \"readers\" WHERE 'B' <= \"name\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in "B" <= "B" }), "SELECT * FROM \"readers\" WHERE 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name <= Col.name)), + sql(dbQueue, tableRequest.filter(Columns.name <= Columns.name)), "SELECT * FROM \"readers\" WHERE \"name\" <= \"name\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.group(Col.name).having(average(Col.age) + 10 <= 20)), + sql(dbQueue, tableRequest.filter { $0.name <= $0.name }), + "SELECT * FROM \"readers\" WHERE \"name\" <= \"name\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.group(Columns.name).having(average(Columns.age) + 10 <= 20)), + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (AVG(\"age\") + 10) <= 20") + XCTAssertEqual( + sql(dbQueue, tableRequest.group { $0.name }.having { average($0.age) + 10 <= 20 }), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (AVG(\"age\") + 10) <= 20") } @@ -531,10 +820,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) <= "fOo")), + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) <= "fOo")), "SELECT * FROM \"readers\" WHERE \"name\" <= 'fOo' COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(collation) <= "fOo")), + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) <= "fOo" }), + "SELECT * FROM \"readers\" WHERE \"name\" <= 'fOo' COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.collating(collation) <= "fOo")), + "SELECT * FROM \"readers\" WHERE \"name\" <= 'fOo' COLLATE localized_case_insensitive") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.collating(collation) <= "fOo" }), "SELECT * FROM \"readers\" WHERE \"name\" <= 'fOo' COLLATE localized_case_insensitive") } @@ -542,64 +837,115 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age == 10)), + sql(dbQueue, tableRequest.filter(Columns.age == 10)), "SELECT * FROM \"readers\" WHERE \"age\" = 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age == (10 as Int?))), + sql(dbQueue, tableRequest.filter { $0.age == 10 }), "SELECT * FROM \"readers\" WHERE \"age\" = 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(10 == Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age == (10 as Int?))), + "SELECT * FROM \"readers\" WHERE \"age\" = 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age == (10 as Int?) }), + "SELECT * FROM \"readers\" WHERE \"age\" = 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(10 == Columns.age)), "SELECT * FROM \"readers\" WHERE 10 = \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter((10 as Int?) == Col.age)), + sql(dbQueue, tableRequest.filter { 10 == $0.age }), + "SELECT * FROM \"readers\" WHERE 10 = \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter((10 as Int?) == Columns.age)), + "SELECT * FROM \"readers\" WHERE 10 = \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { (10 as Int?) == $0.age }), "SELECT * FROM \"readers\" WHERE 10 = \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 10 == 10 }), "SELECT * FROM \"readers\" WHERE 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age == Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age == Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" = \"age\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age == nil)), - "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age == DatabaseValue.null)), - "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(nil == Col.age)), - "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(DatabaseValue.null == Col.age)), - "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age == Col.age)), + sql(dbQueue, tableRequest.filter { $0.age == $0.age }), "SELECT * FROM \"readers\" WHERE \"age\" = \"age\"") - + XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name == "B")), + sql(dbQueue, tableRequest.filter(Columns.age == nil)), + "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age == nil }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age == DatabaseValue.null)), + "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age == DatabaseValue.null }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(nil == Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { nil == $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(DatabaseValue.null == Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { DatabaseValue.null == $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age == Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" = \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age == $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" = \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name == "B")), "SELECT * FROM \"readers\" WHERE \"name\" = 'B'") XCTAssertEqual( - sql(dbQueue, tableRequest.filter("B" == Col.name)), + sql(dbQueue, tableRequest.filter { $0.name == "B" }), + "SELECT * FROM \"readers\" WHERE \"name\" = 'B'") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter("B" == Columns.name)), + "SELECT * FROM \"readers\" WHERE 'B' = \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { "B" == $0.name }), "SELECT * FROM \"readers\" WHERE 'B' = \"name\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in "B" == "B" }), "SELECT * FROM \"readers\" WHERE 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name == Col.name)), + sql(dbQueue, tableRequest.filter(Columns.name == Columns.name)), "SELECT * FROM \"readers\" WHERE \"name\" = \"name\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age == true)), + sql(dbQueue, tableRequest.filter { $0.name == $0.name }), + "SELECT * FROM \"readers\" WHERE \"name\" = \"name\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age == true)), "SELECT * FROM \"readers\" WHERE \"age\" = 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(true == Col.age)), + sql(dbQueue, tableRequest.filter { $0.age == true }), "SELECT * FROM \"readers\" WHERE \"age\" = 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age == false)), + sql(dbQueue, tableRequest.filter(true == Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" = 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { true == $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" = 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age == false)), "SELECT * FROM \"readers\" WHERE \"age\" = 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(false == Col.age)), + sql(dbQueue, tableRequest.filter { $0.age == false }), + "SELECT * FROM \"readers\" WHERE \"age\" = 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(false == Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" = 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { false == $0.age }), "SELECT * FROM \"readers\" WHERE \"age\" = 0") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in true == true }), @@ -616,19 +962,34 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) == "fOo")), + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) == "fOo")), "SELECT * FROM \"readers\" WHERE \"name\" = 'fOo' COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) == ("fOo" as String?))), + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) == "fOo" }), "SELECT * FROM \"readers\" WHERE \"name\" = 'fOo' COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) == nil)), + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) == ("fOo" as String?))), + "SELECT * FROM \"readers\" WHERE \"name\" = 'fOo' COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) == ("fOo" as String?) }), + "SELECT * FROM \"readers\" WHERE \"name\" = 'fOo' COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) == nil)), "SELECT * FROM \"readers\" WHERE \"name\" IS NULL COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) == DatabaseValue.null)), + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) == nil }), "SELECT * FROM \"readers\" WHERE \"name\" IS NULL COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(collation) == "fOo")), + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) == DatabaseValue.null)), + "SELECT * FROM \"readers\" WHERE \"name\" IS NULL COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) == DatabaseValue.null }), + "SELECT * FROM \"readers\" WHERE \"name\" IS NULL COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.collating(collation) == "fOo")), + "SELECT * FROM \"readers\" WHERE \"name\" = 'fOo' COLLATE localized_case_insensitive") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.collating(collation) == "fOo" }), "SELECT * FROM \"readers\" WHERE \"name\" = 'fOo' COLLATE localized_case_insensitive") } @@ -636,9 +997,18 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() do { - let subquery = tableRequest.select(max(Col.age)) + let subquery = tableRequest.select(max(Columns.age)) XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age == subquery)), + sql(dbQueue, tableRequest.filter(Columns.age == subquery)), + """ + SELECT * FROM "readers" WHERE "age" = (SELECT MAX("age") FROM "readers") + """) + } + + do { + let subquery = tableRequest.select { max($0.age) } + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age == subquery }), """ SELECT * FROM "readers" WHERE "age" = (SELECT MAX("age") FROM "readers") """) @@ -647,7 +1017,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { do { let subquery = SQLRequest(sql: "SELECT MAX(age + ?) FROM readers", arguments: [1]) XCTAssertEqual( - sql(dbQueue, tableRequest.filter((Col.age + 2) == subquery)), + sql(dbQueue, tableRequest.filter((Columns.age + 2) == subquery)), + """ + SELECT * FROM "readers" WHERE ("age" + 2) = (SELECT MAX(age + 1) FROM readers) + """) + } + + do { + let subquery = SQLRequest(sql: "SELECT MAX(age + ?) FROM readers", arguments: [1]) + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { ($0.age + 2) == subquery }), """ SELECT * FROM "readers" WHERE ("age" + 2) = (SELECT MAX(age + 1) FROM readers) """) @@ -694,112 +1073,202 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age != 10)), + sql(dbQueue, tableRequest.filter(Columns.age != 10)), "SELECT * FROM \"readers\" WHERE \"age\" <> 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age != (10 as Int?))), + sql(dbQueue, tableRequest.filter { $0.age != 10 }), "SELECT * FROM \"readers\" WHERE \"age\" <> 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(10 != Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age != (10 as Int?))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age != (10 as Int?) }), + "SELECT * FROM \"readers\" WHERE \"age\" <> 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(10 != Columns.age)), "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter((10 as Int?) != Col.age)), + sql(dbQueue, tableRequest.filter { 10 != $0.age }), + "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter((10 as Int?) != Columns.age)), + "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { (10 as Int?) != $0.age }), "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 10 != 10 }), "SELECT * FROM \"readers\" WHERE 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age != Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age != Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == 10))), + sql(dbQueue, tableRequest.filter { $0.age != $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Columns.age == 10))), "SELECT * FROM \"readers\" WHERE \"age\" <> 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == (10 as Int?)))), + sql(dbQueue, tableRequest.filter { !($0.age == 10) }), "SELECT * FROM \"readers\" WHERE \"age\" <> 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(10 == Col.age))), + sql(dbQueue, tableRequest.filter(!(Columns.age == (10 as Int?)))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !($0.age == (10 as Int?)) }), + "SELECT * FROM \"readers\" WHERE \"age\" <> 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(10 == Columns.age))), "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!((10 as Int?) == Col.age))), + sql(dbQueue, tableRequest.filter { !(10 == $0.age) }), + "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!((10 as Int?) == Columns.age))), + "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !((10 as Int?) == $0.age) }), "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in !(10 == 10) }), "SELECT * FROM \"readers\" WHERE 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == Col.age))), + sql(dbQueue, tableRequest.filter(!(Columns.age == Columns.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !($0.age == $0.age) }), "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age != nil)), + sql(dbQueue, tableRequest.filter(Columns.age != nil)), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age != DatabaseValue.null)), + sql(dbQueue, tableRequest.filter { $0.age != nil }), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(nil != Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age != DatabaseValue.null)), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(DatabaseValue.null != Col.age)), + sql(dbQueue, tableRequest.filter { $0.age != DatabaseValue.null }), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age != Col.age)), + sql(dbQueue, tableRequest.filter(nil != Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { nil != $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(DatabaseValue.null != Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { DatabaseValue.null != $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age != Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == nil))), - "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == DatabaseValue.null))), - "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(nil == Col.age))), - "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(DatabaseValue.null == Col.age))), - "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == Col.age))), + sql(dbQueue, tableRequest.filter { $0.age != $0.age }), "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name != "B")), + sql(dbQueue, tableRequest.filter(!(Columns.age == nil))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !($0.age == nil) }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Columns.age == DatabaseValue.null))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !($0.age == DatabaseValue.null) }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(nil == Columns.age))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !(nil == $0.age) }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(DatabaseValue.null == Columns.age))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !(DatabaseValue.null == $0.age) }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Columns.age == Columns.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !($0.age == $0.age) }), + "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name != "B")), "SELECT * FROM \"readers\" WHERE \"name\" <> 'B'") XCTAssertEqual( - sql(dbQueue, tableRequest.filter("B" != Col.name)), + sql(dbQueue, tableRequest.filter { $0.name != "B" }), + "SELECT * FROM \"readers\" WHERE \"name\" <> 'B'") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter("B" != Columns.name)), + "SELECT * FROM \"readers\" WHERE 'B' <> \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { "B" != $0.name }), "SELECT * FROM \"readers\" WHERE 'B' <> \"name\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in "B" != "B" }), "SELECT * FROM \"readers\" WHERE 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name != Col.name)), + sql(dbQueue, tableRequest.filter(Columns.name != Columns.name)), "SELECT * FROM \"readers\" WHERE \"name\" <> \"name\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.name == "B"))), + sql(dbQueue, tableRequest.filter { $0.name != $0.name }), + "SELECT * FROM \"readers\" WHERE \"name\" <> \"name\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Columns.name == "B"))), "SELECT * FROM \"readers\" WHERE \"name\" <> 'B'") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!("B" == Col.name))), + sql(dbQueue, tableRequest.filter { !($0.name == "B") }), + "SELECT * FROM \"readers\" WHERE \"name\" <> 'B'") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!("B" == Columns.name))), + "SELECT * FROM \"readers\" WHERE 'B' <> \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !("B" == $0.name) }), "SELECT * FROM \"readers\" WHERE 'B' <> \"name\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in !("B" == "B") }), "SELECT * FROM \"readers\" WHERE 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.name == Col.name))), + sql(dbQueue, tableRequest.filter(!(Columns.name == Columns.name))), "SELECT * FROM \"readers\" WHERE \"name\" <> \"name\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age != true)), + sql(dbQueue, tableRequest.filter { !($0.name == $0.name) }), + "SELECT * FROM \"readers\" WHERE \"name\" <> \"name\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age != true)), "SELECT * FROM \"readers\" WHERE \"age\" <> 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(true != Col.age)), + sql(dbQueue, tableRequest.filter { $0.age != true }), "SELECT * FROM \"readers\" WHERE \"age\" <> 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age != false)), + sql(dbQueue, tableRequest.filter(true != Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" <> 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { true != $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" <> 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age != false)), "SELECT * FROM \"readers\" WHERE \"age\" <> 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(false != Col.age)), + sql(dbQueue, tableRequest.filter { $0.age != false }), + "SELECT * FROM \"readers\" WHERE \"age\" <> 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(false != Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" <> 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { false != $0.age }), "SELECT * FROM \"readers\" WHERE \"age\" <> 0") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in true != true }), @@ -812,16 +1281,28 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT * FROM \"readers\" WHERE 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == true))), + sql(dbQueue, tableRequest.filter(!(Columns.age == true))), "SELECT * FROM \"readers\" WHERE \"age\" <> 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(true == Col.age))), + sql(dbQueue, tableRequest.filter { !($0.age == true) }), "SELECT * FROM \"readers\" WHERE \"age\" <> 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == false))), + sql(dbQueue, tableRequest.filter(!(true == Columns.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !(true == $0.age) }), + "SELECT * FROM \"readers\" WHERE \"age\" <> 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Columns.age == false))), "SELECT * FROM \"readers\" WHERE \"age\" <> 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(false == Col.age))), + sql(dbQueue, tableRequest.filter { !($0.age == false) }), + "SELECT * FROM \"readers\" WHERE \"age\" <> 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(false == Columns.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !(false == $0.age) }), "SELECT * FROM \"readers\" WHERE \"age\" <> 0") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in !(true == true) }), @@ -838,19 +1319,34 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) != "fOo")), + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) != "fOo")), "SELECT * FROM \"readers\" WHERE \"name\" <> 'fOo' COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) != ("fOo" as String?))), + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) != "fOo" }), "SELECT * FROM \"readers\" WHERE \"name\" <> 'fOo' COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) != nil)), + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) != ("fOo" as String?))), + "SELECT * FROM \"readers\" WHERE \"name\" <> 'fOo' COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) != ("fOo" as String?) }), + "SELECT * FROM \"readers\" WHERE \"name\" <> 'fOo' COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) != nil)), "SELECT * FROM \"readers\" WHERE \"name\" IS NOT NULL COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) != DatabaseValue.null)), + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) != nil }), "SELECT * FROM \"readers\" WHERE \"name\" IS NOT NULL COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(collation) != "fOo")), + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) != DatabaseValue.null)), + "SELECT * FROM \"readers\" WHERE \"name\" IS NOT NULL COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) != DatabaseValue.null }), + "SELECT * FROM \"readers\" WHERE \"name\" IS NOT NULL COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.collating(collation) != "fOo")), + "SELECT * FROM \"readers\" WHERE \"name\" <> 'fOo' COLLATE localized_case_insensitive") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.collating(collation) != "fOo" }), "SELECT * FROM \"readers\" WHERE \"name\" <> 'fOo' COLLATE localized_case_insensitive") } @@ -858,32 +1354,56 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == 10))), + sql(dbQueue, tableRequest.filter(!(Columns.age == 10))), "SELECT * FROM \"readers\" WHERE \"age\" <> 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(10 == Col.age))), + sql(dbQueue, tableRequest.filter { !($0.age == 10) }), + "SELECT * FROM \"readers\" WHERE \"age\" <> 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(10 == Columns.age))), + "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !(10 == $0.age) }), "SELECT * FROM \"readers\" WHERE 10 <> \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in !(10 == 10) }), "SELECT * FROM \"readers\" WHERE 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == Col.age))), + sql(dbQueue, tableRequest.filter(!(Columns.age == Columns.age))), "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == nil))), + sql(dbQueue, tableRequest.filter { !($0.age == $0.age) }), + "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Columns.age == nil))), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == DatabaseValue.null))), + sql(dbQueue, tableRequest.filter { !($0.age == nil) }), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(nil == Col.age))), + sql(dbQueue, tableRequest.filter(!(Columns.age == DatabaseValue.null))), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(DatabaseValue.null == Col.age))), + sql(dbQueue, tableRequest.filter { !($0.age == DatabaseValue.null) }), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age == Col.age))), + sql(dbQueue, tableRequest.filter(!(nil == Columns.age))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !(nil == $0.age) }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(DatabaseValue.null == Columns.age))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !(DatabaseValue.null == $0.age) }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Columns.age == Columns.age))), + "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !($0.age == $0.age) }), "SELECT * FROM \"readers\" WHERE \"age\" <> \"age\"") } @@ -891,33 +1411,60 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age === 10)), + sql(dbQueue, tableRequest.filter(Columns.age === 10)), "SELECT * FROM \"readers\" WHERE \"age\" IS 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(10 === Col.age)), + sql(dbQueue, tableRequest.filter { $0.age === 10 }), + "SELECT * FROM \"readers\" WHERE \"age\" IS 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(10 === Columns.age)), "SELECT * FROM \"readers\" WHERE 10 IS \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age === Col.age)), - "SELECT * FROM \"readers\" WHERE \"age\" IS \"age\"") - + sql(dbQueue, tableRequest.filter { 10 === $0.age }), + "SELECT * FROM \"readers\" WHERE 10 IS \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age === nil)), + sql(dbQueue, tableRequest.filter(Columns.age === Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" IS \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age === $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" IS \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age === nil)), "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(nil === Col.age)), + sql(dbQueue, tableRequest.filter { $0.age === nil }), "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age === Col.age)), - "SELECT * FROM \"readers\" WHERE \"age\" IS \"age\"") - + sql(dbQueue, tableRequest.filter(nil === Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name === "B")), + sql(dbQueue, tableRequest.filter { nil === $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age === Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" IS \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age === $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" IS \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name === "B")), "SELECT * FROM \"readers\" WHERE \"name\" IS 'B'") XCTAssertEqual( - sql(dbQueue, tableRequest.filter("B" === Col.name)), + sql(dbQueue, tableRequest.filter { $0.name === "B" }), + "SELECT * FROM \"readers\" WHERE \"name\" IS 'B'") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter("B" === Columns.name)), "SELECT * FROM \"readers\" WHERE 'B' IS \"name\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name === Col.name)), + sql(dbQueue, tableRequest.filter { "B" === $0.name }), + "SELECT * FROM \"readers\" WHERE 'B' IS \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name === Columns.name)), + "SELECT * FROM \"readers\" WHERE \"name\" IS \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name === $0.name }), "SELECT * FROM \"readers\" WHERE \"name\" IS \"name\"") } @@ -925,10 +1472,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) === "fOo")), + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) === "fOo")), "SELECT * FROM \"readers\" WHERE \"name\" IS 'fOo' COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(collation) === "fOo")), + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) === "fOo" }), + "SELECT * FROM \"readers\" WHERE \"name\" IS 'fOo' COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.collating(collation) === "fOo")), + "SELECT * FROM \"readers\" WHERE \"name\" IS 'fOo' COLLATE localized_case_insensitive") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.collating(collation) === "fOo" }), "SELECT * FROM \"readers\" WHERE \"name\" IS 'fOo' COLLATE localized_case_insensitive") } @@ -936,33 +1489,60 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age !== 10)), + sql(dbQueue, tableRequest.filter(Columns.age !== 10)), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(10 !== Col.age)), + sql(dbQueue, tableRequest.filter { $0.age !== 10 }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(10 !== Columns.age)), "SELECT * FROM \"readers\" WHERE 10 IS NOT \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age !== Col.age)), - "SELECT * FROM \"readers\" WHERE \"age\" IS NOT \"age\"") - + sql(dbQueue, tableRequest.filter { 10 !== $0.age }), + "SELECT * FROM \"readers\" WHERE 10 IS NOT \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age !== nil)), + sql(dbQueue, tableRequest.filter(Columns.age !== Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age !== $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age !== nil)), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(nil !== Col.age)), + sql(dbQueue, tableRequest.filter { $0.age !== nil }), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age !== Col.age)), - "SELECT * FROM \"readers\" WHERE \"age\" IS NOT \"age\"") - + sql(dbQueue, tableRequest.filter(nil !== Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name !== "B")), + sql(dbQueue, tableRequest.filter { nil !== $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age !== Columns.age)), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age !== $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name !== "B")), "SELECT * FROM \"readers\" WHERE \"name\" IS NOT 'B'") XCTAssertEqual( - sql(dbQueue, tableRequest.filter("B" !== Col.name)), + sql(dbQueue, tableRequest.filter { $0.name !== "B" }), + "SELECT * FROM \"readers\" WHERE \"name\" IS NOT 'B'") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter("B" !== Columns.name)), "SELECT * FROM \"readers\" WHERE 'B' IS NOT \"name\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name !== Col.name)), + sql(dbQueue, tableRequest.filter { "B" !== $0.name }), + "SELECT * FROM \"readers\" WHERE 'B' IS NOT \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name !== Columns.name)), + "SELECT * FROM \"readers\" WHERE \"name\" IS NOT \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name !== $0.name }), "SELECT * FROM \"readers\" WHERE \"name\" IS NOT \"name\"") } @@ -970,10 +1550,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(.nocase) !== "fOo")), + sql(dbQueue, tableRequest.filter(Columns.name.collating(.nocase) !== "fOo")), "SELECT * FROM \"readers\" WHERE \"name\" IS NOT 'fOo' COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.collating(collation) !== "fOo")), + sql(dbQueue, tableRequest.filter { $0.name.collating(.nocase) !== "fOo" }), + "SELECT * FROM \"readers\" WHERE \"name\" IS NOT 'fOo' COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.collating(collation) !== "fOo")), + "SELECT * FROM \"readers\" WHERE \"name\" IS NOT 'fOo' COLLATE localized_case_insensitive") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.collating(collation) !== "fOo" }), "SELECT * FROM \"readers\" WHERE \"name\" IS NOT 'fOo' COLLATE localized_case_insensitive") } @@ -981,23 +1567,41 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age === 10))), + sql(dbQueue, tableRequest.filter(!(Columns.age === 10))), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(10 === Col.age))), + sql(dbQueue, tableRequest.filter { !($0.age === 10) }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(10 === Columns.age))), "SELECT * FROM \"readers\" WHERE 10 IS NOT \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age === Col.age))), + sql(dbQueue, tableRequest.filter { !(10 === $0.age) }), + "SELECT * FROM \"readers\" WHERE 10 IS NOT \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Columns.age === Columns.age))), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT \"age\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age === nil))), + sql(dbQueue, tableRequest.filter { !($0.age === $0.age) }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT \"age\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Columns.age === nil))), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(nil === Col.age))), + sql(dbQueue, tableRequest.filter { !($0.age === nil) }), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age === Col.age))), + sql(dbQueue, tableRequest.filter(!(nil === Columns.age))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !(nil === $0.age) }), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT NULL") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Columns.age === Columns.age))), + "SELECT * FROM \"readers\" WHERE \"age\" IS NOT \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !($0.age === $0.age) }), "SELECT * FROM \"readers\" WHERE \"age\" IS NOT \"age\"") } @@ -1005,35 +1609,65 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!Col.age)), + sql(dbQueue, tableRequest.filter(!Columns.age)), + "SELECT * FROM \"readers\" WHERE NOT \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !$0.age }), "SELECT * FROM \"readers\" WHERE NOT \"age\"") // Make sure NOT NOT "hack" is available in order to produce 0 or 1 XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(!Col.age))), + sql(dbQueue, tableRequest.filter(!(!Columns.age))), "SELECT * FROM \"readers\" WHERE NOT (NOT \"age\")") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age && true)), + sql(dbQueue, tableRequest.filter { !(!$0.age) }), + "SELECT * FROM \"readers\" WHERE NOT (NOT \"age\")") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age && true)), "SELECT * FROM \"readers\" WHERE \"age\" AND 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(true && Col.age)), + sql(dbQueue, tableRequest.filter { $0.age && true }), + "SELECT * FROM \"readers\" WHERE \"age\" AND 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(true && Columns.age)), "SELECT * FROM \"readers\" WHERE 1 AND \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age || false)), + sql(dbQueue, tableRequest.filter { true && $0.age }), + "SELECT * FROM \"readers\" WHERE 1 AND \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age || false)), "SELECT * FROM \"readers\" WHERE \"age\" OR 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(false || Col.age)), + sql(dbQueue, tableRequest.filter { $0.age || false }), + "SELECT * FROM \"readers\" WHERE \"age\" OR 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(false || Columns.age)), "SELECT * FROM \"readers\" WHERE 0 OR \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age != nil || Col.name == nil)), + sql(dbQueue, tableRequest.filter { false || $0.age }), + "SELECT * FROM \"readers\" WHERE 0 OR \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age != nil || Columns.name == nil)), "SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL) OR (\"name\" IS NULL)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age != nil || Col.name != nil && Col.id != nil)), + sql(dbQueue, tableRequest.filter { $0.age != nil || $0.name == nil }), + "SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL) OR (\"name\" IS NULL)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age != nil || Columns.name != nil && Columns.id != nil)), "SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL) OR ((\"name\" IS NOT NULL) AND (\"id\" IS NOT NULL))") XCTAssertEqual( - sql(dbQueue, tableRequest.filter((Col.age != nil || Col.name != nil) && Col.id != nil)), + sql(dbQueue, tableRequest.filter { $0.age != nil || $0.name != nil && $0.id != nil }), + "SELECT * FROM \"readers\" WHERE (\"age\" IS NOT NULL) OR ((\"name\" IS NOT NULL) AND (\"id\" IS NOT NULL))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter((Columns.age != nil || Columns.name != nil) && Columns.id != nil)), "SELECT * FROM \"readers\" WHERE ((\"age\" IS NOT NULL) OR (\"name\" IS NOT NULL)) AND (\"id\" IS NOT NULL)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!(Col.age > 18) && !(Col.name > "foo"))), + sql(dbQueue, tableRequest.filter { ($0.age != nil || $0.name != nil) && $0.id != nil }), + "SELECT * FROM \"readers\" WHERE ((\"age\" IS NOT NULL) OR (\"name\" IS NOT NULL)) AND (\"id\" IS NOT NULL)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!(Columns.age > 18) && !(Columns.name > "foo"))), + "SELECT * FROM \"readers\" WHERE (NOT (\"age\" > 18)) AND (NOT (\"name\" > 'foo'))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { !($0.age > 18) && !($0.name > "foo") }), "SELECT * FROM \"readers\" WHERE (NOT (\"age\" > 18)) AND (NOT (\"name\" > 'foo'))") } @@ -1053,25 +1687,46 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { sql(dbQueue, tableRequest.filter([false.databaseValue].joined(operator: .and) || false)), "SELECT * FROM \"readers\" WHERE 0 OR 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id == 1].joined(operator: .and))), + sql(dbQueue, tableRequest.filter([Columns.id == 1].joined(operator: .and))), "SELECT * FROM \"readers\" WHERE \"id\" = 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id == 1].joined(operator: .and) || false)), + sql(dbQueue, tableRequest.filter { [$0.id == 1].joined(operator: .and) }), + "SELECT * FROM \"readers\" WHERE \"id\" = 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Columns.id == 1].joined(operator: .and) || false)), "SELECT * FROM \"readers\" WHERE (\"id\" = 1) OR 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil].joined(operator: .and))), + sql(dbQueue, tableRequest.filter { [$0.id == 1].joined(operator: .and) || false }), + "SELECT * FROM \"readers\" WHERE (\"id\" = 1) OR 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Columns.id == 1, Columns.name != nil].joined(operator: .and))), "SELECT * FROM \"readers\" WHERE (\"id\" = 1) AND (\"name\" IS NOT NULL)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil].joined(operator: .and) || false)), + sql(dbQueue, tableRequest.filter { [$0.id == 1, $0.name != nil].joined(operator: .and) }), + "SELECT * FROM \"readers\" WHERE (\"id\" = 1) AND (\"name\" IS NOT NULL)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Columns.id == 1, Columns.name != nil].joined(operator: .and) || false)), "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) AND (\"name\" IS NOT NULL)) OR 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil, Col.age == nil].joined(operator: .and))), + sql(dbQueue, tableRequest.filter { [$0.id == 1, $0.name != nil].joined(operator: .and) || false }), + "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) AND (\"name\" IS NOT NULL)) OR 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Columns.id == 1, Columns.name != nil, Columns.age == nil].joined(operator: .and))), "SELECT * FROM \"readers\" WHERE (\"id\" = 1) AND (\"name\" IS NOT NULL) AND (\"age\" IS NULL)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil, Col.age == nil].joined(operator: .and) || false)), + sql(dbQueue, tableRequest.filter { (columns: Reader.DatabaseComponents) in [columns.id == 1, columns.name != nil, columns.age == nil].joined(operator: .and) }), + "SELECT * FROM \"readers\" WHERE (\"id\" = 1) AND (\"name\" IS NOT NULL) AND (\"age\" IS NULL)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Columns.id == 1, Columns.name != nil, Columns.age == nil].joined(operator: .and) || false)), "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) AND (\"name\" IS NOT NULL) AND (\"age\" IS NULL)) OR 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(![Col.id == 1, Col.name != nil, Col.age == nil].joined(operator: .and))), + sql(dbQueue, tableRequest.filter { (columns: Reader.DatabaseComponents) in [columns.id == 1, columns.name != nil, columns.age == nil].joined(operator: .and) || false }), + "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) AND (\"name\" IS NOT NULL) AND (\"age\" IS NULL)) OR 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(![Columns.id == 1, Columns.name != nil, Columns.age == nil].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE NOT ((\"id\" = 1) AND (\"name\" IS NOT NULL) AND (\"age\" IS NULL))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { (columns: Reader.DatabaseComponents) in ![columns.id == 1, columns.name != nil, columns.age == nil].joined(operator: .and) }), "SELECT * FROM \"readers\" WHERE NOT ((\"id\" = 1) AND (\"name\" IS NOT NULL) AND (\"age\" IS NULL))") } @@ -1091,25 +1746,46 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { sql(dbQueue, tableRequest.filter([true.databaseValue].joined(operator: .or) && true)), "SELECT * FROM \"readers\" WHERE 1 AND 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id == 1].joined(operator: .or))), + sql(dbQueue, tableRequest.filter([Columns.id == 1].joined(operator: .or))), "SELECT * FROM \"readers\" WHERE \"id\" = 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id == 1].joined(operator: .or) && true)), + sql(dbQueue, tableRequest.filter { [$0.id == 1].joined(operator: .or) }), + "SELECT * FROM \"readers\" WHERE \"id\" = 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Columns.id == 1].joined(operator: .or) && true)), "SELECT * FROM \"readers\" WHERE (\"id\" = 1) AND 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil].joined(operator: .or))), + sql(dbQueue, tableRequest.filter { [$0.id == 1].joined(operator: .or) && true }), + "SELECT * FROM \"readers\" WHERE (\"id\" = 1) AND 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Columns.id == 1, Columns.name != nil].joined(operator: .or))), "SELECT * FROM \"readers\" WHERE (\"id\" = 1) OR (\"name\" IS NOT NULL)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil].joined(operator: .or) && true)), + sql(dbQueue, tableRequest.filter { [$0.id == 1, $0.name != nil].joined(operator: .or) }), + "SELECT * FROM \"readers\" WHERE (\"id\" = 1) OR (\"name\" IS NOT NULL)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Columns.id == 1, Columns.name != nil].joined(operator: .or) && true)), "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) OR (\"name\" IS NOT NULL)) AND 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil, Col.age == nil].joined(operator: .or))), + sql(dbQueue, tableRequest.filter { [$0.id == 1, $0.name != nil].joined(operator: .or) && true }), + "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) OR (\"name\" IS NOT NULL)) AND 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Columns.id == 1, Columns.name != nil, Columns.age == nil].joined(operator: .or))), "SELECT * FROM \"readers\" WHERE (\"id\" = 1) OR (\"name\" IS NOT NULL) OR (\"age\" IS NULL)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.id == 1, Col.name != nil, Col.age == nil].joined(operator: .or) && true)), + sql(dbQueue, tableRequest.filter { (columns: Reader.DatabaseComponents) in [columns.id == 1, columns.name != nil, columns.age == nil].joined(operator: .or) }), + "SELECT * FROM \"readers\" WHERE (\"id\" = 1) OR (\"name\" IS NOT NULL) OR (\"age\" IS NULL)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Columns.id == 1, Columns.name != nil, Columns.age == nil].joined(operator: .or) && true)), "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) OR (\"name\" IS NOT NULL) OR (\"age\" IS NULL)) AND 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(![Col.id == 1, Col.name != nil, Col.age == nil].joined(operator: .or))), + sql(dbQueue, tableRequest.filter { (columns: Reader.DatabaseComponents) in [columns.id == 1, columns.name != nil, columns.age == nil].joined(operator: .or) && true }), + "SELECT * FROM \"readers\" WHERE ((\"id\" = 1) OR (\"name\" IS NOT NULL) OR (\"age\" IS NULL)) AND 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(![Columns.id == 1, Columns.name != nil, Columns.age == nil].joined(operator: .or))), + "SELECT * FROM \"readers\" WHERE NOT ((\"id\" = 1) OR (\"name\" IS NOT NULL) OR (\"age\" IS NULL))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { (columns: Reader.DatabaseComponents) in ![columns.id == 1, columns.name != nil, columns.age == nil].joined(operator: .or) }), "SELECT * FROM \"readers\" WHERE NOT ((\"id\" = 1) OR (\"name\" IS NOT NULL) OR (\"age\" IS NULL))") } @@ -1120,23 +1796,41 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(Col.name.capitalized)), + sql(dbQueue, tableRequest.select(Columns.name.capitalized)), "SELECT swiftCapitalizedString(\"name\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(Col.name.lowercased)), + sql(dbQueue, tableRequest.select { $0.name.capitalized }), + "SELECT swiftCapitalizedString(\"name\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(Columns.name.lowercased)), "SELECT swiftLowercaseString(\"name\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(Col.name.uppercased)), - "SELECT swiftUppercaseString(\"name\") FROM \"readers\"") - + sql(dbQueue, tableRequest.select { $0.name.lowercased }), + "SELECT swiftLowercaseString(\"name\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(Col.name.localizedCapitalized)), + sql(dbQueue, tableRequest.select(Columns.name.uppercased)), + "SELECT swiftUppercaseString(\"name\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { $0.name.uppercased }), + "SELECT swiftUppercaseString(\"name\") FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select(Columns.name.localizedCapitalized)), "SELECT swiftLocalizedCapitalizedString(\"name\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(Col.name.localizedLowercased)), + sql(dbQueue, tableRequest.select { $0.name.localizedCapitalized }), + "SELECT swiftLocalizedCapitalizedString(\"name\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(Columns.name.localizedLowercased)), "SELECT swiftLocalizedLowercaseString(\"name\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(Col.name.localizedUppercased)), + sql(dbQueue, tableRequest.select { $0.name.localizedLowercased }), + "SELECT swiftLocalizedLowercaseString(\"name\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(Columns.name.localizedUppercased)), + "SELECT swiftLocalizedUppercaseString(\"name\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { $0.name.localizedUppercased }), "SELECT swiftLocalizedUppercaseString(\"name\") FROM \"readers\"") } @@ -1147,13 +1841,22 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(-Col.age)), + sql(dbQueue, tableRequest.filter(-Columns.age)), "SELECT * FROM \"readers\" WHERE -\"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(-(Col.age + 1))), + sql(dbQueue, tableRequest.filter { -$0.age }), + "SELECT * FROM \"readers\" WHERE -\"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(-(Columns.age + 1))), "SELECT * FROM \"readers\" WHERE -(\"age\" + 1)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(-(-Col.age + 1))), + sql(dbQueue, tableRequest.filter { -($0.age + 1) }), + "SELECT * FROM \"readers\" WHERE -(\"age\" + 1)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(-(-Columns.age + 1))), + "SELECT * FROM \"readers\" WHERE -((-\"age\") + 1)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { -(-$0.age + 1) }), "SELECT * FROM \"readers\" WHERE -((-\"age\") + 1)") } @@ -1161,22 +1864,37 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age - 2)), + sql(dbQueue, tableRequest.filter(Columns.age - 2)), "SELECT * FROM \"readers\" WHERE \"age\" - 2") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(2 - Col.age)), + sql(dbQueue, tableRequest.filter { $0.age - 2 }), + "SELECT * FROM \"readers\" WHERE \"age\" - 2") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(2 - Columns.age)), + "SELECT * FROM \"readers\" WHERE 2 - \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 2 - $0.age }), "SELECT * FROM \"readers\" WHERE 2 - \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 2 - 2 }), "SELECT * FROM \"readers\" WHERE 0") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age - Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age - Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" - \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter((Col.age - Col.age) - 1)), + sql(dbQueue, tableRequest.filter { $0.age - $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" - \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter((Columns.age - Columns.age) - 1)), "SELECT * FROM \"readers\" WHERE (\"age\" - \"age\") - 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(1 - [Col.age > 1, Col.age == nil].joined(operator: .and))), + sql(dbQueue, tableRequest.filter { ($0.age - $0.age) - 1 }), + "SELECT * FROM \"readers\" WHERE (\"age\" - \"age\") - 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(1 - [Columns.age > 1, Columns.age == nil].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE 1 - ((\"age\" > 1) AND (\"age\" IS NULL))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 1 - [$0.age > 1, $0.age == nil].joined(operator: .and) }), "SELECT * FROM \"readers\" WHERE 1 - ((\"age\" > 1) AND (\"age\" IS NULL))") } @@ -1184,22 +1902,37 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age + 2)), + sql(dbQueue, tableRequest.filter(Columns.age + 2)), "SELECT * FROM \"readers\" WHERE \"age\" + 2") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(2 + Col.age)), + sql(dbQueue, tableRequest.filter { $0.age + 2 }), + "SELECT * FROM \"readers\" WHERE \"age\" + 2") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(2 + Columns.age)), + "SELECT * FROM \"readers\" WHERE 2 + \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 2 + $0.age }), "SELECT * FROM \"readers\" WHERE 2 + \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 2 + 2 }), "SELECT * FROM \"readers\" WHERE 4") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age + Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age + Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" + \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(1 + (Col.age + Col.age))), + sql(dbQueue, tableRequest.filter { $0.age + $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" + \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(1 + (Columns.age + Columns.age))), "SELECT * FROM \"readers\" WHERE 1 + (\"age\" + \"age\")") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(1 + [Col.age > 1, Col.age == nil].joined(operator: .and))), + sql(dbQueue, tableRequest.filter { 1 + ($0.age + $0.age) }), + "SELECT * FROM \"readers\" WHERE 1 + (\"age\" + \"age\")") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(1 + [Columns.age > 1, Columns.age == nil].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE 1 + ((\"age\" > 1) AND (\"age\" IS NULL))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 1 + [$0.age > 1, $0.age == nil].joined(operator: .and) }), "SELECT * FROM \"readers\" WHERE 1 + ((\"age\" > 1) AND (\"age\" IS NULL))") } @@ -1211,39 +1944,64 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT 0 FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select([Col.age, Col.age].joined(operator: .add))), + sql(dbQueue, tableRequest.select([Columns.age, Columns.age].joined(operator: .add))), "SELECT \"age\" + \"age\" FROM \"readers\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.select([Col.age, 2.databaseValue, Col.age].joined(operator: .add))), + sql(dbQueue, tableRequest.select { [$0.age, $0.age].joined(operator: .add) }), + "SELECT \"age\" + \"age\" FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Columns.age, 2.databaseValue, Columns.age].joined(operator: .add))), + "SELECT \"age\" + 2 + \"age\" FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { [$0.age, 2.databaseValue, $0.age].joined(operator: .add) }), "SELECT \"age\" + 2 + \"age\" FROM \"readers\"") // Not flattened XCTAssertEqual( sql(dbQueue, tableRequest.select([ - [Col.age, 1.databaseValue].joined(operator: .add), - [2.databaseValue, Col.age].joined(operator: .add), + [Columns.age, 1.databaseValue].joined(operator: .add), + [2.databaseValue, Columns.age].joined(operator: .add), ].joined(operator: .add))), "SELECT (\"age\" + 1) + (2 + \"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { [ + [$0.age, 1.databaseValue].joined(operator: .add), + [2.databaseValue, $0.age].joined(operator: .add), + ].joined(operator: .add) + }), + "SELECT (\"age\" + 1) + (2 + \"age\") FROM \"readers\"") } func testInfixMultiplyOperator() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age * 2)), + sql(dbQueue, tableRequest.filter(Columns.age * 2)), "SELECT * FROM \"readers\" WHERE \"age\" * 2") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(2 * Col.age)), + sql(dbQueue, tableRequest.filter { $0.age * 2 }), + "SELECT * FROM \"readers\" WHERE \"age\" * 2") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(2 * Columns.age)), + "SELECT * FROM \"readers\" WHERE 2 * \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 2 * $0.age }), "SELECT * FROM \"readers\" WHERE 2 * \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 2 * 2 }), "SELECT * FROM \"readers\" WHERE 4") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age * Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age * Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" * \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(2 * (Col.age * Col.age))), + sql(dbQueue, tableRequest.filter { $0.age * $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" * \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(2 * (Columns.age * Columns.age))), + "SELECT * FROM \"readers\" WHERE 2 * (\"age\" * \"age\")") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 2 * ($0.age * $0.age) }), "SELECT * FROM \"readers\" WHERE 2 * (\"age\" * \"age\")") } @@ -1255,39 +2013,64 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT 1 FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select([Col.age, Col.age].joined(operator: .multiply))), + sql(dbQueue, tableRequest.select([Columns.age, Columns.age].joined(operator: .multiply))), "SELECT \"age\" * \"age\" FROM \"readers\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.select([Col.age, 2.databaseValue, Col.age].joined(operator: .multiply))), + sql(dbQueue, tableRequest.select { [$0.age, $0.age].joined(operator: .multiply) }), + "SELECT \"age\" * \"age\" FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Columns.age, 2.databaseValue, Columns.age].joined(operator: .multiply))), + "SELECT \"age\" * 2 * \"age\" FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { [$0.age, 2.databaseValue, $0.age].joined(operator: .multiply) }), "SELECT \"age\" * 2 * \"age\" FROM \"readers\"") // Not flattened XCTAssertEqual( sql(dbQueue, tableRequest.select([ - [Col.age, 1.databaseValue].joined(operator: .multiply), - [2.databaseValue, Col.age].joined(operator: .multiply), + [Columns.age, 1.databaseValue].joined(operator: .multiply), + [2.databaseValue, Columns.age].joined(operator: .multiply), ].joined(operator: .multiply))), "SELECT (\"age\" * 1) * (2 * \"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { [ + [$0.age, 1.databaseValue].joined(operator: .multiply), + [2.databaseValue, $0.age].joined(operator: .multiply), + ].joined(operator: .multiply) + }), + "SELECT (\"age\" * 1) * (2 * \"age\") FROM \"readers\"") } func testInfixDivideOperator() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age / 2)), + sql(dbQueue, tableRequest.filter(Columns.age / 2)), "SELECT * FROM \"readers\" WHERE \"age\" / 2") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(2 / Col.age)), + sql(dbQueue, tableRequest.filter { $0.age / 2 }), + "SELECT * FROM \"readers\" WHERE \"age\" / 2") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(2 / Columns.age)), + "SELECT * FROM \"readers\" WHERE 2 / \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 2 / $0.age }), "SELECT * FROM \"readers\" WHERE 2 / \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 2 / 2 }), "SELECT * FROM \"readers\" WHERE 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age / Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age / Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" / \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(1 / (Col.age / Col.age))), + sql(dbQueue, tableRequest.filter { $0.age / $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" / \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(1 / (Columns.age / Columns.age))), + "SELECT * FROM \"readers\" WHERE 1 / (\"age\" / \"age\")") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 1 / ($0.age / $0.age) }), "SELECT * FROM \"readers\" WHERE 1 / (\"age\" / \"age\")") } @@ -1296,17 +2079,29 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { // Int / Double XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age / 2.0)), + sql(dbQueue, tableRequest.filter(Columns.age / 2.0)), + "SELECT * FROM \"readers\" WHERE \"age\" / 2.0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age / 2.0 }), "SELECT * FROM \"readers\" WHERE \"age\" / 2.0") // Double / Int XCTAssertEqual( - sql(dbQueue, tableRequest.filter(2.0 / Col.age)), + sql(dbQueue, tableRequest.filter(2.0 / Columns.age)), "SELECT * FROM \"readers\" WHERE 2.0 / \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age + 2 * 5)), + sql(dbQueue, tableRequest.filter { 2.0 / $0.age }), + "SELECT * FROM \"readers\" WHERE 2.0 / \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age + 2 * 5)), "SELECT * FROM \"readers\" WHERE \"age\" + 10") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age * 2 + 5)), + sql(dbQueue, tableRequest.filter { $0.age + 2 * 5 }), + "SELECT * FROM \"readers\" WHERE \"age\" + 10") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age * 2 + 5)), + "SELECT * FROM \"readers\" WHERE (\"age\" * 2) + 5") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age * 2 + 5 }), "SELECT * FROM \"readers\" WHERE (\"age\" * 2) + 5") } @@ -1317,13 +2112,22 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(~Col.age)), + sql(dbQueue, tableRequest.filter(~Columns.age)), "SELECT * FROM \"readers\" WHERE ~\"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(~(Col.age + 1))), + sql(dbQueue, tableRequest.filter { ~$0.age }), + "SELECT * FROM \"readers\" WHERE ~\"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(~(Columns.age + 1))), "SELECT * FROM \"readers\" WHERE ~(\"age\" + 1)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(~(~Col.age + 1))), + sql(dbQueue, tableRequest.filter { ~($0.age + 1) }), + "SELECT * FROM \"readers\" WHERE ~(\"age\" + 1)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(~(~Columns.age + 1))), + "SELECT * FROM \"readers\" WHERE ~((~\"age\") + 1)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { ~(~$0.age + 1) }), "SELECT * FROM \"readers\" WHERE ~((~\"age\") + 1)") } @@ -1331,22 +2135,37 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age << 2)), + sql(dbQueue, tableRequest.filter(Columns.age << 2)), "SELECT * FROM \"readers\" WHERE \"age\" << 2") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(2 << Col.age)), + sql(dbQueue, tableRequest.filter { $0.age << 2 }), + "SELECT * FROM \"readers\" WHERE \"age\" << 2") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(2 << Columns.age)), + "SELECT * FROM \"readers\" WHERE 2 << \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 2 << $0.age }), "SELECT * FROM \"readers\" WHERE 2 << \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 2 << 2 }), "SELECT * FROM \"readers\" WHERE 8") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age << Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age << Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" << \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter((Col.age << Col.age) << 1)), + sql(dbQueue, tableRequest.filter { $0.age << $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" << \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter((Columns.age << Columns.age) << 1)), "SELECT * FROM \"readers\" WHERE (\"age\" << \"age\") << 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(1 << [Col.age > 1, Col.age == nil].joined(operator: .and))), + sql(dbQueue, tableRequest.filter { ($0.age << $0.age) << 1 }), + "SELECT * FROM \"readers\" WHERE (\"age\" << \"age\") << 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(1 << [Columns.age > 1, Columns.age == nil].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE 1 << ((\"age\" > 1) AND (\"age\" IS NULL))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 1 << [$0.age > 1, $0.age == nil].joined(operator: .and) }), "SELECT * FROM \"readers\" WHERE 1 << ((\"age\" > 1) AND (\"age\" IS NULL))") } @@ -1354,22 +2173,37 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age >> 2)), + sql(dbQueue, tableRequest.filter(Columns.age >> 2)), "SELECT * FROM \"readers\" WHERE \"age\" >> 2") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(2 >> Col.age)), + sql(dbQueue, tableRequest.filter { $0.age >> 2 }), + "SELECT * FROM \"readers\" WHERE \"age\" >> 2") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(2 >> Columns.age)), + "SELECT * FROM \"readers\" WHERE 2 >> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 2 >> $0.age }), "SELECT * FROM \"readers\" WHERE 2 >> \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 8 >> 2 }), "SELECT * FROM \"readers\" WHERE 2") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age >> Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age >> Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" >> \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter((Col.age >> Col.age) >> 1)), + sql(dbQueue, tableRequest.filter { $0.age >> $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" >> \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter((Columns.age >> Columns.age) >> 1)), "SELECT * FROM \"readers\" WHERE (\"age\" >> \"age\") >> 1") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(1 >> [Col.age > 1, Col.age == nil].joined(operator: .and))), + sql(dbQueue, tableRequest.filter { ($0.age >> $0.age) >> 1 }), + "SELECT * FROM \"readers\" WHERE (\"age\" >> \"age\") >> 1") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(1 >> [Columns.age > 1, Columns.age == nil].joined(operator: .and))), + "SELECT * FROM \"readers\" WHERE 1 >> ((\"age\" > 1) AND (\"age\" IS NULL))") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 1 >> [$0.age > 1, $0.age == nil].joined(operator: .and) }), "SELECT * FROM \"readers\" WHERE 1 >> ((\"age\" > 1) AND (\"age\" IS NULL))") } @@ -1377,19 +2211,31 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age & 2)), + sql(dbQueue, tableRequest.filter(Columns.age & 2)), "SELECT * FROM \"readers\" WHERE \"age\" & 2") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(2 & Col.age)), + sql(dbQueue, tableRequest.filter { $0.age & 2 }), + "SELECT * FROM \"readers\" WHERE \"age\" & 2") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(2 & Columns.age)), + "SELECT * FROM \"readers\" WHERE 2 & \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 2 & $0.age }), "SELECT * FROM \"readers\" WHERE 2 & \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 2 & 2 }), "SELECT * FROM \"readers\" WHERE 2") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age & Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age & Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" & \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(2 & (Col.age & Col.age))), + sql(dbQueue, tableRequest.filter { $0.age & $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" & \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(2 & (Columns.age & Columns.age))), + "SELECT * FROM \"readers\" WHERE 2 & \"age\" & \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 2 & ($0.age & $0.age) }), "SELECT * FROM \"readers\" WHERE 2 & \"age\" & \"age\"") } @@ -1401,39 +2247,64 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT -1 FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select([Col.age, Col.age].joined(operator: .bitwiseAnd))), + sql(dbQueue, tableRequest.select([Columns.age, Columns.age].joined(operator: .bitwiseAnd))), "SELECT \"age\" & \"age\" FROM \"readers\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.select([Col.age, 2.databaseValue, Col.age].joined(operator: .bitwiseAnd))), + sql(dbQueue, tableRequest.select { [$0.age, $0.age].joined(operator: .bitwiseAnd) }), + "SELECT \"age\" & \"age\" FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Columns.age, 2.databaseValue, Columns.age].joined(operator: .bitwiseAnd))), + "SELECT \"age\" & 2 & \"age\" FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { [$0.age, 2.databaseValue, $0.age].joined(operator: .bitwiseAnd) }), "SELECT \"age\" & 2 & \"age\" FROM \"readers\"") // Flattened XCTAssertEqual( sql(dbQueue, tableRequest.select([ - [Col.age, 1.databaseValue].joined(operator: .bitwiseAnd), - [2.databaseValue, Col.age].joined(operator: .bitwiseAnd), + [Columns.age, 1.databaseValue].joined(operator: .bitwiseAnd), + [2.databaseValue, Columns.age].joined(operator: .bitwiseAnd), ].joined(operator: .bitwiseAnd))), "SELECT \"age\" & 1 & 2 & \"age\" FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { [ + [$0.age, 1.databaseValue].joined(operator: .bitwiseAnd), + [2.databaseValue, $0.age].joined(operator: .bitwiseAnd), + ].joined(operator: .bitwiseAnd) + }), + "SELECT \"age\" & 1 & 2 & \"age\" FROM \"readers\"") } func testInfixBitwiseOrOperator() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age | 2)), + sql(dbQueue, tableRequest.filter(Columns.age | 2)), "SELECT * FROM \"readers\" WHERE \"age\" | 2") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(2 | Col.age)), + sql(dbQueue, tableRequest.filter { $0.age | 2 }), + "SELECT * FROM \"readers\" WHERE \"age\" | 2") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(2 | Columns.age)), + "SELECT * FROM \"readers\" WHERE 2 | \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 2 | $0.age }), "SELECT * FROM \"readers\" WHERE 2 | \"age\"") XCTAssertEqual( sql(dbQueue, tableRequest.filterWhenConnected { _ in 2 | 2 }), "SELECT * FROM \"readers\" WHERE 2") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age | Col.age)), + sql(dbQueue, tableRequest.filter(Columns.age | Columns.age)), "SELECT * FROM \"readers\" WHERE \"age\" | \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(2 | (Col.age | Col.age))), + sql(dbQueue, tableRequest.filter { $0.age | $0.age }), + "SELECT * FROM \"readers\" WHERE \"age\" | \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(2 | (Columns.age | Columns.age))), + "SELECT * FROM \"readers\" WHERE 2 | \"age\" | \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { 2 | ($0.age | $0.age) }), "SELECT * FROM \"readers\" WHERE 2 | \"age\" | \"age\"") } @@ -1445,20 +2316,33 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { "SELECT 0 FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select([Col.age, Col.age].joined(operator: .bitwiseOr))), + sql(dbQueue, tableRequest.select([Columns.age, Columns.age].joined(operator: .bitwiseOr))), "SELECT \"age\" | \"age\" FROM \"readers\"") - XCTAssertEqual( - sql(dbQueue, tableRequest.select([Col.age, 2.databaseValue, Col.age].joined(operator: .bitwiseOr))), + sql(dbQueue, tableRequest.select { [$0.age, $0.age].joined(operator: .bitwiseOr) }), + "SELECT \"age\" | \"age\" FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Columns.age, 2.databaseValue, Columns.age].joined(operator: .bitwiseOr))), + "SELECT \"age\" | 2 | \"age\" FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { [$0.age, 2.databaseValue, $0.age].joined(operator: .bitwiseOr) }), "SELECT \"age\" | 2 | \"age\" FROM \"readers\"") // Flattened XCTAssertEqual( sql(dbQueue, tableRequest.select([ - [Col.age, 1.databaseValue].joined(operator: .bitwiseOr), - [2.databaseValue, Col.age].joined(operator: .bitwiseOr), + [Columns.age, 1.databaseValue].joined(operator: .bitwiseOr), + [2.databaseValue, Columns.age].joined(operator: .bitwiseOr), ].joined(operator: .bitwiseOr))), "SELECT \"age\" | 1 | 2 | \"age\" FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { [ + [$0.age, 1.databaseValue].joined(operator: .bitwiseOr), + [2.databaseValue, $0.age].joined(operator: .bitwiseOr), + ].joined(operator: .bitwiseOr) + }), + "SELECT \"age\" | 1 | 2 | \"age\" FROM \"readers\"") } // MARK: - IFNULL expression @@ -1467,10 +2351,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age ?? 2)), + sql(dbQueue, tableRequest.filter(Columns.age ?? 2)), "SELECT * FROM \"readers\" WHERE IFNULL(\"age\", 2)") XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.age ?? Col.age)), + sql(dbQueue, tableRequest.filter { $0.age ?? 2 }), + "SELECT * FROM \"readers\" WHERE IFNULL(\"age\", 2)") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.age ?? Columns.age)), + "SELECT * FROM \"readers\" WHERE IFNULL(\"age\", \"age\")") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.age ?? $0.age }), "SELECT * FROM \"readers\" WHERE IFNULL(\"age\", \"age\")") } @@ -1481,16 +2371,28 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(count(Col.age))), + sql(dbQueue, tableRequest.select(count(Columns.age))), "SELECT COUNT(\"age\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(count(Col.age ?? 0))), + sql(dbQueue, tableRequest.select { count($0.age) }), + "SELECT COUNT(\"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(count(Columns.age ?? 0))), "SELECT COUNT(IFNULL(\"age\", 0)) FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(count(distinct: Col.age))), + sql(dbQueue, tableRequest.select { count($0.age ?? 0) }), + "SELECT COUNT(IFNULL(\"age\", 0)) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(count(distinct: Columns.age))), "SELECT COUNT(DISTINCT \"age\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(count(distinct: Col.age / Col.age))), + sql(dbQueue, tableRequest.select { count(distinct: $0.age) }), + "SELECT COUNT(DISTINCT \"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(count(distinct: Columns.age / Columns.age))), + "SELECT COUNT(DISTINCT \"age\" / \"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { count(distinct: $0.age / $0.age) }), "SELECT COUNT(DISTINCT \"age\" / \"age\") FROM \"readers\"") } @@ -1498,21 +2400,27 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(average(Col.age))), + sql(dbQueue, tableRequest.select(average(Columns.age))), "SELECT AVG(\"age\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(average(Col.age / 2))), + sql(dbQueue, tableRequest.select { average($0.age) }), + "SELECT AVG(\"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(average(Columns.age / 2))), + "SELECT AVG(\"age\" / 2) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { average($0.age / 2) }), "SELECT AVG(\"age\" / 2) FROM \"readers\"") } 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 - guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else { + guard #available(iOS 14, macOS 10.16, tvOS 14, *) else { throw XCTSkip("FILTER clause on aggregate functions is not available") } #endif @@ -1520,10 +2428,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(average(Col.age, filter: Col.age > 0))), + sql(dbQueue, tableRequest.select(average(Columns.age, filter: Columns.age > 0))), "SELECT AVG(\"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(average(Col.age / 2, filter: Col.age > 0))), + sql(dbQueue, tableRequest.select { average($0.age, filter: $0.age > 0) }), + "SELECT AVG(\"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(average(Columns.age / 2, filter: Columns.age > 0))), + "SELECT AVG(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { average($0.age / 2, filter: $0.age > 0) }), "SELECT AVG(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"") } @@ -1531,37 +2445,88 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(cast(Col.name, as: .blob))), + sql(dbQueue, tableRequest.select(cast(Columns.name, as: .blob))), "SELECT CAST(\"name\" AS BLOB) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { cast($0.name, as: .blob) }), + "SELECT CAST(\"name\" AS BLOB) FROM \"readers\"") + } + + func testCoalesceExpression() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.select(coalesce([]))), + "SELECT NULL FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select(coalesce([Columns.name]))), + "SELECT \"name\" FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { coalesce([$0.name]) }), + "SELECT \"name\" FROM \"readers\"") + + XCTAssertEqual( + sql(dbQueue, tableRequest.select(coalesce([Columns.name, Columns.age]))), + "SELECT COALESCE(\"name\", \"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { coalesce([$0.name, $0.age]) }), + "SELECT COALESCE(\"name\", \"age\") FROM \"readers\"") } func testLengthExpression() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(length(Col.name))), + sql(dbQueue, tableRequest.select(length(Columns.name))), + "SELECT LENGTH(\"name\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { length($0.name) }), "SELECT LENGTH(\"name\") FROM \"readers\"") } - func testMinExpression() throws { + func testMultiArgumentMinExpression() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(min(Col.age))), + sql(dbQueue, tableRequest.select(min(Columns.age, 1000))), + "SELECT MIN(\"age\", 1000) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { min($0.age, 1000) }), + "SELECT MIN(\"age\", 1000) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(min(Columns.age, 1000, Columns.id))), + "SELECT MIN(\"age\", 1000, \"id\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { min($0.age, 1000, $0.id) }), + "SELECT MIN(\"age\", 1000, \"id\") FROM \"readers\"") + } + + func testAggregateMinExpression() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.select(min(Columns.age))), "SELECT MIN(\"age\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(min(Col.age / 2))), + sql(dbQueue, tableRequest.select { min($0.age) }), + "SELECT MIN(\"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(min(Columns.age / 2))), + "SELECT MIN(\"age\" / 2) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { min($0.age / 2) }), "SELECT MIN(\"age\" / 2) FROM \"readers\"") } - func testMinExpression_filter() throws { + func testAggregateMinExpression_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 - guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else { + guard #available(iOS 14, macOS 10.16, tvOS 14, *) else { throw XCTSkip("FILTER clause on aggregate functions is not available") } #endif @@ -1569,32 +2534,61 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(min(Col.age, filter: Col.age > 0))), + sql(dbQueue, tableRequest.select(min(Columns.age, filter: Columns.age > 0))), "SELECT MIN(\"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(min(Col.age / 2, filter: Col.age > 0))), + sql(dbQueue, tableRequest.select { min($0.age, filter: $0.age > 0) }), + "SELECT MIN(\"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(min(Columns.age / 2, filter: Columns.age > 0))), + "SELECT MIN(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { min($0.age / 2, filter: $0.age > 0) }), "SELECT MIN(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"") } - func testMaxExpression() throws { + func testMultiArgumentMaxExpression() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(max(Col.age))), + sql(dbQueue, tableRequest.select(max(Columns.age, 1000))), + "SELECT MAX(\"age\", 1000) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { max($0.age, 1000) }), + "SELECT MAX(\"age\", 1000) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(max(Columns.age, 1000, Columns.id))), + "SELECT MAX(\"age\", 1000, \"id\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { max($0.age, 1000, $0.id) }), + "SELECT MAX(\"age\", 1000, \"id\") FROM \"readers\"") + } + + func testAggregateMaxExpression() throws { + let dbQueue = try makeDatabaseQueue() + + XCTAssertEqual( + sql(dbQueue, tableRequest.select(max(Columns.age))), "SELECT MAX(\"age\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(max(Col.age / 2))), + sql(dbQueue, tableRequest.select { max($0.age) }), + "SELECT MAX(\"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(max(Columns.age / 2))), + "SELECT MAX(\"age\" / 2) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { max($0.age / 2) }), "SELECT MAX(\"age\" / 2) FROM \"readers\"") } - func testMaxExpression_filter() throws { + func testAggregateMaxExpression_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 - guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else { + guard #available(iOS 14, macOS 10.16, tvOS 14, *) else { throw XCTSkip("FILTER clause on aggregate functions is not available") } #endif @@ -1602,10 +2596,16 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(max(Col.age, filter: Col.age < 0))), + sql(dbQueue, tableRequest.select(max(Columns.age, filter: Columns.age < 0))), "SELECT MAX(\"age\") FILTER (WHERE \"age\" < 0) FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(max(Col.age / 2, filter: Col.age < 0))), + sql(dbQueue, tableRequest.select { max($0.age, filter: $0.age < 0) }), + "SELECT MAX(\"age\") FILTER (WHERE \"age\" < 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(max(Columns.age / 2, filter: Columns.age < 0))), + "SELECT MAX(\"age\" / 2) FILTER (WHERE \"age\" < 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { max($0.age / 2, filter: $0.age < 0) }), "SELECT MAX(\"age\" / 2) FILTER (WHERE \"age\" < 0) FROM \"readers\"") } @@ -1613,21 +2613,27 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(sum(Col.age))), + sql(dbQueue, tableRequest.select(sum(Columns.age))), "SELECT SUM(\"age\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(sum(Col.age / 2))), + sql(dbQueue, tableRequest.select { sum($0.age) }), + "SELECT SUM(\"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(sum(Columns.age / 2))), + "SELECT SUM(\"age\" / 2) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { sum($0.age / 2) }), "SELECT SUM(\"age\" / 2) FROM \"readers\"") } 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 - guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else { + guard #available(iOS 14, macOS 10.16, tvOS 14, *) else { throw XCTSkip("FILTER clause on aggregate functions is not available") } #endif @@ -1635,33 +2641,51 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(sum(Col.age, filter: Col.age > 0))), + sql(dbQueue, tableRequest.select(sum(Columns.age, filter: Columns.age > 0))), "SELECT SUM(\"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(sum(Col.age / 2, filter: Col.age > 0))), + sql(dbQueue, tableRequest.select { sum($0.age, filter: $0.age > 0) }), + "SELECT SUM(\"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(sum(Columns.age / 2, filter: Columns.age > 0))), + "SELECT SUM(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { sum($0.age / 2, filter: $0.age > 0) }), "SELECT SUM(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"") } #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") } let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(sum(Col.age, orderBy: Col.age))), + sql(dbQueue, tableRequest.select(sum(Columns.age, orderBy: Columns.age))), "SELECT SUM(\"age\" ORDER BY \"age\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(sum(Col.age / 2, orderBy: Col.age.desc))), + sql(dbQueue, tableRequest.select { sum($0.age, orderBy: $0.age) }), + "SELECT SUM(\"age\" ORDER BY \"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(sum(Columns.age / 2, orderBy: Columns.age.desc))), "SELECT SUM(\"age\" / 2 ORDER BY \"age\" DESC) FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(sum(Col.age, orderBy: Col.age, filter: Col.age > 0))), + sql(dbQueue, tableRequest.select { sum($0.age / 2, orderBy: $0.age.desc) }), + "SELECT SUM(\"age\" / 2 ORDER BY \"age\" DESC) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(sum(Columns.age, orderBy: Columns.age, filter: Columns.age > 0))), "SELECT SUM(\"age\" ORDER BY \"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(sum(Col.age / 2, orderBy: Col.age.desc, filter: Col.age > 0))), + sql(dbQueue, tableRequest.select { sum($0.age, orderBy: $0.age, filter: $0.age > 0) }), + "SELECT SUM(\"age\" ORDER BY \"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(sum(Columns.age / 2, orderBy: Columns.age.desc, filter: Columns.age > 0))), + "SELECT SUM(\"age\" / 2 ORDER BY \"age\" DESC) FILTER (WHERE \"age\" > 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { sum($0.age / 2, orderBy: $0.age.desc, filter: $0.age > 0) }), "SELECT SUM(\"age\" / 2 ORDER BY \"age\" DESC) FILTER (WHERE \"age\" > 0) FROM \"readers\"") } #endif @@ -1670,21 +2694,27 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(total(Col.age))), + sql(dbQueue, tableRequest.select(total(Columns.age))), "SELECT TOTAL(\"age\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(total(Col.age / 2))), + sql(dbQueue, tableRequest.select { total($0.age) }), + "SELECT TOTAL(\"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(total(Columns.age / 2))), + "SELECT TOTAL(\"age\" / 2) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { total($0.age / 2) }), "SELECT TOTAL(\"age\" / 2) FROM \"readers\"") } 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 - guard #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) else { + guard #available(iOS 14, macOS 10.16, tvOS 14, *) else { throw XCTSkip("FILTER clause on aggregate functions is not available") } #endif @@ -1692,33 +2722,51 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(total(Col.age, filter: Col.age > 0))), + sql(dbQueue, tableRequest.select(total(Columns.age, filter: Columns.age > 0))), "SELECT TOTAL(\"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(total(Col.age / 2, filter: Col.age > 0))), + sql(dbQueue, tableRequest.select { total($0.age, filter: $0.age > 0) }), + "SELECT TOTAL(\"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(total(Columns.age / 2, filter: Columns.age > 0))), + "SELECT TOTAL(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { total($0.age / 2, filter: $0.age > 0) }), "SELECT TOTAL(\"age\" / 2) FILTER (WHERE \"age\" > 0) FROM \"readers\"") } #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") } let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(total(Col.age, orderBy: Col.age))), + sql(dbQueue, tableRequest.select(total(Columns.age, orderBy: Columns.age))), "SELECT TOTAL(\"age\" ORDER BY \"age\") FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(total(Col.age / 2, orderBy: Col.age.desc))), + sql(dbQueue, tableRequest.select { total($0.age, orderBy: $0.age) }), + "SELECT TOTAL(\"age\" ORDER BY \"age\") FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(total(Columns.age / 2, orderBy: Columns.age.desc))), "SELECT TOTAL(\"age\" / 2 ORDER BY \"age\" DESC) FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(total(Col.age, orderBy: Col.age, filter: Col.age > 0))), + sql(dbQueue, tableRequest.select { total($0.age / 2, orderBy: $0.age.desc) }), + "SELECT TOTAL(\"age\" / 2 ORDER BY \"age\" DESC) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(total(Columns.age, orderBy: Columns.age, filter: Columns.age > 0))), "SELECT TOTAL(\"age\" ORDER BY \"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.select(total(Col.age / 2, orderBy: Col.age.desc, filter: Col.age > 0))), + sql(dbQueue, tableRequest.select { total($0.age, orderBy: $0.age, filter: $0.age > 0) }), + "SELECT TOTAL(\"age\" ORDER BY \"age\") FILTER (WHERE \"age\" > 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select(total(Columns.age / 2, orderBy: Columns.age.desc, filter: Columns.age > 0))), + "SELECT TOTAL(\"age\" / 2 ORDER BY \"age\" DESC) FILTER (WHERE \"age\" > 0) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { total($0.age / 2, orderBy: $0.age.desc, filter: $0.age > 0) }), "SELECT TOTAL(\"age\" / 2 ORDER BY \"age\" DESC) FILTER (WHERE \"age\" > 0) FROM \"readers\"") } #endif @@ -1729,35 +2777,59 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.like("%foo"))), + sql(dbQueue, tableRequest.filter(Columns.name.like("%foo"))), "SELECT * FROM \"readers\" WHERE \"name\" LIKE '%foo'") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!Col.name.like("%foo"))), + sql(dbQueue, tableRequest.filter { $0.name.like("%foo") }), + "SELECT * FROM \"readers\" WHERE \"name\" LIKE '%foo'") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!Columns.name.like("%foo"))), "SELECT * FROM \"readers\" WHERE \"name\" NOT LIKE '%foo'") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.like("%foo") == true)), + sql(dbQueue, tableRequest.filter { !$0.name.like("%foo") }), + "SELECT * FROM \"readers\" WHERE \"name\" NOT LIKE '%foo'") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.like("%foo") == true)), "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo') = 1") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.like("%foo") == false)), + sql(dbQueue, tableRequest.filter { $0.name.like("%foo") == true }), + "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo') = 1") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.like("%foo") == false)), "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo') = 0") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.like("%foo", escape: "\\"))), + sql(dbQueue, tableRequest.filter { $0.name.like("%foo") == false }), + "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo') = 0") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.like("%foo", escape: "\\"))), "SELECT * FROM \"readers\" WHERE \"name\" LIKE '%foo' ESCAPE '\\'") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(!Col.name.like("%foo", escape: "\\"))), + sql(dbQueue, tableRequest.filter { $0.name.like("%foo", escape: "\\") }), + "SELECT * FROM \"readers\" WHERE \"name\" LIKE '%foo' ESCAPE '\\'") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(!Columns.name.like("%foo", escape: "\\"))), "SELECT * FROM \"readers\" WHERE \"name\" NOT LIKE '%foo' ESCAPE '\\'") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.like("%foo", escape: "\\") == true)), + sql(dbQueue, tableRequest.filter { !$0.name.like("%foo", escape: "\\") }), + "SELECT * FROM \"readers\" WHERE \"name\" NOT LIKE '%foo' ESCAPE '\\'") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.like("%foo", escape: "\\") == true)), "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo' ESCAPE '\\') = 1") - XCTAssertEqual( - sql(dbQueue, tableRequest.filter(Col.name.like("%foo", escape: "\\") == false)), + sql(dbQueue, tableRequest.filter { $0.name.like("%foo", escape: "\\") == true }), + "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo' ESCAPE '\\') = 1") + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter(Columns.name.like("%foo", escape: "\\") == false)), + "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo' ESCAPE '\\') = 0") + XCTAssertEqual( + sql(dbQueue, tableRequest.filter { $0.name.like("%foo", escape: "\\") == false }), "SELECT * FROM \"readers\" WHERE (\"name\" LIKE '%foo' ESCAPE '\\') = 0") } @@ -1768,32 +2840,56 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select([Col.name, Col.name].joined(operator: .concat))), + sql(dbQueue, tableRequest.select([Columns.name, Columns.name].joined(operator: .concat))), """ SELECT "name" || "name" FROM "readers" """) - XCTAssertEqual( - sql(dbQueue, tableRequest.filter([Col.name, Col.name].joined(operator: .concat) == "foo")), + sql(dbQueue, tableRequest.select { [$0.name, $0.name].joined(operator: .concat) }), + """ + SELECT "name" || "name" FROM "readers" + """) + + XCTAssertEqual( + sql(dbQueue, tableRequest.filter([Columns.name, Columns.name].joined(operator: .concat) == "foo")), """ SELECT * FROM "readers" WHERE ("name" || "name") = 'foo' """) - XCTAssertEqual( - sql(dbQueue, tableRequest.select([Col.name, " ".databaseValue, Col.name].joined(operator: .concat))), + sql(dbQueue, tableRequest.filter { [$0.name, $0.name].joined(operator: .concat) == "foo" }), + """ + SELECT * FROM "readers" WHERE ("name" || "name") = 'foo' + """) + + XCTAssertEqual( + sql(dbQueue, tableRequest.select([Columns.name, " ".databaseValue, Columns.name].joined(operator: .concat))), """ SELECT "name" || ' ' || "name" FROM "readers" """) - + XCTAssertEqual( + sql(dbQueue, tableRequest.select { [$0.name, " ".databaseValue, $0.name].joined(operator: .concat) }), + """ + SELECT "name" || ' ' || "name" FROM "readers" + """) + // Flattened XCTAssertEqual( sql(dbQueue, tableRequest.select([ - [Col.name, "a".databaseValue].joined(operator: .concat), - ["b".databaseValue, Col.name].joined(operator: .concat), + [Columns.name, "a".databaseValue].joined(operator: .concat), + ["b".databaseValue, Columns.name].joined(operator: .concat), ].joined(operator: .concat))), """ SELECT "name" || 'a' || 'b' || "name" FROM "readers" """) + XCTAssertEqual( + sql(dbQueue, tableRequest.select { [ + [$0.name, "a".databaseValue].joined(operator: .concat), + ["b".databaseValue, $0.name].joined(operator: .concat), + ].joined(operator: .concat) + }), + """ + SELECT "name" || 'a' || 'b' || "name" FROM "readers" + """) } @@ -1803,7 +2899,10 @@ class QueryInterfaceExpressionsTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(customFunction(Col.age, 1, 2))), + sql(dbQueue, tableRequest.select(customFunction(Columns.age, 1, 2))), + "SELECT avgOf(\"age\", 1, 2) FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { customFunction($0.age, 1, 2) }), "SELECT avgOf(\"age\", 1, 2) FROM \"readers\"") } diff --git a/Tests/GRDBTests/QueryInterfaceRequestTests.swift b/Tests/GRDBTests/QueryInterfaceRequestTests.swift index 91f032354..43e510b95 100644 --- a/Tests/GRDBTests/QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/QueryInterfaceRequestTests.swift @@ -1,16 +1,17 @@ import XCTest import GRDB -private struct Col { - static let id = Column("id") - static let name = Column("name") - static let age = Column("age") - static let readerId = Column("readerId") -} - private struct Reader : TableRecord { + struct Columns { + static let id = Column("id") + static let name = Column("name") + static let age = Column("age") + static let readerId = Column("readerId") + } + static let databaseTableName = "readers" } +private typealias Columns = Reader.Columns private let tableRequest = Reader.all() class QueryInterfaceRequestTests: GRDBTestCase { @@ -101,37 +102,64 @@ class QueryInterfaceRequestTests: GRDBTestCase { XCTAssertEqual(try tableRequest.reversed().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") - XCTAssertEqual(try tableRequest.order(Col.name).fetchCount(db), 0) + XCTAssertEqual(try tableRequest.order(Columns.name).fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(try tableRequest.order { $0.name }.fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") XCTAssertEqual(try tableRequest.limit(10).fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT * FROM \"readers\" LIMIT 10)") - XCTAssertEqual(try tableRequest.filter(Col.age == 42).fetchCount(db), 0) + XCTAssertEqual(try tableRequest.filter(Columns.age == 42).fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\" WHERE \"age\" = 42") + + XCTAssertEqual(try tableRequest.filter { $0.age == 42 }.fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\" WHERE \"age\" = 42") XCTAssertEqual(try tableRequest.distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT * FROM \"readers\")") - XCTAssertEqual(try tableRequest.select(Col.name).fetchCount(db), 0) + XCTAssertEqual(try tableRequest.select(Columns.name).fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") - XCTAssertEqual(try tableRequest.select(Col.name).distinct().fetchCount(db), 0) + XCTAssertEqual(try tableRequest.select { $0.name }.fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(try tableRequest.select(Columns.name).distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"name\") FROM \"readers\"") - XCTAssertEqual(try tableRequest.select(Col.age * 2).distinct().fetchCount(db), 0) + XCTAssertEqual(try tableRequest.select { $0.name }.distinct().fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"name\") FROM \"readers\"") + + XCTAssertEqual(try tableRequest.select(Columns.age * 2).distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") - XCTAssertEqual(try tableRequest.select((Col.age * 2).forKey("ignored")).distinct().fetchCount(db), 0) + XCTAssertEqual(try tableRequest.select { $0.age * 2 }.distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") - XCTAssertEqual(try tableRequest.select(Col.name, Col.age).fetchCount(db), 0) + XCTAssertEqual(try tableRequest.select((Columns.age * 2).forKey("ignored")).distinct().fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") + + XCTAssertEqual(try tableRequest.select { ($0.age * 2).forKey("ignored") }.distinct().fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") + + XCTAssertEqual(try tableRequest.select(Columns.name, Columns.age).fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") - XCTAssertEqual(try tableRequest.select(Col.name, Col.age).distinct().fetchCount(db), 0) + XCTAssertEqual(try tableRequest.select { [$0.name, $0.age] }.fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + + XCTAssertEqual(try tableRequest.select(Columns.name, Columns.age).distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT \"name\", \"age\" FROM \"readers\")") - XCTAssertEqual(try tableRequest.select(max(Col.age)).group(Col.name).fetchCount(db), 0) + XCTAssertEqual(try tableRequest.select { [$0.name, $0.age] }.distinct().fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT \"name\", \"age\" FROM \"readers\")") + + XCTAssertEqual(try tableRequest.select(max(Columns.age)).group(Columns.name).fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT MAX(\"age\") FROM \"readers\" GROUP BY \"name\")") + + XCTAssertEqual(try tableRequest.select { max($0.age) }.group { $0.name }.fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT MAX(\"age\") FROM \"readers\" GROUP BY \"name\")") } } @@ -231,14 +259,27 @@ class QueryInterfaceRequestTests: GRDBTestCase { try db.execute(sql: "INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) try db.execute(sql: "INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) - let request = tableRequest.select(Col.name, Col.id - 1) - let rows = try Row.fetchAll(db, request) - XCTAssertEqual(lastSQLQuery, "SELECT \"name\", \"id\" - 1 FROM \"readers\"") - XCTAssertEqual(rows.count, 2) - XCTAssertEqual(rows[0][0] as String, "Arthur") - XCTAssertEqual(rows[0][1] as Int64, 0) - XCTAssertEqual(rows[1][0] as String, "Barbara") - XCTAssertEqual(rows[1][1] as Int64, 1) + do { + let request = tableRequest.select(Columns.name, Columns.id - 1) + let rows = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, "SELECT \"name\", \"id\" - 1 FROM \"readers\"") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0][0] as String, "Arthur") + XCTAssertEqual(rows[0][1] as Int64, 0) + XCTAssertEqual(rows[1][0] as String, "Barbara") + XCTAssertEqual(rows[1][1] as Int64, 1) + } + + do { + let request = tableRequest.select { [$0.name, $0.id - 1] } + let rows = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, "SELECT \"name\", \"id\" - 1 FROM \"readers\"") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0][0] as String, "Arthur") + XCTAssertEqual(rows[0][1] as Int64, 0) + XCTAssertEqual(rows[1][0] as String, "Barbara") + XCTAssertEqual(rows[1][1] as Int64, 1) + } } } @@ -247,11 +288,21 @@ class QueryInterfaceRequestTests: GRDBTestCase { try dbQueue.inDatabase { db in try db.execute(sql: "INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) - let request = tableRequest.select(Col.name.forKey("nom"), (Col.age + 1).forKey("agePlusOne")) - let row = try Row.fetchOne(db, request)! - XCTAssertEqual(lastSQLQuery, "SELECT \"name\" AS \"nom\", \"age\" + 1 AS \"agePlusOne\" FROM \"readers\" LIMIT 1") - XCTAssertEqual(row["nom"] as String, "Arthur") - XCTAssertEqual(row["agePlusOne"] as Int, 43) + do { + let request = tableRequest.select(Columns.name.forKey("nom"), (Columns.age + 1).forKey("agePlusOne")) + let row = try Row.fetchOne(db, request)! + XCTAssertEqual(lastSQLQuery, "SELECT \"name\" AS \"nom\", \"age\" + 1 AS \"agePlusOne\" FROM \"readers\" LIMIT 1") + XCTAssertEqual(row["nom"] as String, "Arthur") + XCTAssertEqual(row["agePlusOne"] as Int, 43) + } + + do { + let request = tableRequest.select { [$0.name.forKey("nom"), ($0.age + 1).forKey("agePlusOne")] } + let row = try Row.fetchOne(db, request)! + XCTAssertEqual(lastSQLQuery, "SELECT \"name\" AS \"nom\", \"age\" + 1 AS \"agePlusOne\" FROM \"readers\" LIMIT 1") + XCTAssertEqual(row["nom"] as String, "Arthur") + XCTAssertEqual(row["agePlusOne"] as Int, 43) + } } } @@ -259,32 +310,62 @@ class QueryInterfaceRequestTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { - let request = Reader.annotated(with: [Col.id - 1]) + let request = Reader.annotated(with: [Columns.id - 1]) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT *, \"id\" - 1 FROM \"readers\"") } do { - let request = Reader.annotated(with: Col.id - 1, Col.id + 1) - _ = try Row.fetchAll(db, request) - XCTAssertEqual(lastSQLQuery, "SELECT *, \"id\" - 1, \"id\" + 1 FROM \"readers\"") - } - do { - let request = tableRequest.annotated(with: [Col.id - 1]) + let request = Reader.annotated { $0.id - 1 } _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT *, \"id\" - 1 FROM \"readers\"") } do { - let request = tableRequest.annotated(with: Col.id - 1, Col.id + 1) + let request = Reader.annotated(with: Columns.id - 1, Columns.id + 1) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT *, \"id\" - 1, \"id\" + 1 FROM \"readers\"") } do { - let request = tableRequest.select(Col.name).annotated(with: [Col.id - 1]) + let request = Reader.annotated { [$0.id - 1, $0.id + 1] } + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, "SELECT *, \"id\" - 1, \"id\" + 1 FROM \"readers\"") + } + do { + let request = tableRequest.annotated(with: [Columns.id - 1]) + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, "SELECT *, \"id\" - 1 FROM \"readers\"") + } + do { + let request = tableRequest.annotated { $0.id - 1 } + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, "SELECT *, \"id\" - 1 FROM \"readers\"") + } + do { + let request = tableRequest.annotated(with: Columns.id - 1, Columns.id + 1) + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, "SELECT *, \"id\" - 1, \"id\" + 1 FROM \"readers\"") + } + do { + let request = tableRequest.annotated { [$0.id - 1, $0.id + 1] } + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, "SELECT *, \"id\" - 1, \"id\" + 1 FROM \"readers\"") + } + do { + let request = tableRequest.select(Columns.name).annotated(with: [Columns.id - 1]) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT \"name\", \"id\" - 1 FROM \"readers\"") } do { - let request = tableRequest.select(Col.name).annotated(with: Col.id - 1, Col.id + 1) + let request = tableRequest.select { $0.name }.annotated { $0.id - 1 } + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, "SELECT \"name\", \"id\" - 1 FROM \"readers\"") + } + do { + let request = tableRequest.select(Columns.name).annotated(with: Columns.id - 1, Columns.id + 1) + _ = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, "SELECT \"name\", \"id\" - 1, \"id\" + 1 FROM \"readers\"") + } + do { + let request = tableRequest.select { $0.name }.annotated { [$0.id - 1, $0.id + 1] } _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, "SELECT \"name\", \"id\" - 1, \"id\" + 1 FROM \"readers\"") } @@ -306,35 +387,65 @@ class QueryInterfaceRequestTests: GRDBTestCase { INSERT INTO author(id, name) VALUES (1, 'Arthur'); INSERT INTO book(id, authorId) VALUES (2, 1); """) - struct Author: TableRecord { } + struct Author: TableRecord { + enum Columns { + static let name = Column("name") + } + } struct Book: TableRecord { static let author = belongsTo(Author.self) } - let alias = TableAlias() - let request = Book - .annotated(with: alias[Column("name")]) - .joining(required: Book.author.aliased(alias)) - let rows = try Row.fetchCursor(db, request) - while let row = try rows.next() { - // Just some sanity checks that the "author"."name" SQL column is - // simply exposed as "name" in Swift code: - XCTAssertEqual(row, ["id":2, "authorId":1, "name":"Arthur"]) - XCTAssertEqual(Set(row.columnNames), ["id", "authorId", "name"]) - XCTAssertEqual(row["name"], "Arthur") + do { + let alias = TableAlias() + let request = Book + .annotated(with: alias[Column("name")]) + .joining(required: Book.author.aliased(alias)) + let rows = try Row.fetchCursor(db, request) + while let row = try rows.next() { + // Just some sanity checks that the "author"."name" SQL column is + // simply exposed as "name" in Swift code: + XCTAssertEqual(row, ["id":2, "authorId":1, "name":"Arthur"]) + XCTAssertEqual(Set(row.columnNames), ["id", "authorId", "name"]) + XCTAssertEqual(row["name"], "Arthur") + } + XCTAssertEqual(lastSQLQuery, """ + SELECT "book".*, "author"."name" \ + FROM "book" \ + JOIN "author" ON "author"."id" = "book"."authorId" + """) } - XCTAssertEqual(lastSQLQuery, """ - SELECT "book".*, "author"."name" \ - FROM "book" \ - JOIN "author" ON "author"."id" = "book"."authorId" - """) + #if compiler(>=6.1) + do { + let alias = TableAlias() + let request = Book + .annotated(with: alias.name) + .joining(required: Book.author.aliased(alias)) + let rows = try Row.fetchCursor(db, request) + while let row = try rows.next() { + // Just some sanity checks that the "author"."name" SQL column is + // simply exposed as "name" in Swift code: + XCTAssertEqual(row, ["id":2, "authorId":1, "name":"Arthur"]) + XCTAssertEqual(Set(row.columnNames), ["id", "authorId", "name"]) + XCTAssertEqual(row["name"], "Arthur") + } + XCTAssertEqual(lastSQLQuery, """ + SELECT "book".*, "author"."name" \ + FROM "book" \ + JOIN "author" ON "author"."id" = "book"."authorId" + """) + } + #endif } } func testMultipleSelect() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(Col.age).select(Col.name)), + sql(dbQueue, tableRequest.select(Columns.age).select(Columns.name)), + "SELECT \"name\" FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { $0.age }.select { $0.name }), "SELECT \"name\" FROM \"readers\"") } @@ -347,17 +458,24 @@ class QueryInterfaceRequestTests: GRDBTestCase { do { // Type.select(..., as:) do { + // DatabaseComponents + do { + let value = try Reader + .select({ $0.name }, as: String.self) + .fetchOne(db)! + XCTAssertEqual(value, "Arthur") + } // variadic do { let value = try Reader - .select(Col.name, as: String.self) + .select(Columns.name, as: String.self) .fetchOne(db)! XCTAssertEqual(value, "Arthur") } // array do { let value = try Reader - .select([Col.name], as: String.self) + .select([Columns.name], as: String.self) .fetchOne(db)! XCTAssertEqual(value, "Arthur") } @@ -385,11 +503,19 @@ class QueryInterfaceRequestTests: GRDBTestCase { } // request.select(..., as:) do { + // DatabaseComponents + do { + let value = try Reader + .all() + .select({ $0.name }, as: String.self) + .fetchOne(db)! + XCTAssertEqual(value, "Arthur") + } // variadic do { let value = try Reader .all() - .select(Col.name, as: String.self) + .select(Columns.name, as: String.self) .fetchOne(db)! XCTAssertEqual(value, "Arthur") } @@ -397,7 +523,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { do { let value = try Reader .all() - .select([Col.name], as: String.self) + .select([Columns.name], as: String.self) .fetchOne(db)! XCTAssertEqual(value, "Arthur") } @@ -435,14 +561,14 @@ class QueryInterfaceRequestTests: GRDBTestCase { // variadic do { let value = try Reader - .select(Col.name, Col.age, as: Row.self) + .select(Columns.name, Columns.age, as: Row.self) .fetchOne(db)! XCTAssertEqual(value, ["name": "Arthur", "age": 42]) } // array do { let value = try Reader - .select([Col.name, Col.age], as: Row.self) + .select([Columns.name, Columns.age], as: Row.self) .fetchOne(db)! XCTAssertEqual(value, ["name": "Arthur", "age": 42]) } @@ -474,7 +600,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { do { let value = try Reader .all() - .select(Col.name, Col.age, as: Row.self) + .select(Columns.name, Columns.age, as: Row.self) .fetchOne(db)! XCTAssertEqual(value, ["name": "Arthur", "age": 42]) } @@ -482,7 +608,7 @@ class QueryInterfaceRequestTests: GRDBTestCase { do { let value = try Reader .all() - .select([Col.name, Col.age], as: Row.self) + .select([Columns.name, Columns.age], as: Row.self) .fetchOne(db)! XCTAssertEqual(value, ["name": "Arthur", "age": 42]) } @@ -517,26 +643,32 @@ class QueryInterfaceRequestTests: GRDBTestCase { // This test passes if this method compiles func testSelectAsTypeInference() { - _ = Reader.select(Col.name) as QueryInterfaceRequest - _ = Reader.select([Col.name]) as QueryInterfaceRequest + _ = Reader.select(Columns.name) as QueryInterfaceRequest + _ = Reader.select { $0.name } as QueryInterfaceRequest + _ = Reader.select([Columns.name]) as QueryInterfaceRequest _ = Reader.select(sql: "name") as QueryInterfaceRequest _ = Reader.select(literal: SQL(sql: "name")) as QueryInterfaceRequest - _ = Reader.all().select(Col.name) as QueryInterfaceRequest - _ = Reader.all().select([Col.name]) as QueryInterfaceRequest + _ = Reader.all().select(Columns.name) as QueryInterfaceRequest + _ = Reader.all().select { $0.name } as QueryInterfaceRequest + _ = Reader.all().select([Columns.name]) as QueryInterfaceRequest _ = Reader.all().select(sql: "name") as QueryInterfaceRequest _ = Reader.all().select(literal: SQL(sql: "name")) as QueryInterfaceRequest - func makeRequest() -> QueryInterfaceRequest { - Reader.select(Col.name) + func makeRequest1() -> QueryInterfaceRequest { + Reader.select(Columns.name) + } + + func makeRequest3() -> QueryInterfaceRequest { + Reader.select { $0.name } } // Those should be, without any ambiguuity, requests of Reader. do { - let request = Reader.select(Col.name) + let request = Reader.select(Columns.name) _ = request as QueryInterfaceRequest } do { - let request = Reader.select([Col.name]) + let request = Reader.select([Columns.name]) _ = request as QueryInterfaceRequest } do { @@ -548,11 +680,11 @@ class QueryInterfaceRequestTests: GRDBTestCase { _ = request as QueryInterfaceRequest } do { - let request = Reader.all().select(Col.name) + let request = Reader.all().select(Columns.name) _ = request as QueryInterfaceRequest } do { - let request = Reader.all().select([Col.name]) + let request = Reader.all().select([Columns.name]) _ = request as QueryInterfaceRequest } do { @@ -571,7 +703,10 @@ class QueryInterfaceRequestTests: GRDBTestCase { func testDistinct() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.select(Col.name).distinct()), + sql(dbQueue, tableRequest.select(Columns.name).distinct()), + "SELECT DISTINCT \"name\" FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.select { $0.name }.distinct()), "SELECT DISTINCT \"name\" FROM \"readers\"") } @@ -678,17 +813,26 @@ class QueryInterfaceRequestTests: GRDBTestCase { func testGroup() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.group(Col.age)), + sql(dbQueue, tableRequest.group(Columns.age)), "SELECT * FROM \"readers\" GROUP BY \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.group(Col.age, Col.name)), + sql(dbQueue, tableRequest.group { $0.age }), + "SELECT * FROM \"readers\" GROUP BY \"age\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.group(Columns.age, Columns.name)), + "SELECT * FROM \"readers\" GROUP BY \"age\", \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.group { [$0.age, $0.name ] }), "SELECT * FROM \"readers\" GROUP BY \"age\", \"name\"") } func testMultipleGroup() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.group(Col.age).group(Col.name)), + sql(dbQueue, tableRequest.group(Columns.age).group(Columns.name)), + "SELECT * FROM \"readers\" GROUP BY \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.group { $0.age }.group { $0.name }), "SELECT * FROM \"readers\" GROUP BY \"name\"") } @@ -698,35 +842,41 @@ class QueryInterfaceRequestTests: GRDBTestCase { func testHavingLiteral() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.group(Col.name).having(sql: "min(age) > 18")), + sql(dbQueue, tableRequest.group(Columns.name).having(sql: "min(age) > 18")), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18") } func testHavingLiteralWithPositionalArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.group(Col.name).having(sql: "min(age) > ?", arguments: [18])), + sql(dbQueue, tableRequest.group(Columns.name).having(sql: "min(age) > ?", arguments: [18])), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18") } func testHavingLiteralWithNamedArguments() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.group(Col.name).having(sql: "min(age) > :age", arguments: ["age": 18])), + sql(dbQueue, tableRequest.group(Columns.name).having(sql: "min(age) > :age", arguments: ["age": 18])), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING min(age) > 18") } func testHaving() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.group(Col.name).having(min(Col.age) > 18)), + sql(dbQueue, tableRequest.group(Columns.name).having(min(Columns.age) > 18)), + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING MIN(\"age\") > 18") + XCTAssertEqual( + sql(dbQueue, tableRequest.group { $0.name }.having { min($0.age) > 18 }), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING MIN(\"age\") > 18") } func testMultipleHaving() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.group(Col.name).having(min(Col.age) > 18).having(max(Col.age) < 50)), + sql(dbQueue, tableRequest.group(Columns.name).having(min(Columns.age) > 18).having(max(Columns.age) < 50)), + "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (MIN(\"age\") > 18) AND (MAX(\"age\") < 50)") + XCTAssertEqual( + sql(dbQueue, tableRequest.group { $0.name }.having { min($0.age) > 18 }.having{ max($0.age) < 50 }), "SELECT * FROM \"readers\" GROUP BY \"name\" HAVING (MIN(\"age\") > 18) AND (MAX(\"age\") < 50)") } @@ -757,35 +907,104 @@ class QueryInterfaceRequestTests: GRDBTestCase { func testSort() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age)), + sql(dbQueue, tableRequest.order(Columns.age)), "SELECT * FROM \"readers\" ORDER BY \"age\"") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age.asc)), + sql(dbQueue, tableRequest.order { $0.age }), + "SELECT * FROM \"readers\" ORDER BY \"age\"") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, tableRequest.order(\.age)), + "SELECT * FROM \"readers\" ORDER BY \"age\"") + #endif + + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.age.asc)), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age.desc)), + sql(dbQueue, tableRequest.order { $0.age.asc }), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, tableRequest.order(\.age.asc)), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC") + #endif + + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.age.desc)), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age, Col.name.desc)), + sql(dbQueue, tableRequest.order { $0.age.desc }), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, tableRequest.order(\.age.desc)), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") + #endif + + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.age, Columns.name.desc)), "SELECT * FROM \"readers\" ORDER BY \"age\", \"name\" DESC") XCTAssertEqual( - sql(dbQueue, tableRequest.order(abs(Col.age))), + sql(dbQueue, tableRequest.order { [$0.age, $0.name.desc] }), + "SELECT * FROM \"readers\" ORDER BY \"age\", \"name\" DESC") + + XCTAssertEqual( + sql(dbQueue, tableRequest.order(abs(Columns.age))), "SELECT * FROM \"readers\" ORDER BY ABS(\"age\")") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { abs($0.age) }), + "SELECT * FROM \"readers\" ORDER BY ABS(\"age\")") + #if GRDBCUSTOMSQLITE XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age.ascNullsLast)), + sql(dbQueue, tableRequest.order(Columns.age.ascNullsLast)), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age.descNullsFirst)), + sql(dbQueue, tableRequest.order { $0.age.ascNullsLast }), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, tableRequest.order(\.age.ascNullsLast)), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") + #endif + + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.age.descNullsFirst)), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.age.descNullsFirst }), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, tableRequest.order(\.age.descNullsFirst)), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + #endif #elseif !GRDBCIPHER - if #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) { + if #available(iOS 14, macOS 10.16, tvOS 14, *) { XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age.ascNullsLast)), + sql(dbQueue, tableRequest.order(Columns.age.ascNullsLast)), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age.descNullsFirst)), + sql(dbQueue, tableRequest.order { $0.age.ascNullsLast }), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, tableRequest.order(\.age.ascNullsLast)), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") + #endif + + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.age.descNullsFirst)), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.age.descNullsFirst }), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, tableRequest.order(\.age.descNullsFirst)), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + #endif } #endif } @@ -793,28 +1012,49 @@ class QueryInterfaceRequestTests: GRDBTestCase { func testSortWithCollation() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(.nocase))), + sql(dbQueue, tableRequest.order(Columns.name.collating(.nocase))), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).asc)), + sql(dbQueue, tableRequest.order { $0.name.collating(.nocase) }), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE") + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.name.collating(.nocase).asc)), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(collation))), + sql(dbQueue, tableRequest.order { $0.name.collating(.nocase).asc }), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC") + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.name.collating(collation))), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE localized_case_insensitive") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.name.collating(collation) }), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE localized_case_insensitive") #if GRDBCUSTOMSQLITE XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).ascNullsLast)), + sql(dbQueue, tableRequest.order(Columns.name.collating(.nocase).ascNullsLast)), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC NULLS LAST") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).descNullsFirst)), + sql(dbQueue, tableRequest.order { $0.name.collating(.nocase).ascNullsLast }), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC NULLS LAST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.name.collating(.nocase).descNullsFirst)), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC NULLS FIRST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.name.collating(.nocase).descNullsFirst }), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC NULLS FIRST") #elseif !GRDBCIPHER - if #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) { + if #available(iOS 14, macOS 10.16, tvOS 14, *) { XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).ascNullsLast)), + sql(dbQueue, tableRequest.order(Columns.name.collating(.nocase).ascNullsLast)), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC NULLS LAST") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).descNullsFirst)), + sql(dbQueue, tableRequest.order { $0.name.collating(.nocase).ascNullsLast }), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC NULLS LAST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.name.collating(.nocase).descNullsFirst)), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC NULLS FIRST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.name.collating(.nocase).descNullsFirst }), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC NULLS FIRST") } #endif @@ -823,7 +1063,10 @@ class QueryInterfaceRequestTests: GRDBTestCase { func testMultipleSort() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age).order(Col.name)), + sql(dbQueue, tableRequest.order(Columns.age).order(Columns.name)), + "SELECT * FROM \"readers\" ORDER BY \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.age }.order { $0.name }), "SELECT * FROM \"readers\" ORDER BY \"name\"") } @@ -836,34 +1079,61 @@ class QueryInterfaceRequestTests: GRDBTestCase { sql(dbQueue, tableRequest.reversed()), "SELECT * FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age).reversed()), + sql(dbQueue, tableRequest.order(Columns.age).reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age.asc).reversed()), + sql(dbQueue, tableRequest.order { $0.age }.reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age.desc).reversed()), + sql(dbQueue, tableRequest.order(Columns.age.asc).reversed()), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.age.asc }.reversed()), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.age.desc).reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age, Col.name.desc).reversed()), + sql(dbQueue, tableRequest.order { $0.age.desc }.reversed()), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC") + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.age, Columns.name.desc).reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC, \"name\" ASC") XCTAssertEqual( - sql(dbQueue, tableRequest.order(abs(Col.age)).reversed()), + sql(dbQueue, tableRequest.order { [$0.age, $0.name.desc] }.reversed()), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC, \"name\" ASC") + XCTAssertEqual( + sql(dbQueue, tableRequest.order(abs(Columns.age)).reversed()), + "SELECT * FROM \"readers\" ORDER BY ABS(\"age\") DESC") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { abs($0.age) }.reversed()), "SELECT * FROM \"readers\" ORDER BY ABS(\"age\") DESC") #if GRDBCUSTOMSQLITE XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age.descNullsFirst).reversed()), + sql(dbQueue, tableRequest.order(Columns.age.descNullsFirst).reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age.ascNullsLast).reversed()), + sql(dbQueue, tableRequest.order { $0.age.descNullsFirst }.reversed()), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.age.ascNullsLast).reversed()), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.age.ascNullsLast }.reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") #elseif !GRDBCIPHER - if #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) { + if #available(iOS 14, macOS 10.16, tvOS 14, *) { XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age.descNullsFirst).reversed()), + sql(dbQueue, tableRequest.order(Columns.age.descNullsFirst).reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age.ascNullsLast).reversed()), + sql(dbQueue, tableRequest.order { $0.age.descNullsFirst }.reversed()), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.age.ascNullsLast).reversed()), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.age.ascNullsLast }.reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") } #endif @@ -872,28 +1142,49 @@ class QueryInterfaceRequestTests: GRDBTestCase { func testReverseWithCollation() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(.nocase)).reversed()), + sql(dbQueue, tableRequest.order(Columns.name.collating(.nocase)).reversed()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).asc).reversed()), + sql(dbQueue, tableRequest.order { $0.name.collating(.nocase) }.reversed()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(collation)).reversed()), + sql(dbQueue, tableRequest.order(Columns.name.collating(.nocase).asc).reversed()), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.name.collating(.nocase).asc }.reversed()), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC") + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.name.collating(collation)).reversed()), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE localized_case_insensitive DESC") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.name.collating(collation) }.reversed()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE localized_case_insensitive DESC") #if GRDBCUSTOMSQLITE XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).ascNullsLast).reversed()), + sql(dbQueue, tableRequest.order(Columns.name.collating(.nocase).ascNullsLast).reversed()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC NULLS FIRST") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).descNullsFirst).reversed()), + sql(dbQueue, tableRequest.order { $0.name.collating(.nocase).ascNullsLast }.reversed()), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC NULLS FIRST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.name.collating(.nocase).descNullsFirst).reversed()), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC NULLS LAST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.name.collating(.nocase).descNullsFirst }.reversed()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC NULLS LAST") #elseif !GRDBCIPHER - if #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) { + if #available(iOS 14, macOS 10.16, tvOS 14, *) { XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).ascNullsLast).reversed()), + sql(dbQueue, tableRequest.order(Columns.name.collating(.nocase).ascNullsLast).reversed()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC NULLS FIRST") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.name.collating(.nocase).descNullsFirst).reversed()), + sql(dbQueue, tableRequest.order { $0.name.collating(.nocase).ascNullsLast }.reversed()), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE DESC NULLS FIRST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order(Columns.name.collating(.nocase).descNullsFirst).reversed()), + "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC NULLS LAST") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { $0.name.collating(.nocase).descNullsFirst }.reversed()), "SELECT * FROM \"readers\" ORDER BY \"name\" COLLATE NOCASE ASC NULLS LAST") } #endif @@ -905,7 +1196,10 @@ class QueryInterfaceRequestTests: GRDBTestCase { sql(dbQueue, tableRequest.reversed().reversed()), "SELECT * FROM \"readers\"") XCTAssertEqual( - sql(dbQueue, tableRequest.order(Col.age, Col.name).reversed().reversed()), + sql(dbQueue, tableRequest.order(Columns.age, Columns.name).reversed().reversed()), + "SELECT * FROM \"readers\" ORDER BY \"age\", \"name\"") + XCTAssertEqual( + sql(dbQueue, tableRequest.order { [$0.age, $0.name] } .reversed().reversed()), "SELECT * FROM \"readers\" ORDER BY \"age\", \"name\"") } diff --git a/Tests/GRDBTests/RecordEditedTests.swift b/Tests/GRDBTests/RecordEditedTests.swift index 31316f5c0..64573f4c4 100644 --- a/Tests/GRDBTests/RecordEditedTests.swift +++ b/Tests/GRDBTests/RecordEditedTests.swift @@ -15,7 +15,7 @@ private class Person : Record { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, @@ -131,7 +131,9 @@ class RecordEditedTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createPerson", migrate: Person.setup) + migrator.registerMigration("createPerson") { + try Person.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift index 1ce98c182..069f0e4f3 100644 --- a/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalNonOptionalPrimaryKeySingleTests.swift @@ -13,7 +13,7 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: "CREATE TABLE minimalSingles (id TEXT NOT NULL PRIMARY KEY)") } @@ -41,14 +41,15 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension MinimalNonOptionalPrimaryKeySingle: Identifiable { } class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createMinimalNonOptionalPrimaryKeySingle", migrate: MinimalNonOptionalPrimaryKeySingle.setup) + migrator.registerMigration("createMinimalNonOptionalPrimaryKeySingle") { + try MinimalNonOptionalPrimaryKeySingle.setup($0) + } try migrator.migrate(dbWriter) } @@ -471,20 +472,18 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [String] = [] - let cursor = try MinimalNonOptionalPrimaryKeySingle.fetchCursor(db, ids: ids) - try XCTAssertNil(cursor.next()) - } - - do { - let ids = [record1.id, record2.id] - let cursor = try MinimalNonOptionalPrimaryKeySingle.fetchCursor(db, ids: ids) - let fetchedRecords = try [cursor.next()!, cursor.next()!] - XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) - XCTAssertTrue(try cursor.next() == nil) // end - } + do { + let ids: [String] = [] + let cursor = try MinimalNonOptionalPrimaryKeySingle.fetchCursor(db, ids: ids) + try XCTAssertNil(cursor.next()) + } + + do { + let ids = [record1.id, record2.id] + let cursor = try MinimalNonOptionalPrimaryKeySingle.fetchCursor(db, ids: ids) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) + XCTAssertTrue(try cursor.next() == nil) // end } } } @@ -510,19 +509,17 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [String] = [] - let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.fetchAll(db, ids: ids) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let ids = [record1.id, record2.id] - let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.fetchAll(db, ids: ids) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) - } + do { + let ids: [String] = [] + let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.fetchAll(db, ids: ids) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id, record2.id] + let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.fetchAll(db, ids: ids) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) } } } @@ -548,19 +545,17 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [String] = [] - let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.fetchSet(db, ids: ids) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let ids = [record1.id, record2.id] - let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.fetchSet(db, ids: ids) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) - } + do { + let ids: [String] = [] + let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.fetchSet(db, ids: ids) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id, record2.id] + let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.fetchSet(db, ids: ids) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) } } } @@ -583,12 +578,10 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"id\" = '\(record.id)'") } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let fetchedRecord = try MinimalNonOptionalPrimaryKeySingle.fetchOne(db, id: record.id)! - XCTAssertTrue(fetchedRecord.id == record.id) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"id\" = '\(record.id)'") - } + do { + let fetchedRecord = try MinimalNonOptionalPrimaryKeySingle.fetchOne(db, id: record.id)! + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"id\" = '\(record.id)'") } } } @@ -611,17 +604,15 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"id\" = '\(record.id)'") } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - _ = try MinimalNonOptionalPrimaryKeySingle.find(db, key: "missing") - XCTFail("Expected RecordError") - } catch RecordError.recordNotFound(databaseTableName: "minimalSingles", key: ["id": "missing".databaseValue]) { } - - do { - let fetchedRecord = try MinimalNonOptionalPrimaryKeySingle.find(db, id: record.id) - XCTAssertTrue(fetchedRecord.id == record.id) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"id\" = '\(record.id)'") - } + do { + _ = try MinimalNonOptionalPrimaryKeySingle.find(db, key: "missing") + XCTFail("Expected RecordError") + } catch RecordError.recordNotFound(databaseTableName: "minimalSingles", key: ["id": "missing".databaseValue]) { } + + do { + let fetchedRecord = try MinimalNonOptionalPrimaryKeySingle.find(db, id: record.id) + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"id\" = '\(record.id)'") } } } @@ -651,20 +642,18 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [String] = [] - let cursor = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchCursor(db) - try XCTAssertNil(cursor.next()) - } - - do { - let ids = [record1.id, record2.id] - let cursor = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchCursor(db) - let fetchedRecords = try [cursor.next()!, cursor.next()!] - XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) - XCTAssertTrue(try cursor.next() == nil) // end - } + do { + let ids: [String] = [] + let cursor = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let ids = [record1.id, record2.id] + let cursor = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) + XCTAssertTrue(try cursor.next() == nil) // end } } } @@ -690,19 +679,17 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [String] = [] - let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchAll(db) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let ids = [record1.id, record2.id] - let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchAll(db) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) - } + do { + let ids: [String] = [] + let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id, record2.id] + let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) } } } @@ -728,19 +715,17 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [String] = [] - let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchSet(db) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let ids = [record1.id, record2.id] - let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchSet(db) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) - } + do { + let ids: [String] = [] + let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchSet(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id, record2.id] + let fetchedRecords = try MinimalNonOptionalPrimaryKeySingle.filter(ids: ids).fetchSet(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.id }), Set(ids)) } } } @@ -763,12 +748,10 @@ class RecordMinimalNonOptionalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"id\" = '\(record.id)'") } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let fetchedRecord = try MinimalNonOptionalPrimaryKeySingle.filter(id: record.id).fetchOne(db)! - XCTAssertTrue(fetchedRecord.id == record.id) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"id\" = '\(record.id)'") - } + do { + let fetchedRecord = try MinimalNonOptionalPrimaryKeySingle.filter(id: record.id).fetchOne(db)! + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"id\" = '\(record.id)'") } } } @@ -817,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 @@ -828,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"]) + } + } } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift index 43e649f46..7102057a5 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeyRowIDTests.swift @@ -12,7 +12,7 @@ class MinimalRowID : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: "CREATE TABLE minimalRowIDs (id INTEGER PRIMARY KEY)") } @@ -45,14 +45,15 @@ class MinimalRowID : Record, Hashable { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension MinimalRowID: Identifiable { } class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createMinimalRowID", migrate: MinimalRowID.setup) + migrator.registerMigration("createMinimalRowID") { + try MinimalRowID.setup($0) + } try migrator.migrate(dbWriter) } @@ -505,20 +506,18 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [Int64] = [] - let cursor = try MinimalRowID.fetchCursor(db, ids: ids) - try XCTAssertNil(cursor.next()) - } - - do { - let ids = [record1.id!, record2.id!] - let cursor = try MinimalRowID.fetchCursor(db, ids: ids) - let fetchedRecords = try [cursor.next()!, cursor.next()!] - XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) - XCTAssertTrue(try cursor.next() == nil) // end - } + do { + let ids: [Int64] = [] + let cursor = try MinimalRowID.fetchCursor(db, ids: ids) + try XCTAssertNil(cursor.next()) + } + + do { + let ids = [record1.id!, record2.id!] + let cursor = try MinimalRowID.fetchCursor(db, ids: ids) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) + XCTAssertTrue(try cursor.next() == nil) // end } } } @@ -544,19 +543,17 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [Int64] = [] - let fetchedRecords = try MinimalRowID.fetchAll(db, ids: ids) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let ids = [record1.id!, record2.id!] - let fetchedRecords = try MinimalRowID.fetchAll(db, ids: ids) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) - } + do { + let ids: [Int64] = [] + let fetchedRecords = try MinimalRowID.fetchAll(db, ids: ids) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id!, record2.id!] + let fetchedRecords = try MinimalRowID.fetchAll(db, ids: ids) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } } } @@ -582,19 +579,17 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [Int64] = [] - let fetchedRecords = try MinimalRowID.fetchSet(db, ids: ids) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let ids = [record1.id!, record2.id!] - let fetchedRecords = try MinimalRowID.fetchSet(db, ids: ids) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) - } + do { + let ids: [Int64] = [] + let fetchedRecords = try MinimalRowID.fetchSet(db, ids: ids) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id!, record2.id!] + let fetchedRecords = try MinimalRowID.fetchSet(db, ids: ids) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } } } @@ -617,15 +612,13 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let fetchedRecord = try MinimalRowID.fetchOne(db, id: record.id!)! - XCTAssertTrue(fetchedRecord.id == record.id) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") - } - do { - try XCTAssertNil(MinimalRowID.fetchOne(db, id: nil)) - } + do { + let fetchedRecord = try MinimalRowID.fetchOne(db, id: record.id!)! + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") + } + do { + try XCTAssertNil(MinimalRowID.fetchOne(db, id: nil)) } } } @@ -648,20 +641,18 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - _ = try MinimalRowID.find(db, id: -1) - XCTFail("Expected RecordError") - } catch RecordError.recordNotFound(databaseTableName: "minimalRowIDs", key: ["id": (-1).databaseValue]) { } - - do { - let fetchedRecord = try MinimalRowID.find(db, id: record.id!) - XCTAssertTrue(fetchedRecord.id == record.id) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") - } - do { - try XCTAssertNil(MinimalRowID.fetchOne(db, id: nil)) - } + do { + _ = try MinimalRowID.find(db, id: -1) + XCTFail("Expected RecordError") + } catch RecordError.recordNotFound(databaseTableName: "minimalRowIDs", key: ["id": (-1).databaseValue]) { } + + do { + let fetchedRecord = try MinimalRowID.find(db, id: record.id!) + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") + } + do { + try XCTAssertNil(MinimalRowID.fetchOne(db, id: nil)) } } } @@ -691,20 +682,18 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [Int64] = [] - let cursor = try MinimalRowID.filter(ids: ids).fetchCursor(db) - try XCTAssertNil(cursor.next()) - } - - do { - let ids = [record1.id!, record2.id!] - let cursor = try MinimalRowID.filter(ids: ids).fetchCursor(db) - let fetchedRecords = try [cursor.next()!, cursor.next()!] - XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) - XCTAssertTrue(try cursor.next() == nil) // end - } + do { + let ids: [Int64] = [] + let cursor = try MinimalRowID.filter(ids: ids).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let ids = [record1.id!, record2.id!] + let cursor = try MinimalRowID.filter(ids: ids).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) + XCTAssertTrue(try cursor.next() == nil) // end } } } @@ -730,19 +719,17 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [Int64] = [] - let fetchedRecords = try MinimalRowID.filter(ids: ids).fetchAll(db) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let ids = [record1.id!, record2.id!] - let fetchedRecords = try MinimalRowID.filter(ids: ids).fetchAll(db) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) - } + do { + let ids: [Int64] = [] + let fetchedRecords = try MinimalRowID.filter(ids: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id!, record2.id!] + let fetchedRecords = try MinimalRowID.filter(ids: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } } } @@ -768,19 +755,17 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [Int64] = [] - let fetchedRecords = try MinimalRowID.filter(ids: ids).fetchSet(db) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let ids = [record1.id!, record2.id!] - let fetchedRecords = try MinimalRowID.filter(ids: ids).fetchSet(db) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) - } + do { + let ids: [Int64] = [] + let fetchedRecords = try MinimalRowID.filter(ids: ids).fetchSet(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id!, record2.id!] + let fetchedRecords = try MinimalRowID.filter(ids: ids).fetchSet(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } } } @@ -803,15 +788,13 @@ class RecordMinimalPrimaryKeyRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let fetchedRecord = try MinimalRowID.filter(id: record.id!).fetchOne(db)! - XCTAssertTrue(fetchedRecord.id == record.id) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") - } - do { - try XCTAssertNil(MinimalRowID.filter(id: nil).fetchOne(db)) - } + do { + let fetchedRecord = try MinimalRowID.filter(id: record.id!).fetchOne(db)! + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalRowIDs\" WHERE \"id\" = \(record.id!)") + } + do { + try XCTAssertNil(MinimalRowID.filter(id: nil).fetchOne(db)) } } } @@ -861,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 @@ -872,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]) + } + } } diff --git a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift index 8c5c1f036..2216058f9 100644 --- a/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordMinimalPrimaryKeySingleTests.swift @@ -11,7 +11,7 @@ class MinimalSingle: Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: "CREATE TABLE minimalSingles (UUID TEXT NOT NULL PRIMARY KEY)") } @@ -39,7 +39,6 @@ class MinimalSingle: Record, Hashable { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension MinimalSingle: Identifiable { /// Test non-optional ID type var id: String { UUID! } @@ -49,7 +48,9 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createMinimalSingle", migrate: MinimalSingle.setup) + migrator.registerMigration("createMinimalSingle") { + try MinimalSingle.setup($0) + } try migrator.migrate(dbWriter) } @@ -374,7 +375,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") } } - + // MARK: - Fetch With Key Request @@ -529,20 +530,18 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let UUIDs: [String] = [] - let cursor = try MinimalSingle.fetchCursor(db, ids: UUIDs) - try XCTAssertNil(cursor.next()) - } - - do { - let UUIDs = [record1.UUID!, record2.UUID!] - let cursor = try MinimalSingle.fetchCursor(db, ids: UUIDs) - let fetchedRecords = try [cursor.next()!, cursor.next()!] - XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) - XCTAssertTrue(try cursor.next() == nil) // end - } + do { + let UUIDs: [String] = [] + let cursor = try MinimalSingle.fetchCursor(db, ids: UUIDs) + try XCTAssertNil(cursor.next()) + } + + do { + let UUIDs = [record1.UUID!, record2.UUID!] + let cursor = try MinimalSingle.fetchCursor(db, ids: UUIDs) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) + XCTAssertTrue(try cursor.next() == nil) // end } } } @@ -570,19 +569,17 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let UUIDs: [String] = [] - let fetchedRecords = try MinimalSingle.fetchAll(db, ids: UUIDs) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let UUIDs = [record1.UUID!, record2.UUID!] - let fetchedRecords = try MinimalSingle.fetchAll(db, ids: UUIDs) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) - } + do { + let UUIDs: [String] = [] + let fetchedRecords = try MinimalSingle.fetchAll(db, ids: UUIDs) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let UUIDs = [record1.UUID!, record2.UUID!] + let fetchedRecords = try MinimalSingle.fetchAll(db, ids: UUIDs) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) } } } @@ -610,19 +607,17 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let UUIDs: [String] = [] - let fetchedRecords = try MinimalSingle.fetchSet(db, ids: UUIDs) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let UUIDs = [record1.UUID!, record2.UUID!] - let fetchedRecords = try MinimalSingle.fetchSet(db, ids: UUIDs) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) - } + do { + let UUIDs: [String] = [] + let fetchedRecords = try MinimalSingle.fetchSet(db, ids: UUIDs) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let UUIDs = [record1.UUID!, record2.UUID!] + let fetchedRecords = try MinimalSingle.fetchSet(db, ids: UUIDs) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) } } } @@ -646,12 +641,10 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let fetchedRecord = try MinimalSingle.fetchOne(db, id: record.UUID!)! - XCTAssertTrue(fetchedRecord.UUID == record.UUID) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") - } + do { + let fetchedRecord = try MinimalSingle.fetchOne(db, id: record.UUID!)! + XCTAssertTrue(fetchedRecord.UUID == record.UUID) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") } } } @@ -668,28 +661,26 @@ 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) XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - _ = try MinimalSingle.find(db, id: "missing") - XCTFail("Expected RecordError") - } catch RecordError.recordNotFound(databaseTableName: "minimalSingles", key: ["UUID": "missing".databaseValue]) { } - - do { - let fetchedRecord = try MinimalSingle.find(db, id: record.UUID!) - XCTAssertTrue(fetchedRecord.UUID == record.UUID) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") - } + do { + _ = try MinimalSingle.find(db, id: "missing") + XCTFail("Expected RecordError") + } catch RecordError.recordNotFound(databaseTableName: "minimalSingles", key: ["UUID": "missing".databaseValue]) { } + + do { + let fetchedRecord = try MinimalSingle.find(db, id: record.UUID!) + XCTAssertTrue(fetchedRecord.UUID == record.UUID) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") } } } - + // MARK: - Fetch With Primary Key Request @@ -717,20 +708,18 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let UUIDs: [String] = [] - let cursor = try MinimalSingle.filter(ids: UUIDs).fetchCursor(db) - try XCTAssertNil(cursor.next()) - } - - do { - let UUIDs = [record1.UUID!, record2.UUID!] - let cursor = try MinimalSingle.filter(ids: UUIDs).fetchCursor(db) - let fetchedRecords = try [cursor.next()!, cursor.next()!] - XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) - XCTAssertTrue(try cursor.next() == nil) // end - } + do { + let UUIDs: [String] = [] + let cursor = try MinimalSingle.filter(ids: UUIDs).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let UUIDs = [record1.UUID!, record2.UUID!] + let cursor = try MinimalSingle.filter(ids: UUIDs).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) + XCTAssertTrue(try cursor.next() == nil) // end } } } @@ -758,19 +747,17 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let UUIDs: [String] = [] - let fetchedRecords = try MinimalSingle.filter(ids: UUIDs).fetchAll(db) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let UUIDs = [record1.UUID!, record2.UUID!] - let fetchedRecords = try MinimalSingle.filter(ids: UUIDs).fetchAll(db) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) - } + do { + let UUIDs: [String] = [] + let fetchedRecords = try MinimalSingle.filter(ids: UUIDs).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let UUIDs = [record1.UUID!, record2.UUID!] + let fetchedRecords = try MinimalSingle.filter(ids: UUIDs).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) } } } @@ -798,19 +785,17 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let UUIDs: [String] = [] - let fetchedRecords = try MinimalSingle.filter(ids: UUIDs).fetchSet(db) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let UUIDs = [record1.UUID!, record2.UUID!] - let fetchedRecords = try MinimalSingle.filter(ids: UUIDs).fetchSet(db) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) - } + do { + let UUIDs: [String] = [] + let fetchedRecords = try MinimalSingle.filter(ids: UUIDs).fetchSet(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let UUIDs = [record1.UUID!, record2.UUID!] + let fetchedRecords = try MinimalSingle.filter(ids: UUIDs).fetchSet(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs)) } } } @@ -834,12 +819,10 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let fetchedRecord = try MinimalSingle.filter(id: record.UUID!).fetchOne(db)! - XCTAssertTrue(fetchedRecord.UUID == record.UUID) - XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") - } + do { + let fetchedRecord = try MinimalSingle.filter(id: record.UUID!).fetchOne(db)! + XCTAssertTrue(fetchedRecord.UUID == record.UUID) + XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"minimalSingles\" WHERE \"UUID\" = '\(record.UUID!)'") } } } @@ -878,7 +861,7 @@ class RecordMinimalPrimaryKeySingleTests: GRDBTestCase { } // MARK: Select PrimaryKey - + func test_static_selectPrimaryKey() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -892,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 @@ -904,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"]) + } + } } diff --git a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift index 677772281..d8bc981db 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyHiddenRowIDTests.swift @@ -16,7 +16,7 @@ private class Person : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE persons ( creationDate TEXT NOT NULL, @@ -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 { @@ -77,14 +77,15 @@ private class Person : Record, Hashable { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Person: Identifiable { } class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createPerson", migrate: Person.setup) + migrator.registerMigration("createPerson") { + try Person.setup($0) + } try migrator.migrate(dbWriter) } @@ -597,20 +598,18 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [Int64] = [] - let cursor = try Person.fetchCursor(db, ids: ids) - try XCTAssertNil(cursor.next()) - } - - do { - let ids = [record1.id!, record2.id!] - let cursor = try Person.fetchCursor(db, ids: ids) - let fetchedRecords = try [cursor.next()!, cursor.next()!] - XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) - XCTAssertTrue(try cursor.next() == nil) // end - } + do { + let ids: [Int64] = [] + let cursor = try Person.fetchCursor(db, ids: ids) + try XCTAssertNil(cursor.next()) + } + + do { + let ids = [record1.id!, record2.id!] + let cursor = try Person.fetchCursor(db, ids: ids) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) + XCTAssertTrue(try cursor.next() == nil) // end } } } @@ -636,19 +635,17 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [Int64] = [] - let fetchedRecords = try Person.fetchAll(db, ids: ids) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let ids = [record1.id!, record2.id!] - let fetchedRecords = try Person.fetchAll(db, ids: ids) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) - } + do { + let ids: [Int64] = [] + let fetchedRecords = try Person.fetchAll(db, ids: ids) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id!, record2.id!] + let fetchedRecords = try Person.fetchAll(db, ids: ids) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } } } @@ -674,19 +671,17 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [Int64] = [] - let fetchedRecords = try Person.fetchSet(db, ids: ids) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let ids = [record1.id!, record2.id!] - let fetchedRecords = try Person.fetchSet(db, ids: ids) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) - } + do { + let ids: [Int64] = [] + let fetchedRecords = try Person.fetchSet(db, ids: ids) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id!, record2.id!] + let fetchedRecords = try Person.fetchSet(db, ids: ids) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } } } @@ -712,18 +707,16 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let fetchedRecord = try Person.fetchOne(db, id: record.id!)! - XCTAssertTrue(fetchedRecord.id == record.id) - XCTAssertTrue(fetchedRecord.name == record.name) - XCTAssertTrue(fetchedRecord.age == record.age) - XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. - XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") - } - do { - try XCTAssertNil(Person.fetchOne(db, id: nil)) - } + do { + let fetchedRecord = try Person.fetchOne(db, id: record.id!)! + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertTrue(fetchedRecord.name == record.name) + XCTAssertTrue(fetchedRecord.age == record.age) + XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. + XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") + } + do { + try XCTAssertNil(Person.fetchOne(db, id: nil)) } } } @@ -749,23 +742,21 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - _ = try Person.find(db, id: -1) - XCTFail("Expected RecordError") - } catch RecordError.recordNotFound(databaseTableName: "persons", key: ["rowid": (-1).databaseValue]) { } - - do { - let fetchedRecord = try Person.find(db, id: record.id!) - XCTAssertTrue(fetchedRecord.id == record.id) - XCTAssertTrue(fetchedRecord.name == record.name) - XCTAssertTrue(fetchedRecord.age == record.age) - XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. - XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") - } - do { - try XCTAssertNil(Person.fetchOne(db, id: nil)) - } + do { + _ = try Person.find(db, id: -1) + XCTFail("Expected RecordError") + } catch RecordError.recordNotFound(databaseTableName: "persons", key: ["rowid": (-1).databaseValue]) { } + + do { + let fetchedRecord = try Person.find(db, id: record.id!) + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertTrue(fetchedRecord.name == record.name) + XCTAssertTrue(fetchedRecord.age == record.age) + XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. + XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") + } + do { + try XCTAssertNil(Person.fetchOne(db, id: nil)) } } } @@ -795,20 +786,18 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertTrue(try cursor.next() == nil) // end } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [Int64] = [] - let cursor = try Person.filter(ids: ids).fetchCursor(db) - try XCTAssertNil(cursor.next()) - } - - do { - let ids = [record1.id!, record2.id!] - let cursor = try Person.filter(ids: ids).fetchCursor(db) - let fetchedRecords = try [cursor.next()!, cursor.next()!] - XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) - XCTAssertTrue(try cursor.next() == nil) // end - } + do { + let ids: [Int64] = [] + let cursor = try Person.filter(ids: ids).fetchCursor(db) + try XCTAssertNil(cursor.next()) + } + + do { + let ids = [record1.id!, record2.id!] + let cursor = try Person.filter(ids: ids).fetchCursor(db) + let fetchedRecords = try [cursor.next()!, cursor.next()!] + XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) + XCTAssertTrue(try cursor.next() == nil) // end } } } @@ -834,19 +823,17 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [Int64] = [] - let fetchedRecords = try Person.filter(ids: ids).fetchAll(db) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let ids = [record1.id!, record2.id!] - let fetchedRecords = try Person.filter(ids: ids).fetchAll(db) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) - } + do { + let ids: [Int64] = [] + let fetchedRecords = try Person.filter(ids: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id!, record2.id!] + let fetchedRecords = try Person.filter(ids: ids).fetchAll(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } } } @@ -872,19 +859,17 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let ids: [Int64] = [] - let fetchedRecords = try Person.filter(ids: ids).fetchSet(db) - XCTAssertEqual(fetchedRecords.count, 0) - } - - do { - let ids = [record1.id!, record2.id!] - let fetchedRecords = try Person.filter(ids: ids).fetchSet(db) - XCTAssertEqual(fetchedRecords.count, 2) - XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) - } + do { + let ids: [Int64] = [] + let fetchedRecords = try Person.filter(ids: ids).fetchSet(db) + XCTAssertEqual(fetchedRecords.count, 0) + } + + do { + let ids = [record1.id!, record2.id!] + let fetchedRecords = try Person.filter(ids: ids).fetchSet(db) + XCTAssertEqual(fetchedRecords.count, 2) + XCTAssertEqual(Set(fetchedRecords.map(\.id)), Set(ids)) } } } @@ -910,18 +895,16 @@ class RecordPrimaryKeyHiddenRowIDTests : GRDBTestCase { XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - do { - let fetchedRecord = try Person.filter(id: record.id!).fetchOne(db)! - XCTAssertTrue(fetchedRecord.id == record.id) - XCTAssertTrue(fetchedRecord.name == record.name) - XCTAssertTrue(fetchedRecord.age == record.age) - XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. - XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") - } - do { - try XCTAssertNil(Person.filter(id: nil).fetchOne(db)) - } + do { + let fetchedRecord = try Person.filter(id: record.id!).fetchOne(db)! + XCTAssertTrue(fetchedRecord.id == record.id) + XCTAssertTrue(fetchedRecord.name == record.name) + XCTAssertTrue(fetchedRecord.age == record.age) + XCTAssertTrue(abs(fetchedRecord.creationDate.timeIntervalSince(record.creationDate)) < 1e-3) // ISO-8601 is precise to the millisecond. + XCTAssertEqual(lastSQLQuery, "SELECT *, \"rowid\" FROM \"persons\" WHERE \"rowid\" = \(record.id!)") + } + do { + try XCTAssertNil(Person.filter(id: nil).fetchOne(db)) } } } diff --git a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift index f8b8c8e10..cf792c686 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyMultipleTests.swift @@ -14,7 +14,7 @@ private class Citizenship : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE citizenships ( personName TEXT NOT NULL, @@ -61,7 +61,9 @@ class RecordPrimaryKeyMultipleTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createCitizenship", migrate: Citizenship.setup) + migrator.registerMigration("createCitizenship") { + try Citizenship.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift index 8582a5e48..a96bd496e 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyNoneTests.swift @@ -14,7 +14,7 @@ private class Item : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE items ( name TEXT, @@ -58,7 +58,9 @@ class RecordPrimaryKeyNoneTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createItem", migrate: Item.setup) + migrator.registerMigration("createItem") { + try Item.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift index eb9023cf2..dabb5c908 100644 --- a/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeyRowIDTests.swift @@ -16,7 +16,7 @@ private class Person : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, @@ -78,7 +78,9 @@ class RecordPrimaryKeyRowIDTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createPerson", migrate: Person.setup) + migrator.registerMigration("createPerson") { + try Person.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift index 69664f729..ca70ff5b4 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleTests.swift @@ -12,7 +12,7 @@ class Pet : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE pets ( UUID TEXT NOT NULL PRIMARY KEY, @@ -51,7 +51,9 @@ class RecordPrimaryKeySingleTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createPet", migrate: Pet.setup) + migrator.registerMigration("createPet") { + try Pet.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift index e1444cdf3..8451feeab 100644 --- a/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift +++ b/Tests/GRDBTests/RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift @@ -11,7 +11,7 @@ class Email : Record, Hashable { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE emails ( email TEXT NOT NULL PRIMARY KEY ON CONFLICT REPLACE, @@ -50,7 +50,9 @@ class RecordPrimaryKeySingleWithReplaceConflictResolutionTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createEmail", migrate: Email.setup) + migrator.registerMigration("createEmail") { + try Email.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordSubClassTests.swift b/Tests/GRDBTests/RecordSubClassTests.swift index fc3d8dc3f..ce82183f5 100644 --- a/Tests/GRDBTests/RecordSubClassTests.swift +++ b/Tests/GRDBTests/RecordSubClassTests.swift @@ -15,7 +15,7 @@ private class Person : Record { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: """ CREATE TABLE persons ( id INTEGER PRIMARY KEY, @@ -105,7 +105,9 @@ class RecordSubClassTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createPerson", migrate: Person.setup) + migrator.registerMigration("createPerson") { + try Person.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift index 0ce7021e0..e9dba8383 100644 --- a/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift +++ b/Tests/GRDBTests/RecordWithColumnNameManglingTests.swift @@ -13,7 +13,7 @@ class BadlyMangledStuff : Record { super.init() } - static func setup(inDatabase db: Database) throws { + static func setup(_ db: Database) throws { try db.execute(sql: "CREATE TABLE stuffs (id INTEGER PRIMARY KEY, name TEXT)") } @@ -48,7 +48,9 @@ class RecordWithColumnNameManglingTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { var migrator = DatabaseMigrator() - migrator.registerMigration("createBadlyMangledStuff", migrate: BadlyMangledStuff.setup) + migrator.registerMigration("createBadlyMangledStuff") { + try BadlyMangledStuff.setup($0) + } try migrator.migrate(dbWriter) } diff --git a/Tests/GRDBTests/RowCopiedFromStatementTests.swift b/Tests/GRDBTests/RowCopiedFromStatementTests.swift index 8bc077c5b..e672d67d5 100644 --- a/Tests/GRDBTests/RowCopiedFromStatementTests.swift +++ b/Tests/GRDBTests/RowCopiedFromStatementTests.swift @@ -287,4 +287,29 @@ class RowCopiedFromStatementTests: RowTestCase { XCTAssertEqual(row.debugDescription, "[null:NULL int:1 double:1.1 string:\"foo\" data:Data(6 bytes)]") } } + + func testCoalesce() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let values = try Row + .fetchAll(db, sql: """ + SELECT 'Artie' AS nickname, 'Arthur' AS name + UNION ALL SELECT NULL, 'Jacob' + UNION ALL SELECT NULL, NULL + """) + .map { row in + [ + row.coalesce(Array()) as String?, + row.coalesce(["nickname"]) as String?, + row.coalesce(["nickname", "name"]) as String?, + row.coalesce([Column("nickname"), Column("name")]) as String?, + ] + } + XCTAssertEqual(values, [ + [nil, "Artie", "Artie", "Artie"], + [nil, nil, "Jacob", "Jacob"], + [nil, nil, nil, nil], + ]) + } + } } diff --git a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift index f840c437a..2554e6e20 100644 --- a/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryLiteralTests.swift @@ -232,4 +232,25 @@ class RowFromDictionaryLiteralTests : RowTestCase { XCTAssertEqual(row.description, "[a:0 b:1 c:2]") XCTAssertEqual(row.debugDescription, "[a:0 b:1 c:2]") } + + func testCoalesce() throws { + let rows: [Row] = [ + ["nickname": "Artie", "name": "Arthur"], + ["nickname": nil, "name": "Jacob"], + ["nickname": nil, "name": nil], + ] + let values = rows.map { row in + [ + row.coalesce(Array()) as String?, + row.coalesce(["nickname"]) as String?, + row.coalesce(["nickname", "name"]) as String?, + row.coalesce([Column("nickname"), Column("name")]) as String?, + ] + } + XCTAssertEqual(values, [ + [nil, "Artie", "Artie", "Artie"], + [nil, nil, "Jacob", "Jacob"], + [nil, nil, nil, nil], + ]) + } } diff --git a/Tests/GRDBTests/RowFromDictionaryTests.swift b/Tests/GRDBTests/RowFromDictionaryTests.swift index 08ddca00f..5625295e4 100644 --- a/Tests/GRDBTests/RowFromDictionaryTests.swift +++ b/Tests/GRDBTests/RowFromDictionaryTests.swift @@ -224,4 +224,25 @@ class RowFromDictionaryTests : RowTestCase { let debugVariants: Set = ["[a:0 b:\"foo\"]", "[b:\"foo\" a:0]"] XCTAssert(debugVariants.contains(row.debugDescription)) } + + func testCoalesce() throws { + let rows = [ + Row(["nickname": "Artie", "name": "Arthur"]), + Row(["nickname": nil, "name": "Jacob"]), + Row(["nickname": nil, "name": nil]), + ] + let values = rows.map { row in + [ + row.coalesce(Array()) as String?, + row.coalesce(["nickname"]) as String?, + row.coalesce(["nickname", "name"]) as String?, + row.coalesce([Column("nickname"), Column("name")]) as String?, + ] + } + XCTAssertEqual(values, [ + [nil, "Artie", "Artie", "Artie"], + [nil, nil, "Jacob", "Jacob"], + [nil, nil, nil, nil], + ]) + } } diff --git a/Tests/GRDBTests/RowFromStatementTests.swift b/Tests/GRDBTests/RowFromStatementTests.swift index c42624a2b..85f17ff24 100644 --- a/Tests/GRDBTests/RowFromStatementTests.swift +++ b/Tests/GRDBTests/RowFromStatementTests.swift @@ -380,4 +380,29 @@ class RowFromStatementTests : RowTestCase { XCTAssertTrue(rowFetched) } } + + func testCoalesce() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.inDatabase { db in + let values = try Array(Row + .fetchCursor(db, sql: """ + SELECT 'Artie' AS nickname, 'Arthur' AS name + UNION ALL SELECT NULL, 'Jacob' + UNION ALL SELECT NULL, NULL + """) + .map { row in + [ + row.coalesce(Array()) as String?, + row.coalesce(["nickname"]) as String?, + row.coalesce(["nickname", "name"]) as String?, + row.coalesce([Column("nickname"), Column("name")]) as String?, + ] + }) + XCTAssertEqual(values, [ + [nil, "Artie", "Artie", "Artie"], + [nil, nil, "Jacob", "Jacob"], + [nil, nil, nil, nil], + ]) + } + } } diff --git a/Tests/GRDBTests/SQLLiteralTests.swift b/Tests/GRDBTests/SQLLiteralTests.swift index e5ef6272b..e059b4a66 100644 --- a/Tests/GRDBTests/SQLLiteralTests.swift +++ b/Tests/GRDBTests/SQLLiteralTests.swift @@ -309,7 +309,21 @@ extension SQLLiteralTests { try makeDatabaseQueue().inDatabase { db in struct Player: TableRecord { } struct AltPlayer: TableRecord { - static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")] + 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 = """ @@ -345,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) @@ -363,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) + } } } @@ -638,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)" @@ -652,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)" @@ -666,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)") @@ -680,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"]) diff --git a/Tests/GRDBTests/SelectStatementTests.swift b/Tests/GRDBTests/SelectStatementTests.swift index b3263d651..95d8d39c4 100644 --- a/Tests/GRDBTests/SelectStatementTests.swift +++ b/Tests/GRDBTests/SelectStatementTests.swift @@ -139,20 +139,20 @@ class SelectStatementTests : GRDBTestCase { func testCachedSelectStatementStepFailure() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - var needsThrow = false + let needsThrowMutex = Mutex(false) db.add(function: DatabaseFunction("bomb", argumentCount: 0, pure: false) { _ in - if needsThrow { + if needsThrowMutex.load() { throw DatabaseError(message: "boom") } return "success" }) let sql = "SELECT bomb()" - needsThrow = false + needsThrowMutex.store(false) XCTAssertEqual(try String.fetchAll(db.cachedStatement(sql: sql)), ["success"]) do { - needsThrow = true + needsThrowMutex.store(true) _ = try String.fetchAll(db.cachedStatement(sql: sql)) XCTFail() } catch let error as DatabaseError { @@ -162,7 +162,7 @@ class SelectStatementTests : GRDBTestCase { XCTAssertEqual(error.description, "SQLite error 1: boom - while executing `\(sql)`") } - needsThrow = false + needsThrowMutex.store(false) XCTAssertEqual(try String.fetchAll(db.cachedStatement(sql: sql)), ["success"]) } } diff --git a/Tests/GRDBTests/SharedValueObservationTests.swift b/Tests/GRDBTests/SharedValueObservationTests.swift index 156960805..4a8d629a5 100644 --- a/Tests/GRDBTests/SharedValueObservationTests.swift +++ b/Tests/GRDBTests/SharedValueObservationTests.swift @@ -39,12 +39,12 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated withExtendedLifetime(sharedObservation) { sharedObservation in do { - var value: Int? + let valueMutex: Mutex = Mutex(nil) let cancellable = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value = $0 }) + onChange: { value in valueMutex.store(value) }) - XCTAssertEqual(value, 0) + XCTAssertEqual(valueMutex.load(), 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable.cancel() @@ -52,12 +52,12 @@ class SharedValueObservationTests: GRDBTestCase { } do { - var value: Int? + let valueMutex: Mutex = Mutex(nil) let cancellable = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value = $0 }) + onChange: { value in valueMutex.store(value) }) - XCTAssertEqual(value, 0) + XCTAssertEqual(valueMutex.load(), 0) XCTAssertEqual(log.flush(), []) cancellable.cancel() @@ -91,21 +91,21 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated withExtendedLifetime(sharedObservation) { sharedObservation in do { - var value1: Int? - var value2: Int? + let value1Mutex: Mutex = Mutex(nil) + let value2Mutex: Mutex = Mutex(nil) let cancellable1 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in - value1 = value + value1Mutex.store(value) _ = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in - value2 = value + value2Mutex.store(value) }) }) - XCTAssertEqual(value1, 0) - XCTAssertEqual(value2, 0) + XCTAssertEqual(value1Mutex.load(), 0) + XCTAssertEqual(value2Mutex.load(), 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable1.cancel() @@ -120,10 +120,6 @@ class SharedValueObservationTests: GRDBTestCase { #if canImport(Combine) func test_immediate_publisher() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -175,12 +171,12 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated withExtendedLifetime(sharedObservation) { sharedObservation in do { - var value: Int? + let valueMutex: Mutex = Mutex(nil) let cancellable = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value = $0 }) + onChange: { value in valueMutex.store(value) }) - XCTAssertEqual(value, 0) + XCTAssertEqual(valueMutex.load(), 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable.cancel() @@ -188,12 +184,12 @@ class SharedValueObservationTests: GRDBTestCase { } do { - var value: Int? + let valueMutex: Mutex = Mutex(nil) let cancellable = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { value = $0 }) + onChange: { value in valueMutex.store(value) }) - XCTAssertEqual(value, 0) + XCTAssertEqual(valueMutex.load(), 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable.cancel() @@ -226,21 +222,21 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated withExtendedLifetime(sharedObservation) { sharedObservation in - var value1: Int? - var value2: Int? + let value1Mutex: Mutex = Mutex(nil) + let value2Mutex: Mutex = Mutex(nil) let cancellable1 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in - value1 = value + value1Mutex.store(value) _ = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, onChange: { value in - value2 = value + value2Mutex.store(value) }) }) - XCTAssertEqual(value1, 0) - XCTAssertEqual(value2, 0) + XCTAssertEqual(value1Mutex.load(), 0) + XCTAssertEqual(value2Mutex.load(), 0) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 0"]) cancellable1.cancel() @@ -273,40 +269,40 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated try withExtendedLifetime(sharedObservation) { sharedObservation in // --- Start observation 1 - var values1: [Int] = [] + let values1Mutex: Mutex<[Int]> = Mutex([]) let exp1 = expectation(description: "") exp1.expectedFulfillmentCount = 2 exp1.assertForOverFulfill = false let cancellable1 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { - values1.append($0) + onChange: { value in + values1Mutex.withLock { $0.append(value) } exp1.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp1], timeout: 1) - XCTAssertEqual(values1, [0, 1]) + XCTAssertEqual(values1Mutex.load(), [0, 1]) XCTAssertEqual(log.flush(), [ "start", "fetch", "tracked region: player(*)", "value: 0", "database did change", "fetch", "value: 1"]) // --- Start observation 2 - var values2: [Int] = [] + let values2Mutex: Mutex<[Int]> = Mutex([]) let exp2 = expectation(description: "") exp2.expectedFulfillmentCount = 2 exp2.assertForOverFulfill = false let cancellable2 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { - values2.append($0) + onChange: { value in + values2Mutex.withLock { $0.append(value) } exp2.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp2], timeout: 1) - XCTAssertEqual(values1, [0, 1, 2]) - XCTAssertEqual(values2, [1, 2]) + XCTAssertEqual(values1Mutex.load(), [0, 1, 2]) + XCTAssertEqual(values2Mutex.load(), [1, 2]) XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"]) // --- Stop observation 1 @@ -314,22 +310,22 @@ class SharedValueObservationTests: GRDBTestCase { XCTAssertEqual(log.flush(), []) // --- Start observation 3 - var values3: [Int] = [] + let values3Mutex: Mutex<[Int]> = Mutex([]) let exp3 = expectation(description: "") exp3.expectedFulfillmentCount = 2 exp3.assertForOverFulfill = false let cancellable3 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { - values3.append($0) + onChange: { value in + values3Mutex.withLock { $0.append(value) } exp3.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp3], timeout: 1) - XCTAssertEqual(values1, [0, 1, 2]) - XCTAssertEqual(values2, [1, 2, 3]) - XCTAssertEqual(values3, [2, 3]) + XCTAssertEqual(values1Mutex.load(), [0, 1, 2]) + XCTAssertEqual(values2Mutex.load(), [1, 2, 3]) + XCTAssertEqual(values3Mutex.load(), [2, 3]) XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"]) // --- Stop observation 2 @@ -355,7 +351,7 @@ class SharedValueObservationTests: GRDBTestCase { } let log = Log() - var sharedObservation: SharedValueObservation? = ValueObservation + nonisolated(unsafe) var sharedObservation: SharedValueObservation? = ValueObservation .tracking(Table("player").fetchCount) .print(to: log) .shared( @@ -397,10 +393,6 @@ class SharedValueObservationTests: GRDBTestCase { #if canImport(Combine) func test_async_publisher() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -452,40 +444,40 @@ class SharedValueObservationTests: GRDBTestCase { // We want to control when the shared observation is deallocated try withExtendedLifetime(sharedObservation) { sharedObservation in // --- Start observation 1 - var values1: [Int] = [] + let values1Mutex: Mutex<[Int]> = Mutex([]) let exp1 = expectation(description: "") exp1.expectedFulfillmentCount = 2 exp1.assertForOverFulfill = false let cancellable1 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { - values1.append($0) + onChange: { value in + values1Mutex.withLock { $0.append(value) } exp1.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp1], timeout: 1) - XCTAssertEqual(values1, [0, 1]) + XCTAssertEqual(values1Mutex.load(), [0, 1]) XCTAssertEqual(log.flush(), [ "start", "fetch", "tracked region: player(*)", "value: 0", "database did change", "fetch", "value: 1"]) // --- Start observation 2 - var values2: [Int] = [] + let values2Mutex: Mutex<[Int]> = Mutex([]) let exp2 = expectation(description: "") exp2.expectedFulfillmentCount = 2 exp2.assertForOverFulfill = false let cancellable2 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { - values2.append($0) + onChange: { value in + values2Mutex.withLock { $0.append(value) } exp2.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp2], timeout: 1) - XCTAssertEqual(values1, [0, 1, 2]) - XCTAssertEqual(values2, [1, 2]) + XCTAssertEqual(values1Mutex.load(), [0, 1, 2]) + XCTAssertEqual(values2Mutex.load(), [1, 2]) XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"]) // --- Stop observation 1 @@ -493,22 +485,22 @@ class SharedValueObservationTests: GRDBTestCase { XCTAssertEqual(log.flush(), []) // --- Start observation 3 - var values3: [Int] = [] + let values3Mutex: Mutex<[Int]> = Mutex([]) let exp3 = expectation(description: "") exp3.expectedFulfillmentCount = 2 exp3.assertForOverFulfill = false let cancellable3 = sharedObservation!.start( onError: { XCTFail("Unexpected error \($0)") }, - onChange: { - values3.append($0) + onChange: { value in + values3Mutex.withLock { $0.append(value) } exp3.fulfill() }) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} wait(for: [exp3], timeout: 1) - XCTAssertEqual(values1, [0, 1, 2]) - XCTAssertEqual(values2, [1, 2, 3]) - XCTAssertEqual(values3, [2, 3]) + XCTAssertEqual(values1Mutex.load(), [0, 1, 2]) + XCTAssertEqual(values2Mutex.load(), [1, 2, 3]) + XCTAssertEqual(values3Mutex.load(), [2, 3]) XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"]) // --- Stop observation 2 @@ -525,12 +517,7 @@ class SharedValueObservationTests: GRDBTestCase { XCTAssertEqual(log.flush(), []) } -#if canImport(Combine) - func test_error_recovery_observationLifetime() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - + func test_task_observationLifetime() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -539,10 +526,233 @@ class SharedValueObservationTests: GRDBTestCase { } let log = Log() - var fetchError: Error? = nil + var sharedObservation: SharedValueObservation? = ValueObservation + .tracking(Table("player").fetchCount) + .print(to: log) + .shared( + in: dbQueue, + scheduling: .task, + extent: .observationLifetime) + XCTAssertEqual(log.flush(), []) + + // We want to control when the shared observation is deallocated + try withExtendedLifetime(sharedObservation) { sharedObservation in + // --- Start observation 1 + let values1Mutex: Mutex<[Int]> = Mutex([]) + let exp1 = expectation(description: "") + exp1.expectedFulfillmentCount = 2 + exp1.assertForOverFulfill = false + let cancellable1 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + values1Mutex.withLock { $0.append(value) } + exp1.fulfill() + }) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + wait(for: [exp1], timeout: 1) + XCTAssertEqual(values1Mutex.load(), [0, 1]) + XCTAssertEqual(log.flush(), [ + "start", "fetch", "tracked region: player(*)", "value: 0", + "database did change", "fetch", "value: 1"]) + + // --- Start observation 2 + let values2Mutex: Mutex<[Int]> = Mutex([]) + let exp2 = expectation(description: "") + exp2.expectedFulfillmentCount = 2 + exp2.assertForOverFulfill = false + let cancellable2 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + values2Mutex.withLock { $0.append(value) } + exp2.fulfill() + }) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + wait(for: [exp2], timeout: 1) + XCTAssertEqual(values1Mutex.load(), [0, 1, 2]) + XCTAssertEqual(values2Mutex.load(), [1, 2]) + XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"]) + + // --- Stop observation 1 + cancellable1.cancel() + XCTAssertEqual(log.flush(), []) + + // --- Start observation 3 + let values3Mutex: Mutex<[Int]> = Mutex([]) + let exp3 = expectation(description: "") + exp3.expectedFulfillmentCount = 2 + exp3.assertForOverFulfill = false + let cancellable3 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + values3Mutex.withLock { $0.append(value) } + exp3.fulfill() + }) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + wait(for: [exp3], timeout: 1) + XCTAssertEqual(values1Mutex.load(), [0, 1, 2]) + XCTAssertEqual(values2Mutex.load(), [1, 2, 3]) + XCTAssertEqual(values3Mutex.load(), [2, 3]) + XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"]) + + // --- Stop observation 2 + cancellable2.cancel() + XCTAssertEqual(log.flush(), []) + + // --- Stop observation 3 + cancellable3.cancel() + XCTAssertEqual(log.flush(), []) + } + + // --- Release shared observation + sharedObservation = nil + XCTAssertEqual(log.flush(), ["cancel"]) + } + +#if canImport(Combine) + func test_task_publisher() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let publisher = ValueObservation + .tracking(Table("player").fetchCount) + .shared(in: dbQueue, scheduling: .task) + .publisher() + + do { + let recorder = publisher.record() + try XCTAssert(recorder.availableElements.get().isEmpty) + try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 0) + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1) + } + + do { + let recorder = publisher.record() + try XCTAssert(recorder.availableElements.get().isEmpty) + try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1) + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 2) + } + } +#endif + + func test_task_whileObserved() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let log = Log() + var sharedObservation: SharedValueObservation? = ValueObservation + .tracking(Table("player").fetchCount) + .print(to: log) + .shared( + in: dbQueue, + scheduling: .task, + extent: .whileObserved) + XCTAssertEqual(log.flush(), []) + + // We want to control when the shared observation is deallocated + try withExtendedLifetime(sharedObservation) { sharedObservation in + // --- Start observation 1 + let values1Mutex: Mutex<[Int]> = Mutex([]) + let exp1 = expectation(description: "") + exp1.expectedFulfillmentCount = 2 + exp1.assertForOverFulfill = false + let cancellable1 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + values1Mutex.withLock { $0.append(value) } + exp1.fulfill() + }) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + wait(for: [exp1], timeout: 1) + XCTAssertEqual(values1Mutex.load(), [0, 1]) + XCTAssertEqual(log.flush(), [ + "start", "fetch", "tracked region: player(*)", "value: 0", + "database did change", "fetch", "value: 1"]) + + // --- Start observation 2 + let values2Mutex: Mutex<[Int]> = Mutex([]) + let exp2 = expectation(description: "") + exp2.expectedFulfillmentCount = 2 + exp2.assertForOverFulfill = false + let cancellable2 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + values2Mutex.withLock { $0.append(value) } + exp2.fulfill() + }) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + wait(for: [exp2], timeout: 1) + XCTAssertEqual(values1Mutex.load(), [0, 1, 2]) + XCTAssertEqual(values2Mutex.load(), [1, 2]) + XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 2"]) + + // --- Stop observation 1 + cancellable1.cancel() + XCTAssertEqual(log.flush(), []) + + // --- Start observation 3 + let values3Mutex: Mutex<[Int]> = Mutex([]) + let exp3 = expectation(description: "") + exp3.expectedFulfillmentCount = 2 + exp3.assertForOverFulfill = false + let cancellable3 = sharedObservation!.start( + onError: { XCTFail("Unexpected error \($0)") }, + onChange: { value in + values3Mutex.withLock { $0.append(value) } + exp3.fulfill() + }) + + try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} + wait(for: [exp3], timeout: 1) + XCTAssertEqual(values1Mutex.load(), [0, 1, 2]) + XCTAssertEqual(values2Mutex.load(), [1, 2, 3]) + XCTAssertEqual(values3Mutex.load(), [2, 3]) + XCTAssertEqual(log.flush(), ["database did change", "fetch", "value: 3"]) + + // --- Stop observation 2 + cancellable2.cancel() + XCTAssertEqual(log.flush(), []) + + // --- Stop observation 3 + cancellable3.cancel() + XCTAssertEqual(log.flush(), ["cancel"]) + } + + // --- Release shared observation + sharedObservation = nil + XCTAssertEqual(log.flush(), []) + } + +#if canImport(Combine) + func test_error_recovery_observationLifetime() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let log = Log() + let fetchErrorMutex: Mutex = Mutex(nil) let publisher = ValueObservation .tracking { db -> Int in - if let error = fetchError { throw error } + try fetchErrorMutex.withLock { error in + if let error { throw error } + } return try Table("player").fetchCount(db) } .print(to: log) @@ -556,7 +766,7 @@ class SharedValueObservationTests: GRDBTestCase { try XCTAssertEqual(wait(for: recorder1.next(), timeout: 1), 0) try XCTAssertEqual(wait(for: recorder2.next(), timeout: 1), 0) - fetchError = TestError() + fetchErrorMutex.store(TestError()) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") } @@ -573,7 +783,7 @@ class SharedValueObservationTests: GRDBTestCase { } do { - fetchError = nil + fetchErrorMutex.store(nil) let recorder = publisher.record() if case .finished = try wait(for: recorder.completion, timeout: 1) { XCTFail("Expected error") } XCTAssertEqual(log.flush(), []) @@ -583,10 +793,6 @@ class SharedValueObservationTests: GRDBTestCase { #if canImport(Combine) func test_error_recovery_whileObserved() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Combine is not available") - } - let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -595,10 +801,12 @@ class SharedValueObservationTests: GRDBTestCase { } let log = Log() - var fetchError: Error? = nil + let fetchErrorMutex: Mutex = Mutex(nil) let publisher = ValueObservation .tracking { db -> Int in - if let error = fetchError { throw error } + try fetchErrorMutex.withLock { error in + if let error { throw error } + } return try Table("player").fetchCount(db) } .print(to: log) @@ -612,7 +820,7 @@ class SharedValueObservationTests: GRDBTestCase { try XCTAssertEqual(wait(for: recorder1.next(), timeout: 1), 0) try XCTAssertEqual(wait(for: recorder2.next(), timeout: 1), 0) - fetchError = TestError() + fetchErrorMutex.store(TestError()) try dbQueue.write { try $0.execute(sql: "INSERT INTO player DEFAULT VALUES")} if case .finished = try wait(for: recorder1.completion, timeout: 1) { XCTFail("Expected error") } @@ -629,7 +837,7 @@ class SharedValueObservationTests: GRDBTestCase { } do { - fetchError = nil + fetchErrorMutex.store(nil) let recorder = publisher.record() try XCTAssertEqual(wait(for: recorder.next(), timeout: 1), 1) XCTAssertEqual(log.flush(), ["start", "fetch", "tracked region: player(*)", "value: 1"]) @@ -637,8 +845,7 @@ class SharedValueObservationTests: GRDBTestCase { } #endif - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - func testAsyncAwait() async throws { + func testAsyncAwait_mainQueue() async throws { let dbQueue = try makeDatabaseQueue() try await dbQueue.write { db in try db.create(table: "player") { t in @@ -656,6 +863,25 @@ class SharedValueObservationTests: GRDBTestCase { break } } + + func testAsyncAwait_task() async throws { + let dbQueue = try makeDatabaseQueue() + try await dbQueue.write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let values = ValueObservation + .tracking(Table("player").fetchCount) + .shared(in: dbQueue, scheduling: .task) + .values() + + for try await value in values { + XCTAssertEqual(value, 0) + break + } + } } private class Log: TextOutputStream { diff --git a/Tests/GRDBTests/SingletonRecordTest.swift b/Tests/GRDBTests/SingletonRecordTest.swift index a3fb0766e..0be0c8f09 100644 --- a/Tests/GRDBTests/SingletonRecordTest.swift +++ b/Tests/GRDBTests/SingletonRecordTest.swift @@ -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 diff --git a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift index ed94e9e69..cee0f6e95 100644 --- a/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift +++ b/Tests/GRDBTests/StatementColumnConvertibleFetchTests.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import XCTest import GRDB diff --git a/Tests/GRDBTests/TableDefinitionTests.swift b/Tests/GRDBTests/TableDefinitionTests.swift index 0092b26d7..30e8174ea 100644 --- a/Tests/GRDBTests/TableDefinitionTests.swift +++ b/Tests/GRDBTests/TableDefinitionTests.swift @@ -47,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 @@ -195,7 +195,7 @@ class TableDefinitionTests: GRDBTestCase { func testColumnIndexed() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "test") { t in t.column("a", .integer).indexed() t.column("b", .integer).indexed() @@ -210,7 +210,7 @@ class TableDefinitionTests: GRDBTestCase { func testColumnIndexedInheritsIfNotExistsFlag() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in - sqlQueries.removeAll() + clearSQLQueries() try db.create(table: "test", options: [.ifNotExists]) { t in t.column("a", .integer).indexed() t.column("b", .integer).indexed() @@ -358,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 @@ -724,7 +724,7 @@ class TableDefinitionTests: GRDBTestCase { t.column("a", .text) } - sqlQueries.removeAll() + clearSQLQueries() try db.alter(table: "test") { t in t.add(column: "b", .text) t.add(column: "c", .integer).notNull().defaults(to: 1) @@ -751,7 +751,7 @@ class TableDefinitionTests: GRDBTestCase { t.column("a", .text) } - sqlQueries.removeAll() + clearSQLQueries() try db.alter(table: "hiddenRowIdTable") { t in t.add(column: "ref").references("hiddenRowIdTable") } @@ -766,7 +766,7 @@ class TableDefinitionTests: GRDBTestCase { t.column("a", .text) } - sqlQueries.removeAll() + clearSQLQueries() try db.alter(table: "explicitPrimaryKey") { t in t.add(column: "ref").references("explicitPrimaryKey") } @@ -793,21 +793,16 @@ 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") } - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 13, tvOS 13, watchOS 6, *) else { - throw XCTSkip("ALTER TABLE RENAME COLUMN is not available") - } - #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test") { t in t.column("a", .text) } - sqlQueries.removeAll() + clearSQLQueries() try db.alter(table: "test") { t in t.rename(column: "a", to: "b") t.add(column: "c") @@ -821,14 +816,9 @@ 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") } - #if !GRDBCUSTOMSQLITE && !GRDBCIPHER - guard #available(iOS 13, tvOS 13, watchOS 6, *) else { - throw XCTSkip("ALTER TABLE RENAME COLUMN is not available") - } - #endif let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.create(table: "test") { t in @@ -845,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 @@ -861,7 +851,7 @@ class TableDefinitionTests: GRDBTestCase { t.column("c", .text) } - sqlQueries.removeAll() + clearSQLQueries() try db.alter(table: "test") { t in t.add(column: "d", .integer).generatedAs(sql: "a*abs(b)", .virtual) t.add(column: "e", .text).generatedAs(sql: "substr(c,b,b+1)", .virtual) @@ -880,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 @@ -895,7 +885,7 @@ class TableDefinitionTests: GRDBTestCase { t.column("b", .text) } - sqlQueries.removeAll() + clearSQLQueries() try db.alter(table: "test") { t in t.drop(column: "b") } @@ -904,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 diff --git a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift index a141e18e9..8df2e73a6 100644 --- a/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift +++ b/Tests/GRDBTests/TableRecord+QueryInterfaceRequestTests.swift @@ -1,17 +1,19 @@ import XCTest import GRDB -private struct Col { - static let id = Column("id") - static let name = Column("name") - static let age = Column("age") - static let readerId = Column("readerId") -} - private struct Reader : TableRecord { static let databaseTableName = "readers" + + struct Columns { + static let id = Column("id") + static let name = Column("name") + static let age = Column("age") + static let readerId = Column("readerId") + } } +private typealias Columns = Reader.Columns + class TableRecordQueryInterfaceRequestTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { @@ -39,38 +41,82 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { XCTAssertEqual(try Reader.all().reversed().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") - XCTAssertEqual(try Reader.order(Col.name).fetchCount(db), 0) + XCTAssertEqual(try Reader.order(Columns.name).fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + XCTAssertEqual(try Reader.order { $0.name }.fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") XCTAssertEqual(try Reader.limit(10).fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT * FROM \"readers\" LIMIT 10)") - XCTAssertEqual(try Reader.filter(Col.age == 42).fetchCount(db), 0) + XCTAssertEqual(try Reader.filter(Columns.age == 42).fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\" WHERE \"age\" = 42") + XCTAssertEqual(try Reader.filter { $0.age == 42 }.fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\" WHERE \"age\" = 42") XCTAssertEqual(try Reader.all().distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT * FROM \"readers\")") - XCTAssertEqual(try Reader.select(Col.name).fetchCount(db), 0) + XCTAssertEqual(try Reader.select(Columns.name).fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + XCTAssertEqual(try Reader.select { $0.name }.fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") - XCTAssertEqual(try Reader.select(Col.name).distinct().fetchCount(db), 0) + XCTAssertEqual(try Reader.select(Columns.name).distinct().fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"name\") FROM \"readers\"") + XCTAssertEqual(try Reader.select { $0.name }.distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"name\") FROM \"readers\"") - XCTAssertEqual(try Reader.select(Col.age * 2).distinct().fetchCount(db), 0) + XCTAssertEqual(try Reader.select(Columns.age * 2).distinct().fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") + XCTAssertEqual(try Reader.select { $0.age * 2 }.distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") - XCTAssertEqual(try Reader.select((Col.age * 2).forKey("ignored")).distinct().fetchCount(db), 0) + XCTAssertEqual(try Reader.select((Columns.age * 2).forKey("ignored")).distinct().fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") + XCTAssertEqual(try Reader.select { ($0.age * 2).forKey("ignored") }.distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(DISTINCT \"age\" * 2) FROM \"readers\"") - XCTAssertEqual(try Reader.select(Col.name, Col.age).fetchCount(db), 0) + XCTAssertEqual(try Reader.select(Columns.name, Columns.age).fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") + XCTAssertEqual(try Reader.select { [$0.name, $0.age] }.fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM \"readers\"") - XCTAssertEqual(try Reader.select(Col.name, Col.age).distinct().fetchCount(db), 0) + XCTAssertEqual(try Reader.select(Columns.name, Columns.age).distinct().fetchCount(db), 0) + XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT \"name\", \"age\" FROM \"readers\")") + XCTAssertEqual(try Reader.select { [$0.name, $0.age] }.distinct().fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT DISTINCT \"name\", \"age\" FROM \"readers\")") - XCTAssertEqual(try Reader.select(max(Col.age)).group(Col.name).fetchCount(db), 0) + XCTAssertEqual(try Reader.select(max(Columns.age)).group(Columns.name).fetchCount(db), 0) XCTAssertEqual(lastSQLQuery, "SELECT COUNT(*) FROM (SELECT MAX(\"age\") FROM \"readers\" GROUP BY \"name\")") + XCTAssertEqual(try Reader.select { max($0.age) }.group { $0.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\")") } } @@ -154,21 +200,36 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { try db.execute(sql: "INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Arthur", 42]) try db.execute(sql: "INSERT INTO readers (name, age) VALUES (?, ?)", arguments: ["Barbara", 36]) - let request = Reader.select(Col.name, Col.id - 1) - let rows = try Row.fetchAll(db, request) - XCTAssertEqual(lastSQLQuery, "SELECT \"name\", \"id\" - 1 FROM \"readers\"") - XCTAssertEqual(rows.count, 2) - XCTAssertEqual(rows[0][0] as String, "Arthur") - XCTAssertEqual(rows[0][1] as Int64, 0) - XCTAssertEqual(rows[1][0] as String, "Barbara") - XCTAssertEqual(rows[1][1] as Int64, 1) + do { + let request = Reader.select(Columns.name, Columns.id - 1) + let rows = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, "SELECT \"name\", \"id\" - 1 FROM \"readers\"") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0][0] as String, "Arthur") + XCTAssertEqual(rows[0][1] as Int64, 0) + XCTAssertEqual(rows[1][0] as String, "Barbara") + XCTAssertEqual(rows[1][1] as Int64, 1) + } + do { + let request = Reader.select { [$0.name, $0.id - 1] } + let rows = try Row.fetchAll(db, request) + XCTAssertEqual(lastSQLQuery, "SELECT \"name\", \"id\" - 1 FROM \"readers\"") + XCTAssertEqual(rows.count, 2) + XCTAssertEqual(rows[0][0] as String, "Arthur") + XCTAssertEqual(rows[0][1] as Int64, 0) + XCTAssertEqual(rows[1][0] as String, "Barbara") + XCTAssertEqual(rows[1][1] as Int64, 1) + } } } func testMultipleSelect() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, Reader.select(Col.age).select(Col.name)), + sql(dbQueue, Reader.select(Columns.age).select(Columns.name)), + "SELECT \"name\" FROM \"readers\"") + XCTAssertEqual( + sql(dbQueue, Reader.select { $0.age }.select { $0.name }), "SELECT \"name\" FROM \"readers\"") } @@ -237,35 +298,104 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { func testSort() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, Reader.order(Col.age)), + sql(dbQueue, Reader.order(Columns.age)), "SELECT * FROM \"readers\" ORDER BY \"age\"") XCTAssertEqual( - sql(dbQueue, Reader.order(Col.age.asc)), + sql(dbQueue, Reader.order { $0.age }), + "SELECT * FROM \"readers\" ORDER BY \"age\"") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, Reader.order(\.age)), + "SELECT * FROM \"readers\" ORDER BY \"age\"") + #endif + + XCTAssertEqual( + sql(dbQueue, Reader.order(Columns.age.asc)), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC") XCTAssertEqual( - sql(dbQueue, Reader.order(Col.age.desc)), + sql(dbQueue, Reader.order { $0.age.asc }), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, Reader.order(\.age.asc)), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC") + #endif + + XCTAssertEqual( + sql(dbQueue, Reader.order(Columns.age.desc)), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") XCTAssertEqual( - sql(dbQueue, Reader.order(Col.age, Col.name.desc)), + sql(dbQueue, Reader.order { $0.age.desc }), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, Reader.order(\.age.desc)), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC") + #endif + + XCTAssertEqual( + sql(dbQueue, Reader.order(Columns.age, Columns.name.desc)), "SELECT * FROM \"readers\" ORDER BY \"age\", \"name\" DESC") XCTAssertEqual( - sql(dbQueue, Reader.order(abs(Col.age))), + sql(dbQueue, Reader.order { [$0.age, $0.name.desc] }), + "SELECT * FROM \"readers\" ORDER BY \"age\", \"name\" DESC") + + XCTAssertEqual( + sql(dbQueue, Reader.order(abs(Columns.age))), "SELECT * FROM \"readers\" ORDER BY ABS(\"age\")") + XCTAssertEqual( + sql(dbQueue, Reader.order { abs($0.age) }), + "SELECT * FROM \"readers\" ORDER BY ABS(\"age\")") + #if GRDBCUSTOMSQLITE XCTAssertEqual( - sql(dbQueue, Reader.order(Col.age.ascNullsLast)), + sql(dbQueue, Reader.order(Columns.age.ascNullsLast)), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") XCTAssertEqual( - sql(dbQueue, Reader.order(Col.age.descNullsFirst)), + sql(dbQueue, Reader.order { $0.age.ascNullsLast }), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, Reader.order(\.age.ascNullsLast)), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") + #endif + + XCTAssertEqual( + sql(dbQueue, Reader.order(Columns.age.descNullsFirst)), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + XCTAssertEqual( + sql(dbQueue, Reader.order { $0.age.descNullsFirst }), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, Reader.order(\.age.descNullsFirst)), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + #endif #elseif !GRDBCIPHER - if #available(iOS 14, macOS 10.16, tvOS 14, watchOS 7, *) { + if #available(iOS 14, macOS 10.16, tvOS 14, *) { XCTAssertEqual( - sql(dbQueue, Reader.order(Col.age.ascNullsLast)), + sql(dbQueue, Reader.order(Columns.age.ascNullsLast)), "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") XCTAssertEqual( - sql(dbQueue, Reader.order(Col.age.descNullsFirst)), + sql(dbQueue, Reader.order { $0.age.ascNullsLast }), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, Reader.order(\.age.ascNullsLast)), + "SELECT * FROM \"readers\" ORDER BY \"age\" ASC NULLS LAST") + #endif + + XCTAssertEqual( + sql(dbQueue, Reader.order(Columns.age.descNullsFirst)), "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + XCTAssertEqual( + sql(dbQueue, Reader.order { $0.age.descNullsFirst }), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + #if compiler(>=6.1) + XCTAssertEqual( + sql(dbQueue, Reader.order(\.age.descNullsFirst)), + "SELECT * FROM \"readers\" ORDER BY \"age\" DESC NULLS FIRST") + #endif } #endif } @@ -273,7 +403,10 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { func testMultipleSort() throws { let dbQueue = try makeDatabaseQueue() XCTAssertEqual( - sql(dbQueue, Reader.order(Col.age).order(Col.name)), + sql(dbQueue, Reader.order(Columns.age).order(Columns.name)), + "SELECT * FROM \"readers\" ORDER BY \"name\"") + XCTAssertEqual( + sql(dbQueue, Reader.order { $0.age }.order { $0.name }), "SELECT * FROM \"readers\" ORDER BY \"name\"") } @@ -357,10 +490,6 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { } func testExistsIdentifiable() throws { - guard #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) else { - throw XCTSkip("Identifiable is not available") - } - let dbQueue = try makeDatabaseQueue() try dbQueue.inTransaction { db in struct Player: TableRecord, Identifiable { @@ -386,7 +515,7 @@ class TableRecordQueryInterfaceRequestTests: GRDBTestCase { try XCTAssertFalse(Player.exists(db, id: 1)) XCTAssertEqual(lastSQLQuery, "SELECT EXISTS (SELECT * FROM \"player\" WHERE \"id\" = 1)") - sqlQueries.removeAll() + clearSQLQueries() try XCTAssertFalse(Player.exists(db, id: nil)) XCTAssertNil(lastSQLQuery) // Database not hit diff --git a/Tests/GRDBTests/TableRecordDeleteTests.swift b/Tests/GRDBTests/TableRecordDeleteTests.swift index e45252a55..a2fe139fe 100644 --- a/Tests/GRDBTests/TableRecordDeleteTests.swift +++ b/Tests/GRDBTests/TableRecordDeleteTests.swift @@ -6,7 +6,6 @@ private struct Hacker : TableRecord { var id: Int64? // Optional } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Hacker: Identifiable { } private struct Person : Codable, PersistableRecord, FetchableRecord, Hashable { @@ -14,9 +13,13 @@ private struct Person : Codable, PersistableRecord, FetchableRecord, Hashable { var id: Int64 // Non-optional var name: String var email: String + + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Person: Identifiable { } private struct Citizenship : TableRecord { @@ -46,23 +49,23 @@ class TableRecordDeleteTests: GRDBTestCase { XCTAssertTrue(deleted) XCTAssertEqual(try Hacker.fetchCount(db), 0) - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { + try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [1, "Arthur"]) + try XCTAssertFalse(Hacker.deleteOne(db, id: nil)) + deleted = try Hacker.deleteOne(db, id: 1) + XCTAssertTrue(deleted) + XCTAssertEqual(try Hacker.fetchCount(db), 0) + + do { try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [1, "Arthur"]) - try XCTAssertFalse(Hacker.deleteOne(db, id: nil)) - deleted = try Hacker.deleteOne(db, id: 1) - XCTAssertTrue(deleted) - XCTAssertEqual(try Hacker.fetchCount(db), 0) + try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [2, "Barbara"]) + try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [3, "Craig"]) + let deletedCount = try Hacker.deleteAll(db, keys: [2, 3, 4]) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"hackers\" WHERE \"rowid\" IN (2, 3, 4)") + XCTAssertEqual(deletedCount, 2) + XCTAssertEqual(try Hacker.fetchCount(db), 1) } - try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [1, "Arthur"]) - try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [2, "Barbara"]) - try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [3, "Craig"]) - let deletedCount = try Hacker.deleteAll(db, keys: [2, 3, 4]) - XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"hackers\" WHERE \"rowid\" IN (2, 3, 4)") - XCTAssertEqual(deletedCount, 2) - XCTAssertEqual(try Hacker.fetchCount(db), 1) - - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { + do { try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [2, "Barbara"]) try db.execute(sql: "INSERT INTO hackers (rowid, name) VALUES (?, ?)", arguments: [3, "Craig"]) let deletedCount = try Hacker.deleteAll(db, ids: [2, 3, 4]) @@ -85,22 +88,22 @@ class TableRecordDeleteTests: GRDBTestCase { XCTAssertTrue(deleted) XCTAssertEqual(try Person.fetchCount(db), 0) - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { + try db.execute(sql: "INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) + deleted = try Person.deleteOne(db, id: 1) + XCTAssertTrue(deleted) + XCTAssertEqual(try Person.fetchCount(db), 0) + + do { try db.execute(sql: "INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) - deleted = try Person.deleteOne(db, id: 1) - XCTAssertTrue(deleted) - XCTAssertEqual(try Person.fetchCount(db), 0) + try db.execute(sql: "INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"]) + try db.execute(sql: "INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"]) + let deletedCount = try Person.deleteAll(db, keys: [2, 3, 4]) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (2, 3, 4)") + XCTAssertEqual(deletedCount, 2) + XCTAssertEqual(try Person.fetchCount(db), 1) } - try db.execute(sql: "INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [1, "Arthur", "arthur@example.com"]) - try db.execute(sql: "INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"]) - try db.execute(sql: "INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"]) - let deletedCount = try Person.deleteAll(db, keys: [2, 3, 4]) - XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (2, 3, 4)") - XCTAssertEqual(deletedCount, 2) - XCTAssertEqual(try Person.fetchCount(db), 1) - - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { + do { try db.execute(sql: "INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [2, "Barbara", "barbara@example.com"]) try db.execute(sql: "INSERT INTO persons (id, name, email) VALUES (?, ?, ?)", arguments: [3, "Craig", "craig@example.com"]) let deletedCount = try Person.deleteAll(db, ids: [2, 3, 4]) @@ -181,7 +184,7 @@ class TableRecordDeleteTests: GRDBTestCase { try Person.deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\"") - try Person.filter(Column("name") == "Arthur").deleteAll(db) + try Person.filter { $0.name == "Arthur" }.deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"name\" = 'Arthur'") try Person.filter(key: 1).deleteAll(db) @@ -189,38 +192,36 @@ class TableRecordDeleteTests: GRDBTestCase { try Person.filter(keys: [1, 2]).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2)") - - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - try Person.filter(id: 1).deleteAll(db) - XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1") - - try Person.filter(ids: [1, 2]).deleteAll(db) - XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2)") - } - + + try Person.filter(id: 1).deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1") + + try Person.filter(ids: [1, 2]).deleteAll(db) + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2)") + try Person.filter(sql: "id = 1").deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE id = 1") - try Person.filter(sql: "id = 1").filter(Column("name") == "Arthur").deleteAll(db) + try Person.filter(sql: "id = 1").filter { $0.name == "Arthur" }.deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (id = 1) AND (\"name\" = 'Arthur')") - try Person.select(Column("name")).deleteAll(db) + try Person.select { $0.name }.deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\"") - try Person.order(Column("name")).deleteAll(db) + try Person.order { $0.name }.deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\"") if try String.fetchCursor(db, sql: "PRAGMA COMPILE_OPTIONS").contains("ENABLE_UPDATE_DELETE_LIMIT") { try Person.limit(1).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" LIMIT 1") - try Person.order(Column("name")).deleteAll(db) + try Person.order { $0.name }.deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\"") - try Person.order(Column("name")).limit(1).deleteAll(db) + try Person.order { $0.name }.limit(1).deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" ORDER BY \"name\" LIMIT 1") - try Person.order(Column("name")).limit(1, offset: 2).reversed().deleteAll(db) + try Person.order { $0.name }.limit(1, offset: 2).reversed().deleteAll(db) XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" ORDER BY \"name\" DESC LIMIT 1 OFFSET 2") try Person.limit(1, offset: 2).reversed().deleteAll(db) @@ -231,7 +232,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 @@ -242,16 +243,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, select: { [$0.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 @@ -269,7 +284,7 @@ class TableRecordDeleteTests: GRDBTestCase { _ = try Person.all().deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" RETURNING *") - _ = try Person.filter(Column("name") == "Arthur").deleteAndFetchCursor(db).next() + _ = try Person.filter { $0.name == "Arthur" }.deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"name\" = 'Arthur' RETURNING *") _ = try Person.filter(key: 1).deleteAndFetchCursor(db).next() @@ -279,13 +294,11 @@ class TableRecordDeleteTests: GRDBTestCase { XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *") #if GRDBCUSTOMSQLITE || GRDBCIPHER - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - _ = try Person.filter(id: 1).deleteAndFetchCursor(db).next() - XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *") - - _ = try Person.filter(ids: [1, 2]).deleteAndFetchCursor(db).next() - XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *") - } + _ = try Person.filter(id: 1).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *") + + _ = try Person.filter(ids: [1, 2]).deleteAndFetchCursor(db).next() + XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" IN (1, 2) RETURNING *") #else _ = try Person.filter(id: 1).deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE \"id\" = 1 RETURNING *") @@ -297,13 +310,13 @@ class TableRecordDeleteTests: GRDBTestCase { _ = try Person.filter(sql: "id = 1").deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE id = 1 RETURNING *") - _ = try Person.filter(sql: "id = 1").filter(Column("name") == "Arthur").deleteAndFetchCursor(db).next() + _ = try Person.filter(sql: "id = 1").filter { $0.name == "Arthur" }.deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" WHERE (id = 1) AND (\"name\" = 'Arthur') RETURNING *") - _ = try Person.select(Column("name")).deleteAndFetchCursor(db).next() + _ = try Person.select { $0.name }.deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" RETURNING *") - _ = try Person.order(Column("name")).deleteAndFetchCursor(db).next() + _ = try Person.order { $0.name }.deleteAndFetchCursor(db).next() XCTAssertEqual(self.lastSQLQuery, "DELETE FROM \"persons\" RETURNING *") // No test for LIMIT ... RETURNING ... since this is not supported by SQLite @@ -312,7 +325,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 @@ -327,7 +340,7 @@ class TableRecordDeleteTests: GRDBTestCase { try Person(id: 2, name: "Barbara", email: "barbara@example.com").insert(db) try Person(id: 3, name: "Craig", email: "craig@example.com").insert(db) - let request = Person.filter(Column("id") != 2) + let request = Person.filter { $0.id != 2 } let deletePersons = try request .deleteAndFetchAll(db) .sorted(by: { $0.id < $1.id }) @@ -340,7 +353,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 @@ -355,7 +368,7 @@ class TableRecordDeleteTests: GRDBTestCase { try Person(id: 2, name: "Barbara", email: "barbara@example.com").insert(db) try Person(id: 3, name: "Craig", email: "craig@example.com").insert(db) - let request = Person.filter(Column("id") != 2) + let request = Person.filter { $0.id != 2 } let deletePersons = try request.deleteAndFetchSet(db) XCTAssertEqual(deletePersons, [ Person(id: 1, name: "Arthur", email: "arthur@example.com"), @@ -364,10 +377,9 @@ class TableRecordDeleteTests: GRDBTestCase { } } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) // Identifiable 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 @@ -382,7 +394,7 @@ class TableRecordDeleteTests: GRDBTestCase { try Person(id: 2, name: "Barbara", email: "barbara@example.com").insert(db) try Person(id: 3, name: "Craig", email: "craig@example.com").insert(db) - let request = Person.filter(Column("id") != 2) + let request = Person.filter { $0.id != 2 } let deletedIds = try request.deleteAndFetchIds(db) XCTAssertEqual(deletedIds, [1, 3]) } @@ -450,7 +462,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 @@ -468,7 +480,7 @@ class TableRecordDeleteTests: GRDBTestCase { struct Team: MutablePersistableRecord, FetchableRecord { // Test RETURNING - static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")] + static var databaseSelection: [any SQLSelectable] { [Column("id"), Column("name")] } static let players = hasMany(Player.self) func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } init(row: Row) { preconditionFailure("should not be called") } @@ -486,7 +498,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" \ @@ -518,7 +530,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" \ @@ -617,7 +629,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 diff --git a/Tests/GRDBTests/TableRecordTests.swift b/Tests/GRDBTests/TableRecordTests.swift index f59fcd1c5..c28a92512 100644 --- a/Tests/GRDBTests/TableRecordTests.swift +++ b/Tests/GRDBTests/TableRecordTests.swift @@ -103,7 +103,7 @@ class TableRecordTests: GRDBTestCase { func testExtendedDatabaseSelection() throws { struct Record: TableRecord { static let databaseTableName = "t1" - static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID] + static var databaseSelection: [any SQLSelectable] { [.allColumns, .rowID] } } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in @@ -116,7 +116,24 @@ class TableRecordTests: GRDBTestCase { func testRestrictedDatabaseSelection() throws { struct Record: TableRecord { static let databaseTableName = "t1" - static let databaseSelection: [any SQLSelectable] = [Column("a"), Column("b")] + static var databaseSelection: [any SQLSelectable] { + [Column("a"), Column("b")] + } + } + 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 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 diff --git a/Tests/GRDBTests/TableRecordUpdateTests.swift b/Tests/GRDBTests/TableRecordUpdateTests.swift index b5de3fab7..b851b6538 100644 --- a/Tests/GRDBTests/TableRecordUpdateTests.swift +++ b/Tests/GRDBTests/TableRecordUpdateTests.swift @@ -7,6 +7,13 @@ private struct Player: Codable, PersistableRecord, FetchableRecord, Hashable { var score: Int var bonus: Int + enum Columns { + static let id = Column(CodingKeys.id) + static let name = Column(CodingKeys.name) + static let score = Column(CodingKeys.score) + static let bonus = Column(CodingKeys.bonus) + } + static func createTable(_ db: Database) throws { try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") @@ -17,16 +24,13 @@ private struct Player: Codable, PersistableRecord, FetchableRecord, Hashable { } } -@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) extension Player: Identifiable { } -private enum Columns: String, ColumnExpression { - case id, name, score, bonus -} +private typealias Columns = Player.Columns private extension QueryInterfaceRequest { func incrementScore(_ db: Database) throws { - try updateAll(db, Columns.score += 1) + try updateAll(db) { $0.score += 1 } } } @@ -41,7 +45,7 @@ class TableRecordUpdateTests: GRDBTestCase { UPDATE "player" SET "score" = 0 """) - try Player.filter(Columns.name == "Arthur").updateAll(db, assignment) + try Player.filter { $0.name == "Arthur" }.updateAll(db, assignment) XCTAssertEqual(self.lastSQLQuery, """ UPDATE "player" SET "score" = 0 WHERE \"name\" = 'Arthur' """) @@ -56,34 +60,32 @@ class TableRecordUpdateTests: GRDBTestCase { UPDATE "player" SET "score" = 0 WHERE "id" IN (1, 2) """) - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { - try Player.filter(id: 1).updateAll(db, assignment) - XCTAssertEqual(self.lastSQLQuery, """ + try Player.filter(id: 1).updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ UPDATE "player" SET "score" = 0 WHERE "id" = 1 """) - - try Player.filter(ids: [1, 2]).updateAll(db, assignment) - XCTAssertEqual(self.lastSQLQuery, """ + + try Player.filter(ids: [1, 2]).updateAll(db, assignment) + XCTAssertEqual(self.lastSQLQuery, """ UPDATE "player" SET "score" = 0 WHERE "id" IN (1, 2) """) - } - + try Player.filter(sql: "id = 1").updateAll(db, assignment) XCTAssertEqual(self.lastSQLQuery, """ UPDATE "player" SET "score" = 0 WHERE id = 1 """) - try Player.filter(sql: "id = 1").filter(Columns.name == "Arthur").updateAll(db, assignment) + try Player.filter(sql: "id = 1").filter { $0.name == "Arthur" }.updateAll(db, assignment) XCTAssertEqual(self.lastSQLQuery, """ UPDATE "player" SET "score" = 0 WHERE (id = 1) AND (\"name\" = 'Arthur') """) - try Player.select(Columns.name).updateAll(db, assignment) + try Player.select { $0.name }.updateAll(db, assignment) XCTAssertEqual(self.lastSQLQuery, """ UPDATE "player" SET "score" = 0 """) - try Player.order(Columns.name).updateAll(db, assignment) + try Player.order { $0.name }.updateAll(db, assignment) XCTAssertEqual(self.lastSQLQuery, """ UPDATE "player" SET "score" = 0 """) @@ -94,17 +96,17 @@ class TableRecordUpdateTests: GRDBTestCase { UPDATE "player" SET "score" = 0 LIMIT 1 """) - try Player.order(Columns.name).updateAll(db, assignment) + try Player.order { $0.name }.updateAll(db, assignment) XCTAssertEqual(self.lastSQLQuery, """ UPDATE "player" SET "score" = 0 """) - try Player.order(Columns.name).limit(1).updateAll(db, assignment) + try Player.order { $0.name }.limit(1).updateAll(db, assignment) XCTAssertEqual(self.lastSQLQuery, """ UPDATE "player" SET "score" = 0 ORDER BY \"name\" LIMIT 1 """) - try Player.order(Columns.name).limit(1, offset: 2).reversed().updateAll(db, assignment) + try Player.order { $0.name }.limit(1, offset: 2).reversed().updateAll(db, assignment) XCTAssertEqual(self.lastSQLQuery, """ UPDATE "player" SET "score" = 0 ORDER BY \"name\" DESC LIMIT 1 OFFSET 2 """) @@ -117,9 +119,92 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testRequestUpdateAll_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + + try Player.filter { $0.name == "Arthur" }.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 WHERE \"name\" = 'Arthur' + """) + + try Player.filter(key: 1).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 WHERE "id" = 1 + """) + + try Player.filter(keys: [1, 2]).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 WHERE "id" IN (1, 2) + """) + + try Player.filter(id: 1).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 WHERE "id" = 1 + """) + + try Player.filter(ids: [1, 2]).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 WHERE "id" IN (1, 2) + """) + + try Player.filter(sql: "id = 1").updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 WHERE id = 1 + """) + + try Player.filter(sql: "id = 1").filter { $0.name == "Arthur" }.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 WHERE (id = 1) AND (\"name\" = 'Arthur') + """) + + try Player.select { $0.name }.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + + try Player.order { $0.name }.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + + if try String.fetchCursor(db, sql: "PRAGMA COMPILE_OPTIONS").contains("ENABLE_UPDATE_DELETE_LIMIT") { + try Player.limit(1).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 LIMIT 1 + """) + + try Player.order { $0.name }.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + + try Player.order { $0.name }.limit(1).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 ORDER BY \"name\" LIMIT 1 + """) + + try Player.order { $0.name }.limit(1, offset: 2).reversed().updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 ORDER BY \"name\" DESC LIMIT 1 OFFSET 2 + """) + + try Player.limit(1, offset: 2).reversed().updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 LIMIT 1 OFFSET 2 + """) + } + } + } + func testRequestUpdateAndFetchStatement() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER - guard sqlite3_libversion_number() >= 3035000 else { + guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") } #else @@ -132,17 +217,71 @@ class TableRecordUpdateTests: GRDBTestCase { try Player.createTable(db) let assignment = Columns.score.set(to: 0) - let request = Player.all() - let statement = try request.updateAndFetchStatement(db, [assignment], selection: [AllColumns()]) - XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING *") - XCTAssertEqual(statement.arguments, [0]) - XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"]) + do { + let request = Player.all() + let statement = try request.updateAndFetchStatement(db, [assignment], selection: [Column("score")]) + XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING \"score\"") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["score"]) + } + do { + let request = Player.all() + let statement = try request.updateAndFetchStatement(db, [assignment], selection: [.allColumns]) + XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING *") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"]) + } + do { + let request = Player.all() + let statement = try request.updateAndFetchStatement(db, [assignment], selection: [.allColumns(excluding: ["name"])]) + XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING \"id\", \"score\", \"bonus\"") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["id", "score", "bonus"]) + } } } + func testRequestUpdateAndFetchStatement_DatabaseComponents() 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 + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + do { + let request = Player.all() + let statement = try request.updateAndFetchStatement(db) { [$0.score.set(to: 0)] } select: { [$0.score] } + XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING \"score\"") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["score"]) + } + do { + let request = Player.all() + let statement = try request.updateAndFetchStatement(db) { [$0.score.set(to: 0)] } select: { _ in [.allColumns] } + XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING *") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"]) + } + do { + let request = Player.all() + let statement = try request.updateAndFetchStatement(db) { [$0.score.set(to: 0)] } select: { _ in [.allColumns(excluding: ["name"])] } + XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING \"id\", \"score\", \"bonus\"") + XCTAssertEqual(statement.arguments, [0]) + XCTAssertEqual(statement.columnNames, ["id", "score", "bonus"]) + } + } + } + func testRequestUpdateAndFetchCursor() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER - guard sqlite3_libversion_number() >= 3035000 else { + guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") } #else @@ -157,7 +296,7 @@ class TableRecordUpdateTests: GRDBTestCase { try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) - let request = Player.filter(Columns.id != 2) + let request = Player.filter { $0.id != 2 } let cursor = try request.updateAndFetchCursor(db, [Columns.score += 100]) let updatedPlayers = try Array(cursor).sorted(by: { $0.id < $1.id }) XCTAssertEqual(updatedPlayers, [ @@ -167,9 +306,36 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testRequestUpdateAndFetchCursor_DatabaseComponents() 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 + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try Player(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db) + try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) + try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) + + let request = Player.filter { $0.id != 2 } + let cursor = try request.updateAndFetchCursor(db) { [$0.score += 100] } + let updatedPlayers = try Array(cursor).sorted(by: { $0.id < $1.id }) + XCTAssertEqual(updatedPlayers, [ + Player(id: 1, name: "Arthur", score: 110, bonus: 0), + Player(id: 3, name: "Craig", score: 130, bonus: 20), + ]) + } + } + func testRequestUpdateAndFetchAll() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER - guard sqlite3_libversion_number() >= 3035000 else { + guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") } #else @@ -184,7 +350,7 @@ class TableRecordUpdateTests: GRDBTestCase { try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) - let request = Player.filter(Columns.id != 2) + let request = Player.filter { $0.id != 2 } let updatedPlayers = try request .updateAndFetchAll(db, [Columns.score += 100]) .sorted(by: { $0.id < $1.id }) @@ -195,9 +361,9 @@ class TableRecordUpdateTests: GRDBTestCase { } } - func testRequestUpdateAndFetchSet() throws { + func testRequestUpdateAndFetchAll_DatabaseComponents() throws { #if GRDBCUSTOMSQLITE || GRDBCIPHER - guard sqlite3_libversion_number() >= 3035000 else { + guard Database.sqliteLibVersionNumber >= 3035000 else { throw XCTSkip("RETURNING clause is not available") } #else @@ -212,7 +378,35 @@ class TableRecordUpdateTests: GRDBTestCase { try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) - let request = Player.filter(Columns.id != 2) + let request = Player.filter { $0.id != 2 } + let updatedPlayers = try request + .updateAndFetchAll(db) { [$0.score += 100] } + .sorted(by: { $0.id < $1.id }) + XCTAssertEqual(updatedPlayers, [ + Player(id: 1, name: "Arthur", score: 110, bonus: 0), + Player(id: 3, name: "Craig", score: 130, bonus: 20), + ]) + } + } + + func testRequestUpdateAndFetchSet() 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 + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try Player(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db) + try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) + try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) + + let request = Player.filter { $0.id != 2 } let updatedPlayers = try request.updateAndFetchSet(db, [Columns.score += 100]) XCTAssertEqual(updatedPlayers, [ Player(id: 1, name: "Arthur", score: 110, bonus: 0), @@ -221,6 +415,32 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testRequestUpdateAndFetchSet_DatabaseComponents() 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 + + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try Player(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db) + try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db) + try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db) + + let request = Player.filter { $0.id != 2 } + let updatedPlayers = try request.updateAndFetchSet(db) { [$0.score += 100] } + XCTAssertEqual(updatedPlayers, [ + Player(id: 1, name: "Arthur", score: 110, bonus: 0), + Player(id: 3, name: "Craig", score: 130, bonus: 20), + ]) + } + } + func testNilAssignment() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -232,6 +452,17 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testNilAssignment_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { $0.score.set(to: nil) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = NULL + """) + } + } + func testComplexAssignment() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -243,6 +474,17 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testComplexAssignment_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { $0.score.set(to: $0.score * ($0.bonus + 1)) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" * ("bonus" + 1) + """) + } + } + func testAssignmentSubtractAndAssign() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -269,6 +511,32 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testAssignmentSubtractAndAssign_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { $0.score -= 1 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" - 1 + """) + + try Player.updateAll(db) { $0.score -= $0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" - "bonus" + """) + + try Player.updateAll(db) { $0.score -= -$0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" - (-"bonus") + """) + + try Player.updateAll(db) { $0.score -= $0.bonus * 2 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" - ("bonus" * 2) + """) + } + } + func testAssignmentAddAndAssign() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -295,6 +563,32 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testAssignmentAddAndAssign_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { $0.score += 1 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" + 1 + """) + + try Player.updateAll(db) { $0.score += $0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" + "bonus" + """) + + try Player.updateAll(db) { $0.score += -$0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" + (-"bonus") + """) + + try Player.updateAll(db) { $0.score += $0.bonus * 2 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" + ("bonus" * 2) + """) + } + } + func testAssignmentMultiplyAndAssign() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -321,6 +615,32 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testAssignmentMultiplyAndAssign_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { $0.score *= 1 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" * 1 + """) + + try Player.updateAll(db) { $0.score *= $0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" * "bonus" + """) + + try Player.updateAll(db) { $0.score *= -$0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" * (-"bonus") + """) + + try Player.updateAll(db) { $0.score *= $0.bonus * 2 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" * ("bonus" * 2) + """) + } + } + func testAssignmentDivideAndAssign() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -347,6 +667,32 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testAssignmentDivideAndAssign_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { $0.score /= 1 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" / 1 + """) + + try Player.updateAll(db) { $0.score /= $0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" / "bonus" + """) + + try Player.updateAll(db) { $0.score /= -$0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" / (-"bonus") + """) + + try Player.updateAll(db) { $0.score /= $0.bonus * 2 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" / ("bonus" * 2) + """) + } + } + func testAssignmentBitwiseAndAssign() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -373,6 +719,32 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testAssignmentBitwiseAndAssign_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { $0.score &= 1 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" & 1 + """) + + try Player.updateAll(db) { $0.score &= $0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" & "bonus" + """) + + try Player.updateAll(db) { $0.score &= -$0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" & (-"bonus") + """) + + try Player.updateAll(db) { $0.score &= $0.bonus * 2 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" & ("bonus" * 2) + """) + } + } + func testAssignmentBitwiseOrAssign() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -399,6 +771,32 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testAssignmentBitwiseOrAssign_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { $0.score |= 1 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" | 1 + """) + + try Player.updateAll(db) { $0.score |= $0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" | "bonus" + """) + + try Player.updateAll(db) { $0.score |= -$0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" | (-"bonus") + """) + + try Player.updateAll(db) { $0.score |= $0.bonus * 2 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" | ("bonus" * 2) + """) + } + } + func testAssignmentLeftShiftAssign() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -425,6 +823,32 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testAssignmentLeftShiftAssign_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { $0.score <<= 1 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" << 1 + """) + + try Player.updateAll(db) { $0.score <<= $0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" << "bonus" + """) + + try Player.updateAll(db) { $0.score <<= -$0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" << (-"bonus") + """) + + try Player.updateAll(db) { $0.score <<= $0.bonus * 2 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" << ("bonus" * 2) + """) + } + } + func testAssignmentRightShiftAssign() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -451,6 +875,32 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testAssignmentRightShiftAssign_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { $0.score >>= 1 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" >> 1 + """) + + try Player.updateAll(db) { $0.score >>= $0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" >> "bonus" + """) + + try Player.updateAll(db) { $0.score >>= -$0.bonus } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" >> (-"bonus") + """) + + try Player.updateAll(db) { $0.score >>= $0.bonus * 2 } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = "score" >> ("bonus" * 2) + """) + } + } + func testMultipleAssignments() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -477,15 +927,41 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testMultipleAssignments_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { [$0.score.set(to: 0), $0.bonus.set(to: 1)] } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0, "bonus" = 1 + """) + + try Player.all().updateAll(db) { [$0.score.set(to: 0), $0.bonus.set(to: 1)] } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0, "bonus" = 1 + """) + } + } + func testUpdateAllWithoutAssignmentDoesNotAccessTheDatabase() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) - sqlQueries.removeAll() + clearSQLQueries() try XCTAssertEqual(Player.updateAll(db, []), 0) try XCTAssertEqual(Player.all().updateAll(db, []), 0) XCTAssert(sqlQueries.isEmpty) } } + + func testUpdateAllWithoutAssignmentDoesNotAccessTheDatabase_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + clearSQLQueries() + try XCTAssertEqual(Player.updateAll(db) { _ in [] }, 0) + try XCTAssertEqual(Player.all().updateAll(db) { _ in [] }, 0) + XCTAssert(sqlQueries.isEmpty) + } + } func testUpdateAllReturnsNumberOfUpdatedRows() throws { try makeDatabaseQueue().write { db in @@ -502,7 +978,7 @@ class TableRecordUpdateTests: GRDBTestCase { try XCTAssertEqual(Player.updateAll(db, assignment), 4) try XCTAssertEqual(Player.filter(key: 1).updateAll(db, assignment), 1) try XCTAssertEqual(Player.filter(key: 5).updateAll(db, assignment), 0) - try XCTAssertEqual(Player.filter(Columns.bonus > 1).updateAll(db, assignment), 2) + try XCTAssertEqual(Player.filter { $0.bonus > 1 }.updateAll(db, assignment), 2) if try String.fetchCursor(db, sql: "PRAGMA COMPILE_OPTIONS").contains("ENABLE_UPDATE_DELETE_LIMIT") { try XCTAssertEqual(Player.limit(1).updateAll(db, assignment), 1) try XCTAssertEqual(Player.limit(2).updateAll(db, assignment), 2) @@ -512,6 +988,29 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testUpdateAllReturnsNumberOfUpdatedRows_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + try db.execute(sql: """ + INSERT INTO player (id, name, score, bonus) VALUES (1, 'Arthur', 0, 2); + INSERT INTO player (id, name, score, bonus) VALUES (2, 'Barbara', 0, 1); + INSERT INTO player (id, name, score, bonus) VALUES (3, 'Craig', 0, 0); + INSERT INTO player (id, name, score, bonus) VALUES (4, 'Diane', 0, 3); + """) + + try XCTAssertEqual(Player.updateAll(db) { $0.score += 1 }, 4) + try XCTAssertEqual(Player.filter(key: 1).updateAll(db) { $0.score += 1 }, 1) + try XCTAssertEqual(Player.filter(key: 5).updateAll(db) { $0.score += 1 }, 0) + try XCTAssertEqual(Player.filter { $0.bonus > 1 }.updateAll(db) { $0.score += 1 }, 2) + if try String.fetchCursor(db, sql: "PRAGMA COMPILE_OPTIONS").contains("ENABLE_UPDATE_DELETE_LIMIT") { + try XCTAssertEqual(Player.limit(1).updateAll(db) { $0.score += 1 }, 1) + try XCTAssertEqual(Player.limit(2).updateAll(db) { $0.score += 1 }, 2) + try XCTAssertEqual(Player.limit(2, offset: 3).updateAll(db) { $0.score += 1 }, 1) + try XCTAssertEqual(Player.limit(10).updateAll(db) { $0.score += 1 }, 4) + } + } + } + func testQueryInterfaceExtension() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -523,7 +1022,7 @@ class TableRecordUpdateTests: GRDBTestCase { """) try Player.all().incrementScore(db) - try XCTAssertEqual(Player.filter(Columns.score == 1).fetchCount(db), 4) + try XCTAssertEqual(Player.filter { $0.score == 1 }.fetchCount(db), 4) try Player.filter(key: 1).incrementScore(db) try XCTAssertEqual(Player.fetchOne(db, key: 1)!.score, 2) @@ -561,6 +1060,28 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testConflictPolicyAbort_DatabaseComponents() throws { + struct AbortPlayer: PersistableRecord { + static let databaseTableName = "player" + static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .abort, update: .abort) + func encode(to container: inout PersistenceContainer) { } + typealias Columns = Player.Columns + } + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try AbortPlayer.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + + try AbortPlayer.all().updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + } + } + func testConflictPolicyIgnore() throws { struct IgnorePlayer: PersistableRecord { static let databaseTableName = "player" @@ -592,6 +1113,28 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testConflictPolicyIgnore_DatabaseComponents() throws { + struct IgnorePlayer: PersistableRecord { + static let databaseTableName = "player" + static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .abort, update: .ignore) + func encode(to container: inout PersistenceContainer) { } + typealias Columns = Player.Columns + } + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try IgnorePlayer.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + + try IgnorePlayer.all().updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + } + } + func testConflictPolicyIgnoreWithTable() throws { struct IgnorePlayer: PersistableRecord { static let databaseTableName = "player" @@ -624,6 +1167,29 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testConflictPolicyIgnoreWithTable_DatabaseComponents() throws { + struct IgnorePlayer: PersistableRecord { + static let databaseTableName = "player" + static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .abort, update: .ignore) + func encode(to container: inout PersistenceContainer) { } + typealias Columns = Player.Columns + } + let table = Table("player") + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try table.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + + try table.all().updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + } + } + func testConflictPolicyCustom() throws { try makeDatabaseQueue().write { db in try Player.createTable(db) @@ -655,6 +1221,27 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testConflictPolicyCustom_DatabaseComponents() throws { + try makeDatabaseQueue().write { db in + try Player.createTable(db) + + try Player.updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + + try Player.updateAll(db, onConflict: .ignore) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + + try Player.all().updateAll(db, onConflict: .ignore) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + } + } + func testJoinedRequestUpdate() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { @@ -727,6 +1314,84 @@ class TableRecordUpdateTests: GRDBTestCase { } } + func testJoinedRequestUpdate_DatabaseComponents() throws { + try makeDatabaseQueue().inDatabase { db in + struct Player: MutablePersistableRecord { + static let team = belongsTo(Team.self) + func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } + enum Columns { + static let score = Column("score") + } + } + + struct Team: MutablePersistableRecord { + static let players = hasMany(Player.self) + func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } + enum Columns { + static let active = Column("active") + } + } + + try db.create(table: "team") { t in + t.autoIncrementedPrimaryKey("id") + t.column("active", .boolean) + } + + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.belongsTo("team") + t.column("score", .integer) + } + + do { + try Player.including(required: Player.team).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 WHERE "id" IN (\ + SELECT "player"."id" \ + FROM "player" \ + JOIN "team" ON "team"."id" = "player"."teamId") + """) + } + do { + // Regression test for https://github.com/groue/GRDB.swift/issues/758 + try Player.including(required: Player.team.filter(Column("active") == 1)).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 WHERE "id" IN (\ + SELECT "player"."id" \ + FROM "player" \ + JOIN "team" ON ("team"."id" = "player"."teamId") AND ("team"."active" = 1)) + """) + } + do { + let alias = TableAlias(name: "p") + try Player.aliased(alias).including(required: Player.team).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 WHERE "id" IN (\ + SELECT "p"."id" \ + FROM "player" "p" \ + JOIN "team" ON "team"."id" = "p"."teamId") + """) + } + do { + try Team.having(Team.players.isEmpty).updateAll(db) { $0.active.set(to: false) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "team" SET "active" = 0 WHERE "id" IN (\ + SELECT "team"."id" \ + FROM "team" \ + LEFT JOIN "player" ON "player"."teamId" = "team"."id" \ + GROUP BY "team"."id" \ + HAVING COUNT(DISTINCT "player"."id") = 0) + """) + } + do { + try Team.including(all: Team.players).updateAll(db) { $0.active.set(to: false) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "team" SET "active" = 0 + """) + } + } + } + func testGroupedRequestUpdate() throws { try makeDatabaseQueue().inDatabase { db in struct Player: MutablePersistableRecord { @@ -783,4 +1448,67 @@ class TableRecordUpdateTests: GRDBTestCase { } } } + + func testGroupedRequestUpdate_DatabaseComponents() throws { + try makeDatabaseQueue().inDatabase { db in + struct Player: MutablePersistableRecord { + func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } + enum Columns { + static let score = Column("score") + } + } + struct Passport: MutablePersistableRecord { + func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") } + enum Columns { + static let active = Column("active") + } + } + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("score", .integer) + } + try db.create(table: "passport") { t in + t.column("countryCode", .text).notNull() + t.column("citizenId", .integer).notNull() + t.column("active", .boolean) + t.primaryKey(["countryCode", "citizenId"]) + } + do { + try Player.all().groupByPrimaryKey().updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 WHERE "id" IN (\ + SELECT "id" \ + FROM "player" \ + GROUP BY "id") + """) + } + do { + try Player.all().group(Column.rowID).updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 WHERE "id" IN (\ + SELECT "id" \ + FROM "player" \ + GROUP BY "rowid") + """) + } + do { + try Passport.all().groupByPrimaryKey().updateAll(db) { $0.active.set(to: true) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "passport" SET "active" = 1 WHERE "rowid" IN (\ + SELECT "rowid" \ + FROM "passport" \ + GROUP BY "rowid") + """) + } + do { + try Passport.all().group(Column.rowID).updateAll(db) { $0.active.set(to: true) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "passport" SET "active" = 1 WHERE "rowid" IN (\ + SELECT "rowid" \ + FROM "passport" \ + GROUP BY "rowid") + """) + } + } + } } diff --git a/Tests/GRDBTests/TableTests.swift b/Tests/GRDBTests/TableTests.swift index 46c8f5a19..b9d903f79 100644 --- a/Tests/GRDBTests/TableTests.swift +++ b/Tests/GRDBTests/TableTests.swift @@ -44,6 +44,12 @@ class TableTests: GRDBTestCase { try assertEqualSQL(db, t.select([Column("id"), Column("name")]), """ SELECT "id", "name" FROM "player" """) + try assertEqualSQL(db, t.select(.allColumns), """ + SELECT * FROM "player" + """) + try assertEqualSQL(db, t.select(.allColumns(excluding: ["name"])), """ + SELECT "id" FROM "player" + """) try assertEqualSQL(db, t.select(sql: "id, ?", arguments: ["O'Brien"]), """ SELECT id, 'O''Brien' FROM "player" """) @@ -117,7 +123,7 @@ class TableTests: GRDBTestCase { """) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { + do { struct Player: Identifiable { var id: Int64 } let t = Table("player") @@ -127,9 +133,11 @@ class TableTests: GRDBTestCase { try assertEqualSQL(db, t.filter(ids: [1, 2, 3]), """ SELECT * FROM "player" WHERE "id" IN (1, 2, 3) """) + + try XCTAssertEqual(t.selectID().fetchOne(db), 1) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { + do { struct Player: Identifiable { var id: Int64? } let t = Table("player") @@ -142,6 +150,8 @@ class TableTests: GRDBTestCase { try assertEqualSQL(db, t.filter(ids: [1, 2, 3]), """ SELECT * FROM "player" WHERE "id" IN (1, 2, 3) """) + + try XCTAssertEqual(t.selectID().fetchOne(db), 1) } } } @@ -806,7 +816,7 @@ class TableTests: GRDBTestCase { """) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { + do { // Non-optional ID struct Country: Identifiable { var id: String } @@ -821,7 +831,7 @@ class TableTests: GRDBTestCase { """) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { + do { // Optional ID struct Country: Identifiable { var id: String? } @@ -830,7 +840,7 @@ class TableTests: GRDBTestCase { DELETE FROM "country" WHERE "code" = 'FR' """) - sqlQueries.removeAll() + clearSQLQueries() try Table("country").deleteOne(db, id: nil) XCTAssertNil(lastSQLQuery) // Database not hit @@ -873,6 +883,46 @@ class TableTests: GRDBTestCase { } } + func test_updateAll_DatabaseComponents() throws { + struct Player: TableRecord { + enum Columns { + static let score = Column("score") + } + } + + try makeDatabaseQueue().write { db in + try db.create(table: "player") { t in + t.autoIncrementedPrimaryKey("id") + t.column("score", .integer) + } + + do { + try Table("player").updateAll(db) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + } + do { + try Table("player").updateAll(db) { [$0.score.set(to: 0)] } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE "player" SET "score" = 0 + """) + } + do { + try Table("player").updateAll(db, onConflict: .ignore) { $0.score.set(to: 0) } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + } + do { + try Table("player").updateAll(db, onConflict: .ignore) { [$0.score.set(to: 0)] } + XCTAssertEqual(self.lastSQLQuery, """ + UPDATE OR IGNORE "player" SET "score" = 0 + """) + } + } + } + func test_exists() throws { try makeDatabaseQueue().write { db in try db.create(table: "player") { t in @@ -920,7 +970,7 @@ class TableTests: GRDBTestCase { """) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { + do { // Non-optional ID struct Country: Identifiable { var id: String } @@ -930,7 +980,7 @@ class TableTests: GRDBTestCase { """) } - if #available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) { + do { // Optional ID struct Country: Identifiable { var id: String? } @@ -939,7 +989,7 @@ class TableTests: GRDBTestCase { SELECT EXISTS (SELECT * FROM "country" WHERE "code" = 'FR') """) - sqlQueries.removeAll() + clearSQLQueries() try XCTAssertFalse(Table("country").exists(db, id: nil)) XCTAssertNil(lastSQLQuery) // Database not hit } diff --git a/Tests/GRDBTests/TransactionDateTests.swift b/Tests/GRDBTests/TransactionDateTests.swift index 5f2707223..f2121530b 100644 --- a/Tests/GRDBTests/TransactionDateTests.swift +++ b/Tests/GRDBTests/TransactionDateTests.swift @@ -8,9 +8,9 @@ class TransactionDateTests: GRDBTestCase { Date(), Date.distantFuture, ] - var dateIterator = dates.makeIterator() + let dateIteratorMutex = Mutex(dates.makeIterator()) dbConfiguration.transactionClock = .custom { _ in - dateIterator.next()! + dateIteratorMutex.withLock { $0.next()! } } var collectedDates: [Date] = [] @@ -28,9 +28,9 @@ class TransactionDateTests: GRDBTestCase { Date(), Date.distantFuture, ] - var dateIterator = dates.makeIterator() + let dateIteratorMutex = Mutex(dates.makeIterator()) dbConfiguration.transactionClock = .custom { _ in - dateIterator.next()! + dateIteratorMutex.withLock { $0.next()! } } var collectedDates: [Date] = [] @@ -51,9 +51,9 @@ class TransactionDateTests: GRDBTestCase { Date(), Date.distantFuture, ] - var dateIterator = dates.makeIterator() + let dateIteratorMutex = Mutex(dates.makeIterator()) dbConfiguration.transactionClock = .custom { _ in - dateIterator.next()! + dateIteratorMutex.withLock { $0.next()! } } var collectedDates: [Date] = [] @@ -74,9 +74,9 @@ class TransactionDateTests: GRDBTestCase { Date(), Date.distantFuture, ] - var dateIterator = dates.makeIterator() + let dateIteratorMutex = Mutex(dates.makeIterator()) dbConfiguration.transactionClock = .custom { _ in - dateIterator.next()! + dateIteratorMutex.withLock { $0.next()! } } var collectedDates: [Date] = [] @@ -107,8 +107,7 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + dbConfiguration.transactionClock = .custom { _ in .distantPast } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -119,7 +118,6 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast try dbQueue.write { db in do { var player = Player(name: "Arthur") @@ -152,8 +150,8 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + let currentDate = Mutex(Date.distantPast) + dbConfiguration.transactionClock = .custom { _ in currentDate.load() } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -164,14 +162,13 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast try dbQueue.write { db in var player = Player(name: "Arthur") try player.insert(db) } let newTransactionDate = Date() - currentDate = newTransactionDate + currentDate.store(newTransactionDate) try dbQueue.write { db in var player = try Player.find(db, key: 1) @@ -198,8 +195,8 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + let currentDate = Mutex(Date.distantPast) + dbConfiguration.transactionClock = .custom { _ in currentDate.load() } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -210,14 +207,13 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast try dbQueue.write { db in var player = Player(name: "Arthur") try player.insert(db) } let newTransactionDate = Date() - currentDate = newTransactionDate + currentDate.store(newTransactionDate) try dbQueue.write { db in var player = try Player.find(db, key: 1) @@ -251,8 +247,8 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + let currentDate = Mutex(Date.distantPast) + dbConfiguration.transactionClock = .custom { _ in currentDate.load() } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -267,7 +263,7 @@ class TransactionDateTests: GRDBTestCase { } let newTransactionDate = Date() - currentDate = newTransactionDate + currentDate.store(newTransactionDate) try dbQueue.write { db in var player = try Player.find(db, key: 1) try player.touch(db) @@ -303,8 +299,7 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + dbConfiguration.transactionClock = .custom { _ in .distantPast } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -315,7 +310,6 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast try dbQueue.write { db in var player = Player(name: "Arthur", isInserted: false) try player.insert(db) @@ -354,8 +348,7 @@ class TransactionDateTests: GRDBTestCase { } } - var currentDate = Date.distantPast - dbConfiguration.transactionClock = .custom { _ in currentDate } + dbConfiguration.transactionClock = .custom { _ in .distantPast } let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.create(table: "player") { t in @@ -366,7 +359,6 @@ class TransactionDateTests: GRDBTestCase { } } - currentDate = Date.distantPast try dbQueue.write { db in let player = Player(name: "Arthur") try player.insert(db) @@ -379,7 +371,7 @@ class TransactionDateTests: GRDBTestCase { // The protocol in RecordTimestamps.md /// A record type that tracks its creation and modification dates. See -/// +/// protocol TimestampedRecord: MutablePersistableRecord { var creationDate: Date? { get set } var modificationDate: Date? { get set } diff --git a/Tests/GRDBTests/TransactionObserverTests.swift b/Tests/GRDBTests/TransactionObserverTests.swift index 0730f42f2..cedbb2302 100644 --- a/Tests/GRDBTests/TransactionObserverTests.swift +++ b/Tests/GRDBTests/TransactionObserverTests.swift @@ -1384,7 +1384,7 @@ class TransactionObserverTests: GRDBTestCase { dbQueue.add(transactionObserver: observer) try dbQueue.writeWithoutTransaction { db in - try MinimalRowID.setup(inDatabase: db) + try MinimalRowID.setup(db) let record = MinimalRowID() try record.save(db) diff --git a/Tests/GRDBTests/UpdateStatementTests.swift b/Tests/GRDBTests/UpdateStatementTests.swift index faf20f676..6a3233fdc 100644 --- a/Tests/GRDBTests/UpdateStatementTests.swift +++ b/Tests/GRDBTests/UpdateStatementTests.swift @@ -1,3 +1,12 @@ +// Import C SQLite functions +#if SWIFT_PACKAGE +import GRDBSQLite +#elseif GRDBCIPHER +import SQLCipher +#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER +import SQLite3 +#endif + import XCTest import GRDB @@ -169,17 +178,16 @@ class UpdateStatementTests : GRDBTestCase { func testUpdateStatementAcceptsSelectQueriesAndConsumeAllRows() throws { let dbQueue = try makeDatabaseQueue() - var index = 0 + let indexMutex = Mutex(0) try dbQueue.inDatabase { db in db.add(function: DatabaseFunction("seq", argumentCount: 0, pure: false) { _ in - defer { index += 1 } - return index + indexMutex.increment() }) try db.execute(sql: "SELECT seq() UNION ALL SELECT seq() UNION ALL SELECT seq()") let statement = try db.makeStatement(sql: "SELECT seq() UNION ALL SELECT seq() UNION ALL SELECT seq()") try statement.execute() } - XCTAssertEqual(index, 3 + 3) + XCTAssertEqual(indexMutex.load(), 3 + 3) } func testExecuteNothing() throws { diff --git a/Tests/GRDBTests/ValueObservationPrintTests.swift b/Tests/GRDBTests/ValueObservationPrintTests.swift index 51f57f5b6..9ed1a4433 100644 --- a/Tests/GRDBTests/ValueObservationPrintTests.swift +++ b/Tests/GRDBTests/ValueObservationPrintTests.swift @@ -4,9 +4,10 @@ import Dispatch class ValueObservationPrintTests: GRDBTestCase { class TestStream: TextOutputStream { - @LockedBox var strings: [String] = [] + private var stringsMutex: Mutex<[String]> = Mutex([]) + var strings: [String] { stringsMutex.load() } func write(_ string: String) { - strings.append(string) + stringsMutex.withLock { $0.append(string) } } } @@ -54,7 +55,7 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabaseQueue(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool()) #endif } @@ -91,7 +92,7 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabaseQueue(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool()) #endif } @@ -129,7 +130,7 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabaseQueue(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool()) #endif } @@ -167,7 +168,7 @@ class ValueObservationPrintTests: GRDBTestCase { try test(makeDatabaseQueue(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config)) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshot()) -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) try test(makeDatabasePool(filename: "test", configuration: config).makeSnapshotPool()) #endif } @@ -410,11 +411,15 @@ class ValueObservationPrintTests: GRDBTestCase { // Force DatabasePool to perform two initial fetches, because between // its first read access, and its write access that installs the // transaction observer, some write did happen. - var needsChange = true + let needsChangeMutex = Mutex(true) let observation = ValueObservation .trackingConstantRegion { db -> Int? in + let needsChange = needsChangeMutex.withLock { needed in + let wasNeeded = needed + needed = false + return wasNeeded + } if needsChange { - needsChange = false try dbPool.write { db in try db.execute(sql: """ INSERT INTO player DEFAULT VALUES; @@ -461,11 +466,15 @@ class ValueObservationPrintTests: GRDBTestCase { // Force DatabasePool to perform two initial fetches, because between // its first read access, and its write access that installs the // transaction observer, some write did happen. - var needsChange = true + let needsChangeMutex = Mutex(true) let observation = ValueObservation .trackingConstantRegion { db -> Int? in + let needsChange = needsChangeMutex.withLock { needed in + let wasNeeded = needed + needed = false + return wasNeeded + } if needsChange { - needsChange = false try dbPool.write { db in try db.execute(sql: """ INSERT INTO player DEFAULT VALUES; diff --git a/Tests/GRDBTests/ValueObservationRecorder.swift b/Tests/GRDBTests/ValueObservationRecorder.swift index fdc799f5a..8a895c564 100644 --- a/Tests/GRDBTests/ValueObservationRecorder.swift +++ b/Tests/GRDBTests/ValueObservationRecorder.swift @@ -576,9 +576,10 @@ extension GRDBTestCase { func test( observation: ValueObservation, scheduling scheduler: some ValueObservationScheduler, + description: String, testErrorDispatching: @escaping () -> Void) throws { - func test(writer: some DatabaseWriter) throws { + func test(writer: some DatabaseWriter, description: String) throws { try writer.write(setup) let recorder = observation.record( @@ -586,7 +587,7 @@ extension GRDBTestCase { scheduling: scheduler, onError: { _ in testErrorDispatching() }) - let (_, error) = try wait(for: recorder.failure(), timeout: 5) + let (_, error) = try wait(for: recorder.failure(), timeout: 5, description: description) if let error = error as? Failure { try testFailure(error, writer) } else { @@ -594,9 +595,9 @@ extension GRDBTestCase { } } - try test(writer: DatabaseQueue()) - try test(writer: makeDatabaseQueue()) - try test(writer: makeDatabasePool()) + try test(writer: DatabaseQueue(), description: description + " (in-memory DatabaseQueue)") + try test(writer: makeDatabaseQueue(), description: description + " (on-disk DatabaseQueue)") + try test(writer: makeDatabasePool(), description: description + " (DatabasePool)") } do { @@ -606,6 +607,7 @@ extension GRDBTestCase { try test( observation: observation, scheduling: .immediate, + description: "Immediate scheduling", testErrorDispatching: { XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) }) } @@ -616,6 +618,7 @@ extension GRDBTestCase { try test( observation: observation, scheduling: .async(onQueue: .main), + description: "Async on main queue scheduling", testErrorDispatching: { XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) }) } @@ -627,6 +630,7 @@ extension GRDBTestCase { try test( observation: observation, scheduling: .async(onQueue: queue), + description: "Async on custom queue scheduling", testErrorDispatching: { XCTAssertNotNil(DispatchQueue.getSpecific(key: key)) }) } } diff --git a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift index 90bd8beb8..390df4af0 100644 --- a/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift +++ b/Tests/GRDBTests/ValueObservationRegionRecordingTests.swift @@ -130,24 +130,26 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { """) } - var results: [Int] = [] + let resultsMutex: Mutex<[Int]> = Mutex([]) let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 4 - var regions: [DatabaseRegion] = [] + let regionsMutex: Mutex<[DatabaseRegion]> = Mutex([]) let observation = ValueObservation .tracking { db -> Int in let table = try String.fetchOne(db, sql: "SELECT name FROM source")! return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! } - .handleEvents(willTrackRegion: { regions.append($0) }) + .handleEvents(willTrackRegion: { region in + regionsMutex.withLock { $0.append(region) } + }) let observer = observation.start( in: dbQueue, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - results.append(count) + resultsMutex.withLock { $0.append(count) } notificationExpectation.fulfill() }) @@ -162,9 +164,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [0, 1, 2, 3]) + XCTAssertEqual(resultsMutex.load(), [0, 1, 2, 3]) - XCTAssertEqual(regions.map(\.description), [ + XCTAssertEqual(regionsMutex.load().map(\.description), [ "a(value),source(name)", "b(value),source(name)"]) } @@ -181,25 +183,27 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { """) } - var results: [Int] = [] + let resultsMutex: Mutex<[Int]> = Mutex([]) let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 4 - var regions: [DatabaseRegion] = [] + let regionsMutex: Mutex<[DatabaseRegion]> = Mutex([]) let observation = ValueObservation .tracking { db -> Int in let table = try String.fetchOne(db, sql: "SELECT name FROM source")! return try Int.fetchOne(db, sql: "SELECT IFNULL(SUM(value), 0) FROM \(table)")! } - .handleEvents(willTrackRegion: { regions.append($0) }) + .handleEvents(willTrackRegion: { region in + regionsMutex.withLock { $0.append(region) } + }) let observer = observation.start( in: dbQueue, scheduling: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - results.append(count) + resultsMutex.withLock { $0.append(count) } notificationExpectation.fulfill() }) @@ -214,9 +218,9 @@ class ValueObservationRegionRecordingTests: GRDBTestCase { } waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(results, [0, 1, 2, 3]) + XCTAssertEqual(resultsMutex.load(), [0, 1, 2, 3]) - XCTAssertEqual(regions.map(\.description), [ + XCTAssertEqual(regionsMutex.load().map(\.description), [ "a(value),source(name)", "b(value),source(name)"]) } diff --git a/Tests/GRDBTests/ValueObservationTests.swift b/Tests/GRDBTests/ValueObservationTests.swift index 7beeb4d6f..ae5c09ff8 100644 --- a/Tests/GRDBTests/ValueObservationTests.swift +++ b/Tests/GRDBTests/ValueObservationTests.swift @@ -21,10 +21,9 @@ class ValueObservationTests: GRDBTestCase { // Test passes if it compiles. // See - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testValuesFromAnyDatabaseWriter(writer: any DatabaseWriter) { func observe( - fetch: @Sendable @escaping (Database) throws -> T + fetch: @escaping @Sendable (Database) throws -> T ) throws -> AsyncValueObservation { ValueObservation.tracking(fetch).values(in: writer) } @@ -38,13 +37,15 @@ class ValueObservationTests: GRDBTestCase { let observation = ValueObservation.trackingConstantRegion { _ in throw TestError() } // Start observation - var error: TestError? + let errorMutex: Mutex = Mutex(nil) _ = observation.start( in: dbWriter, scheduling: .immediate, - onError: { error = $0 as? TestError }, + onError: { error in + errorMutex.store(error as? TestError) + }, onChange: { _ in }) - XCTAssertNotNil(error) + XCTAssertNotNil(errorMutex.load()) } try test(makeDatabaseQueue()) @@ -64,25 +65,25 @@ class ValueObservationTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 4 notificationExpectation.isInverted = true - var nextError: Error? = nil // If not null, observation throws an error + let nextErrorMutex: Mutex = Mutex(nil) // If not null, observation throws an error let observation = ValueObservation.trackingConstantRegion { _ = try Int.fetchOne($0, sql: "SELECT COUNT(*) FROM t") - if let error = nextError { - throw error + try nextErrorMutex.withLock { error in + if let error { throw error } } } // Start observation - var errorCaught = false + let errorCaughtMutex = Mutex(false) let cancellable = observation.start( in: dbWriter, onError: { _ in - errorCaught = true + errorCaughtMutex.store(true) notificationExpectation.fulfill() }, onChange: { - XCTAssertFalse(errorCaught) - nextError = TestError() + XCTAssertFalse(errorCaughtMutex.load()) + nextErrorMutex.store(TestError()) notificationExpectation.fulfill() // Trigger another change try! dbWriter.writeWithoutTransaction { db in @@ -92,7 +93,7 @@ class ValueObservationTests: GRDBTestCase { withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertTrue(errorCaught) + XCTAssertTrue(errorCaughtMutex.load()) } } @@ -119,12 +120,12 @@ class ValueObservationTests: GRDBTestCase { // Test that view v is not included in the observed region. // This optimization helps observation of views that feed from a // single table. - var region: DatabaseRegion? + let regionMutex: Mutex = Mutex(nil) let expectation = self.expectation(description: "") let observation = ValueObservation - .trackingConstantRegion(request.fetchAll) - .handleEvents(willTrackRegion: { - region = $0 + .trackingConstantRegion { _ = try request.fetchAll($0) } + .handleEvents(willTrackRegion: { region in + regionMutex.store(region) expectation.fulfill() }) let observer = observation.start( @@ -133,7 +134,7 @@ class ValueObservationTests: GRDBTestCase { onChange: { _ in }) withExtendedLifetime(observer) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(region!.description, "t(id,name)") // view is NOT tracked + XCTAssertEqual(regionMutex.load()!.description, "t(id,name)") // view is NOT tracked } } @@ -152,12 +153,12 @@ class ValueObservationTests: GRDBTestCase { // Test that no pragma table is included in the observed region. // This optimization helps observation that feed from a single table. - var region: DatabaseRegion? + let regionMutex: Mutex = Mutex(nil) let expectation = self.expectation(description: "") let observation = ValueObservation - .trackingConstantRegion(request.fetchAll) - .handleEvents(willTrackRegion: { - region = $0 + .trackingConstantRegion{ _ = try request.fetchAll($0) } + .handleEvents(willTrackRegion: { region in + regionMutex.store(region) expectation.fulfill() }) let observer = observation.start( @@ -166,7 +167,7 @@ class ValueObservationTests: GRDBTestCase { onChange: { _ in }) withExtendedLifetime(observer) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(region!.description, "t(id,name)[1]") // pragma_table_xinfo is NOT tracked + XCTAssertEqual(regionMutex.load()?.description, "t(id,name)[1]") // pragma_table_xinfo is NOT tracked } } @@ -174,9 +175,10 @@ class ValueObservationTests: GRDBTestCase { func testTrackingExplicitRegion() throws { class TestStream: TextOutputStream { - @LockedBox var strings: [String] = [] + private var stringsMutex: Mutex<[String]> = Mutex([]) + var strings: [String] { stringsMutex.load() } func write(_ string: String) { - strings.append(string) + stringsMutex.withLock { $0.append(string) } } } @@ -352,10 +354,14 @@ class ValueObservationTests: GRDBTestCase { // Force DatabasePool to perform two initial fetches, because between // its first read access, and its write access that installs the // transaction observer, some write did happen. - var needsChange = true + let needsChangeMutex = Mutex(true) let observation = ValueObservation.trackingConstantRegion { db -> Int in + let needsChange = needsChangeMutex.withLock { needed in + let wasNeeded = needed + needed = false + return wasNeeded + } if needsChange { - needsChange = false try dbPool.write { db in try db.execute(sql: """ INSERT INTO t DEFAULT VALUES; @@ -368,18 +374,18 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 - var observedCounts: [Int] = [] + let observedCountsMutex: Mutex<[Int]> = Mutex([]) let cancellable = observation.start( in: dbPool, scheduling: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - observedCounts.append(count) + observedCountsMutex.withLock { $0.append(count) } expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, [0, 0]) + XCTAssertEqual(observedCountsMutex.load(), [0, 0]) } } @@ -392,10 +398,14 @@ class ValueObservationTests: GRDBTestCase { // Force DatabasePool to perform two initial fetches, because between // its first read access, and its write access that installs the // transaction observer, some write did happen. - var needsChange = true + let needsChangeMutex = Mutex(true) let observation = ValueObservation.trackingConstantRegion { db -> Int in + let needsChange = needsChangeMutex.withLock { needed in + let wasNeeded = needed + needed = false + return wasNeeded + } if needsChange { - needsChange = false try dbPool.write { db in try db.execute(sql: """ INSERT INTO t DEFAULT VALUES; @@ -408,18 +418,18 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = 2 - var observedCounts: [Int] = [] + let observedCountsMutex: Mutex<[Int]> = Mutex([]) let cancellable = observation.start( in: dbPool, scheduling: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - observedCounts.append(count) + observedCountsMutex.withLock { $0.append(count) } expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, [0, 0]) + XCTAssertEqual(observedCountsMutex.load(), [0, 0]) } } @@ -432,10 +442,14 @@ class ValueObservationTests: GRDBTestCase { // Allow pool to perform a single initial fetch, because between // its first read access, and its write access that installs the // transaction observer, no write did happen. - var needsChange = true + let needsChangeMutex = Mutex(true) let observation = ValueObservation.trackingConstantRegion { db -> Int in + let needsChange = needsChangeMutex.withLock { needed in + let wasNeeded = needed + needed = false + return wasNeeded + } if needsChange { - needsChange = false DispatchQueue.main.asyncAfter(deadline: .now() + 1) { try! dbPool.write { db in try db.execute(sql: """ @@ -448,7 +462,7 @@ class ValueObservationTests: GRDBTestCase { } let expectedCounts: [Int] -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) // Optimization available expectedCounts = [0, 1] #else @@ -458,18 +472,18 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = expectedCounts.count - var observedCounts: [Int] = [] + let observedCountsMutex: Mutex<[Int]> = Mutex([]) let cancellable = observation.start( in: dbPool, scheduling: .async(onQueue: .main), onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - observedCounts.append(count) + observedCountsMutex.withLock { $0.append(count) } expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, expectedCounts) + XCTAssertEqual(observedCountsMutex.load(), expectedCounts) } } @@ -482,10 +496,14 @@ class ValueObservationTests: GRDBTestCase { // Allow pool to perform a single initial fetch, because between // its first read access, and its write access that installs the // transaction observer, no write did happen. - var needsChange = true + let needsChangeMutex = Mutex(true) let observation = ValueObservation.trackingConstantRegion { db -> Int in + let needsChange = needsChangeMutex.withLock { needed in + let wasNeeded = needed + needed = false + return wasNeeded + } if needsChange { - needsChange = false DispatchQueue.main.asyncAfter(deadline: .now() + 1) { try! dbPool.write { db in try db.execute(sql: """ @@ -498,7 +516,7 @@ class ValueObservationTests: GRDBTestCase { } let expectedCounts: [Int] -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) // Optimization available expectedCounts = [0, 1] #else @@ -508,24 +526,24 @@ class ValueObservationTests: GRDBTestCase { let expectation = self.expectation(description: "") expectation.expectedFulfillmentCount = expectedCounts.count - var observedCounts: [Int] = [] + let observedCountsMutex: Mutex<[Int]> = Mutex([]) let cancellable = observation.start( in: dbPool, scheduling: .immediate, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { count in - observedCounts.append(count) + observedCountsMutex.withLock { $0.append(count) } expectation.fulfill() }) withExtendedLifetime(cancellable) { waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(observedCounts, expectedCounts) + XCTAssertEqual(observedCountsMutex.load(), expectedCounts) } } // MARK: - Snapshot Observation -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) func testDatabaseSnapshotPoolObservation() throws { let dbPool = try makeDatabasePool() try dbPool.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } @@ -601,7 +619,7 @@ class ValueObservationTests: GRDBTestCase { try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } // Track reducer process - var changesCount = 0 + let changesCountMutex = Mutex(0) let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 2 @@ -612,13 +630,12 @@ class ValueObservationTests: GRDBTestCase { } // Start observation and deallocate cancellable after second change - var cancellable: (any DatabaseCancellable)? + nonisolated(unsafe) var cancellable: (any DatabaseCancellable)? cancellable = observation.start( in: dbQueue, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { _ in - changesCount += 1 - if changesCount == 2 { + if changesCountMutex.increment() == 2 { cancellable = nil } notificationExpectation.fulfill() @@ -638,7 +655,7 @@ class ValueObservationTests: GRDBTestCase { _ = cancellable waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(changesCount, 2) + XCTAssertEqual(changesCountMutex.load(), 2) } func testCancellableExplicitCancellation() throws { @@ -647,7 +664,7 @@ class ValueObservationTests: GRDBTestCase { try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } // Track reducer process - var changesCount = 0 + let changesCountMutex = Mutex(0) let notificationExpectation = expectation(description: "notification") notificationExpectation.assertForOverFulfill = true notificationExpectation.expectedFulfillmentCount = 2 @@ -658,13 +675,12 @@ class ValueObservationTests: GRDBTestCase { } // Start observation and cancel cancellable after second change - var cancellable: (any DatabaseCancellable)! + nonisolated(unsafe) var cancellable: (any DatabaseCancellable)! cancellable = observation.start( in: dbQueue, onError: { error in XCTFail("Unexpected error: \(error)") }, onChange: { _ in - changesCount += 1 - if changesCount == 2 { + if changesCountMutex.increment() == 2 { cancellable.cancel() } notificationExpectation.fulfill() @@ -682,7 +698,7 @@ class ValueObservationTests: GRDBTestCase { } waitForExpectations(timeout: 2, handler: nil) - XCTAssertEqual(changesCount, 2) + XCTAssertEqual(changesCountMutex.load(), 2) } } @@ -696,18 +712,20 @@ class ValueObservationTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 2 do { - var cancellable: (any DatabaseCancellable)? = nil + nonisolated(unsafe) var cancellable: (any DatabaseCancellable)? = nil _ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning - var shouldStopObservation = false + let shouldStopObservationMutex = Mutex(false) let observation = ValueObservation( trackingMode: .nonConstantRegionRecordedFromSelection, makeReducer: { AnyValueReducer( fetch: { _ in - if shouldStopObservation { - cancellable = nil /* deallocation */ + shouldStopObservationMutex.withLock { shouldStopObservation in + if shouldStopObservation { + cancellable = nil /* deallocation */ + } + shouldStopObservation = true } - shouldStopObservation = true }, value: { _ in () }) }) @@ -740,19 +758,21 @@ class ValueObservationTests: GRDBTestCase { notificationExpectation.expectedFulfillmentCount = 2 do { - var cancellable: (any DatabaseCancellable)? = nil + nonisolated(unsafe) var cancellable: (any DatabaseCancellable)? = nil _ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning - var shouldStopObservation = false + let shouldStopObservationMutex = Mutex(false) let observation = ValueObservation( trackingMode: .nonConstantRegionRecordedFromSelection, makeReducer: { AnyValueReducer( fetch: { _ in }, value: { _ in - if shouldStopObservation { - cancellable = nil /* deallocation right before notification */ + shouldStopObservationMutex.withLock { shouldStopObservation in + if shouldStopObservation { + cancellable = nil /* deallocation right before notification */ + } + shouldStopObservation = true } - shouldStopObservation = true return () }) }) @@ -780,13 +800,13 @@ class ValueObservationTests: GRDBTestCase { try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } // Start observing - var counts: [Int] = [] + let countsMutex: Mutex<[Int]> = Mutex([]) let cancellable = ValueObservation .trackingConstantRegion { try Table("t").fetchCount($0) } .start(in: writer) { error in XCTFail("Unexpected error: \(error)") } onChange: { count in - counts.append(count) + countsMutex.withLock { $0.append(count) } } // Perform a write after cancellation, but before the @@ -815,7 +835,7 @@ class ValueObservationTests: GRDBTestCase { // We should not have been notified of the first write, because // it was performed after cancellation. - XCTAssertFalse(counts.contains(1)) + XCTAssertFalse(countsMutex.load().contains(1)) } try test(makeDatabaseQueue()) @@ -871,9 +891,42 @@ class ValueObservationTests: GRDBTestCase { try test(makeDatabasePool()) } + // MARK: - Main Actor + @MainActor func test_mainActor_observation() throws { + let dbQueue = try makeDatabaseQueue() + try dbQueue.write { db in + try db.create(table: "test") { t in + t.autoIncrementedPrimaryKey("id") + } + } + + let observation = ValueObservation.tracking { + try Table("test").fetchCount($0) + } + + var value = 0 // No mutex necessary! + let expectation = self.expectation(description: "completion") + let cancellable = observation.start( + in: dbQueue, + onError: { error in XCTFail("Unexpected error: \(error)") }, + onChange: { + value = $0 + if value == 2 { + expectation.fulfill() + } + }) + + try dbQueue.write { db in + try db.execute(sql: "INSERT INTO test DEFAULT VALUES") + try db.execute(sql: "INSERT INTO test DEFAULT VALUES") + } + withExtendedLifetime(cancellable) { _ in + wait(for: [expectation], timeout: 2) + } + } + // MARK: - Async Await - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_values_prefix() async throws { func test(_ writer: some DatabaseWriter) async throws { // We need something to change @@ -911,45 +964,6 @@ class ValueObservationTests: GRDBTestCase { try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - func testAsyncAwait_values_prefix_immediate_scheduling() async throws { - func test(_ writer: some DatabaseWriter) async throws { - // We need something to change - try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - let cancellationExpectation = expectation(description: "cancelled") - let task = Task { @MainActor () -> [Int] in - var counts: [Int] = [] - let observation = ValueObservation - .trackingConstantRegion(Table("t").fetchCount) - .handleEvents(didCancel: { cancellationExpectation.fulfill() }) - - for try await count in try observation.values(in: writer, scheduling: .immediate).prefix(while: { $0 <= 3 }) { - counts.append(count) - try await writer.write { try $0.execute(sql: "INSERT INTO t DEFAULT VALUES") } - } - return counts - } - - let counts = try await task.value - XCTAssertTrue(counts.contains(0)) - XCTAssertTrue(counts.contains(where: { $0 >= 2 })) - XCTAssertEqual(counts.sorted(), counts) - - // Observation was ended -#if compiler(>=5.8) - await fulfillment(of: [cancellationExpectation], timeout: 2) -#else - wait(for: [cancellationExpectation], timeout: 2) -#endif - } - - try await AsyncTest(test).run { try DatabaseQueue() } - try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } - } - - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_values_break() async throws { func test(_ writer: some DatabaseWriter) async throws { // We need something to change @@ -991,46 +1005,6 @@ class ValueObservationTests: GRDBTestCase { try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } } - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) - func testAsyncAwait_values_immediate_break() async throws { - func test(_ writer: some DatabaseWriter) async throws { - // We need something to change - try await writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - let cancellationExpectation = expectation(description: "cancelled") - - let task = Task { @MainActor () -> [Int] in - var counts: [Int] = [] - let observation = ValueObservation - .trackingConstantRegion(Table("t").fetchCount) - .handleEvents(didCancel: { cancellationExpectation.fulfill() }) - - for try await count in observation.values(in: writer, scheduling: .immediate) { - counts.append(count) - break - } - return counts - } - - let counts = try await task.value - - // A single value was published - assertValueObservationRecordingMatch(recorded: counts, expected: [0]) - - // Observation was ended -#if compiler(>=5.8) - await fulfillment(of: [cancellationExpectation], timeout: 2) -#else - wait(for: [cancellationExpectation], timeout: 2) -#endif - } - - try await AsyncTest(test).run { try DatabaseQueue() } - try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabaseQueue(path: $0) } - try await AsyncTest(test).runAtTemporaryDatabasePath { try DatabasePool(path: $0) } - } - - @available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *) func testAsyncAwait_values_cancelled() async throws { func test(_ writer: some DatabaseWriter) async throws { // We need something to change @@ -1083,6 +1057,13 @@ class ValueObservationTests: GRDBTestCase { // An attempt at finding a regression test for func testManyObservations() throws { + // TODO: Fix flaky test with SQLCipher 3 + #if GRDBCIPHER + if Database.sqliteLibVersionNumber <= 3020001 { + throw XCTSkip("Skip flaky test with SQLCipher 3") + } + #endif + // We'll start many observations let observationCount = 100 dbConfiguration.maximumReaderCount = 5 @@ -1095,8 +1076,8 @@ class ValueObservationTests: GRDBTestCase { try Table("t").fetchCount($0) } - let initialValueExpectation = self.expectation(description: "") -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) + let initialValueExpectation = self.expectation(description: "initialValue") +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) initialValueExpectation.assertForOverFulfill = true #else // ValueObservation on DatabasePool will notify the first value twice @@ -1104,7 +1085,7 @@ class ValueObservationTests: GRDBTestCase { #endif initialValueExpectation.expectedFulfillmentCount = observationCount - let secondValueExpectation = self.expectation(description: "") + let secondValueExpectation = self.expectation(description: "secondValue") secondValueExpectation.expectedFulfillmentCount = observationCount var cancellables: [AnyDatabaseCancellable] = [] @@ -1154,7 +1135,7 @@ class ValueObservationTests: GRDBTestCase { } let initialValueExpectation = self.expectation(description: "") -#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))) +#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER) initialValueExpectation.assertForOverFulfill = true #else // ValueObservation on DatabasePool will notify the first value twice @@ -1371,4 +1352,58 @@ class ValueObservationTests: GRDBTestCase { XCTAssertEqual(value, true) }) } + + // Regression test for + @MainActor func testIssue1746() async throws { + let dbQueue = try makeDatabaseQueue() + try await dbQueue.write { db in + try db.execute(sql: "CREATE TABLE test (id INTEGER PRIMARY KEY)") + } + + // Start a task that waits for writeContinuation before it writes. + let (writeStream, writeContinuation) = AsyncStream.makeStream(of: Void.self) + let task = Task { + for await _ in writeStream { } + try? await dbQueue.write { db in + XCTAssertFalse(Task.isCancelled) // Required for the test to be meaningful + try db.execute(sql: "INSERT INTO test DEFAULT VALUES") + } + } + + // A transaction observer that cancels a Task after commit. + class CancelObserver: TransactionObserver { + let task: Task + init(task: Task) { + self.task = task + } + func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { true } + func databaseDidChange(with event: DatabaseEvent) { } + func databaseDidRollback(_ db: Database) { } + func databaseDidCommit(_ db: Database) { + task.cancel() + } + } + + // Register CancelObserver first, so no other observer could access + // the database before the task is cancelled. + dbQueue.add(transactionObserver: CancelObserver(task: task), extent: .databaseLifetime) + + // Start observing. + // We expect to see 0, then 1. + let values = ValueObservation + .tracking(Table("test").fetchCount) + .values(in: dbQueue) + for try await value in values { + if value == 0 { + // Perform the write. + writeContinuation.finish() + } else if value == 1 { + // Test passes + break + } else { + XCTFail("Unexpected value \(value)") + break + } + } + } } diff --git a/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift b/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift index 90f39ded9..72b41d0e0 100644 --- a/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchPositionalValuesTests.swift @@ -1,5 +1,6 @@ import XCTest import GRDB +import SQLite3 #if GRDB_COMPARE import SQLite #endif diff --git a/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift b/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift index 3195e3003..8cdfd5394 100644 --- a/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchRecordOptimizedTests.swift @@ -29,18 +29,20 @@ private struct Item: Codable, FetchableRecord, PersistableRecord { i9 = row[9] } - static let databaseSelection: [any SQLSelectable] = [ - Column("i0"), - Column("i1"), - Column("i2"), - Column("i3"), - Column("i4"), - Column("i5"), - Column("i6"), - Column("i7"), - Column("i8"), - Column("i9"), - ] + static var databaseSelection: [any SQLSelectable] { + [ + Column("i0"), + Column("i1"), + Column("i2"), + Column("i3"), + Column("i4"), + Column("i5"), + Column("i6"), + Column("i7"), + Column("i8"), + Column("i9"), + ] + } } /// Here we test the extraction of a plain Swift struct diff --git a/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift b/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift index a8b734954..13387d5e1 100644 --- a/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift +++ b/Tests/Performance/GRDBPerformance/FetchRecordStructTests.swift @@ -1,5 +1,6 @@ import XCTest import GRDB +import SQLite3 #if GRDB_COMPARE import SQLite #endif diff --git a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj index 18c7372e0..1491ce351 100755 --- a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj +++ b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.pbxproj @@ -29,7 +29,6 @@ 5690AFD92120589A001530EA /* InsertRecordEncodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFD72120589A001530EA /* InsertRecordEncodableTests.swift */; }; 5690AFDB212058CB001530EA /* FetchRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */; }; 5690AFDC212058CB001530EA /* FetchRecordDecodableTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690AFDA212058CB001530EA /* FetchRecordDecodableTests.swift */; }; - 56A3FEA827A85F4800B0292E /* Realm in Frameworks */ = {isa = PBXBuildFile; productRef = 56A3FEA727A85F4800B0292E /* Realm */; }; 56A3FEAA27A85F4800B0292E /* RealmSwift in Frameworks */ = {isa = PBXBuildFile; productRef = 56A3FEA927A85F4800B0292E /* RealmSwift */; }; 56A6F4AC29BBC8E200E22662 /* ArgumentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A6F4AB29BBC8E200E22662 /* ArgumentsTests.swift */; }; 56B6D0E52618BF78003CC455 /* FetchRecordOptimizedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B6D0E42618BF78003CC455 /* FetchRecordOptimizedTests.swift */; }; @@ -134,7 +133,6 @@ 561C25942439C942001227F2 /* FMDB in Frameworks */, 5679870523A37A790076902D /* GRDB.framework in Frameworks */, 56439B431F4CA1DC0066043F /* CoreData.framework in Frameworks */, - 56A3FEA827A85F4800B0292E /* Realm in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -255,7 +253,6 @@ packageProductDependencies = ( 561C25902439C92D001227F2 /* SQLite */, 561C25932439C942001227F2 /* FMDB */, - 56A3FEA727A85F4800B0292E /* Realm */, 56A3FEA927A85F4800B0292E /* RealmSwift */, ); productName = GRDBOSXTests; @@ -636,7 +633,7 @@ repositoryURL = "https://github.com/stephencelis/SQLite.swift.git"; requirement = { kind = upToNextMajorVersion; - minimumVersion = 0.12.2; + minimumVersion = 0.15.3; }; }; 561C25922439C942001227F2 /* XCRemoteSwiftPackageReference "fmdb" */ = { @@ -644,7 +641,7 @@ repositoryURL = "https://github.com/ccgus/fmdb.git"; requirement = { kind = upToNextMajorVersion; - minimumVersion = 2.7.0; + minimumVersion = 2.7.12; }; }; 56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */ = { @@ -652,7 +649,7 @@ repositoryURL = "https://github.com/realm/realm-swift.git"; requirement = { kind = upToNextMajorVersion; - minimumVersion = 10.22.0; + minimumVersion = 20.0.1; }; }; /* End XCRemoteSwiftPackageReference section */ @@ -668,11 +665,6 @@ package = 561C25922439C942001227F2 /* XCRemoteSwiftPackageReference "fmdb" */; productName = FMDB; }; - 56A3FEA727A85F4800B0292E /* Realm */ = { - isa = XCSwiftPackageProductDependency; - package = 56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */; - productName = Realm; - }; 56A3FEA927A85F4800B0292E /* RealmSwift */ = { isa = XCSwiftPackageProductDependency; package = 56A3FEA627A85F4800B0292E /* XCRemoteSwiftPackageReference "realm-swift" */; diff --git a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 65281ac4e..95d315f33 100644 --- a/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -6,8 +6,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/ccgus/fmdb.git", "state" : { - "revision" : "47a2fa12a242b5a2fe13b916c22f2212e426055c", - "version" : "2.7.9" + "revision" : "1227a3fa2b9916bfd75fe380eb45cd210e69e251", + "version" : "2.7.12" } }, { @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/realm/realm-core.git", "state" : { - "revision" : "374dd672af357732dccc135fecc905406fec3223", - "version" : "14.4.1" + "revision" : "15493076ad9fef22c16cc64cbfbf9e5b65c385f9", + "version" : "20.1.0" } }, { @@ -24,8 +24,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/realm/realm-swift.git", "state" : { - "revision" : "e0c2fbb442979fbf1e4be80e01d142f310a9c762", - "version" : "10.49.1" + "revision" : "bae6c4be7df169fdb047d0ad63f902c1e2665e83", + "version" : "20.0.1" } }, { @@ -33,8 +33,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/stephencelis/SQLite.swift.git", "state" : { - "revision" : "e78ae0220e17525a15ac68c697a155eb7a672a8e", - "version" : "0.15.0" + "revision" : "a95fc6df17d108bd99210db5e8a9bac90fe984b8", + "version" : "0.15.3" } } ], diff --git a/Tests/Performance/GRDBPerformance/InsertPositionalValuesTests.swift b/Tests/Performance/GRDBPerformance/InsertPositionalValuesTests.swift index 382c6b516..ec6edb99b 100644 --- a/Tests/Performance/GRDBPerformance/InsertPositionalValuesTests.swift +++ b/Tests/Performance/GRDBPerformance/InsertPositionalValuesTests.swift @@ -1,5 +1,6 @@ import XCTest import GRDB +import SQLite3 #if GRDB_COMPARE import SQLite #endif diff --git a/Tests/Performance/GRDBPerformance/PerformanceTests.swift b/Tests/Performance/GRDBPerformance/PerformanceTests.swift index c9f4ac0bf..d38257002 100644 --- a/Tests/Performance/GRDBPerformance/PerformanceTests.swift +++ b/Tests/Performance/GRDBPerformance/PerformanceTests.swift @@ -9,16 +9,16 @@ import RealmSwift // MARK:- SQLite let itemTable = Table("item") -let i0Column = Expression("i0") -let i1Column = Expression("i1") -let i2Column = Expression("i2") -let i3Column = Expression("i3") -let i4Column = Expression("i4") -let i5Column = Expression("i5") -let i6Column = Expression("i6") -let i7Column = Expression("i7") -let i8Column = Expression("i8") -let i9Column = Expression("i9") +let i0Column = SQLite.Expression("i0") +let i1Column = SQLite.Expression("i1") +let i2Column = SQLite.Expression("i2") +let i3Column = SQLite.Expression("i3") +let i4Column = SQLite.Expression("i4") +let i5Column = SQLite.Expression("i5") +let i6Column = SQLite.Expression("i6") +let i7Column = SQLite.Expression("i7") +let i8Column = SQLite.Expression("i8") +let i9Column = SQLite.Expression("i9") // MARK: - Realm diff --git a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj index 2851c7774..73c21f954 100644 --- a/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj +++ b/Tests/Performance/GRDBProfiling/GRDBProfiling.xcodeproj/project.pbxproj @@ -364,7 +364,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.13; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; @@ -416,7 +416,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.13; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_VERSION = 5.0; diff --git a/Tests/SPM/PlainPackage/Package.swift b/Tests/SPM/PlainPackage/Package.swift index 3673c7afc..6b6996999 100644 --- a/Tests/SPM/PlainPackage/Package.swift +++ b/Tests/SPM/PlainPackage/Package.swift @@ -1,14 +1,20 @@ -// swift-tools-version:5.2 +// swift-tools-version:6.0 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "SPM", + platforms: [ + .iOS(.v13), + .macOS(.v10_15), + .tvOS(.v13), + .watchOS(.v7), + ], dependencies: [ .package(name: "GRDB", path: "../../.."), ], targets: [ - .target(name: "SPM", dependencies: ["GRDB"]), + .executableTarget(name: "SPM", dependencies: ["GRDB"]), ] ) diff --git a/Tests/SPM/PlainPackage/Sources/SPM/main.swift b/Tests/SPM/PlainPackage/Sources/SPM/main.swift index 1e00a3a2b..01ba31151 100644 --- a/Tests/SPM/PlainPackage/Sources/SPM/main.swift +++ b/Tests/SPM/PlainPackage/Sources/SPM/main.swift @@ -1,4 +1,5 @@ import GRDB +import SQLite3 let cVersion = String(cString: sqlite3_libversion()) print("SQLite version from C API: \(cVersion)") diff --git a/Tests/SPM/PlainProject/Plain.xcodeproj/project.pbxproj b/Tests/SPM/PlainProject/Plain.xcodeproj/project.pbxproj index 00bcf692e..46a8734ad 100644 --- a/Tests/SPM/PlainProject/Plain.xcodeproj/project.pbxproj +++ b/Tests/SPM/PlainProject/Plain.xcodeproj/project.pbxproj @@ -187,7 +187,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.13; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; @@ -241,7 +241,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.13; + MACOSX_DEPLOYMENT_TARGET = 10.15; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = macosx; diff --git a/Tests/SPM/ios-dynamic/ios-dynamic/ViewController.swift b/Tests/SPM/ios-dynamic/ios-dynamic/ViewController.swift index 110634c81..9092d3992 100644 --- a/Tests/SPM/ios-dynamic/ios-dynamic/ViewController.swift +++ b/Tests/SPM/ios-dynamic/ios-dynamic/ViewController.swift @@ -7,13 +7,15 @@ import UIKit import GRDB +import SQLite3 class ViewController: UIViewController { - - override func viewDidLoad() { - super.viewDidLoad() - try! print(DatabaseQueue().read { try String.fetchOne($0, sql: "SELECT 'Hello world!'")! }) - } + override func viewDidLoad() { + super.viewDidLoad() + + try! print(DatabaseQueue().read { try String.fetchOne($0, sql: "SELECT 'Hello world!'")! }) + _ = sqlite3_libversion_number() + } } diff --git a/Tests/SPM/ios/ios/AppDelegate.swift b/Tests/SPM/ios/ios/AppDelegate.swift index b257fc310..973983272 100644 --- a/Tests/SPM/ios/ios/AppDelegate.swift +++ b/Tests/SPM/ios/ios/AppDelegate.swift @@ -1,5 +1,6 @@ import UIKit import GRDB +import SQLite3 @main class AppDelegate: UIResponder, UIApplicationDelegate { @@ -7,6 +8,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { _ = try! DatabaseQueue() .readPublisher(value: { _ in }) .assertNoFailure() + _ = sqlite3_libversion_number() return true } diff --git a/Tests/SPM/macos/macos/AppDelegate.swift b/Tests/SPM/macos/macos/AppDelegate.swift index e056c1961..b788baabb 100644 --- a/Tests/SPM/macos/macos/AppDelegate.swift +++ b/Tests/SPM/macos/macos/AppDelegate.swift @@ -1,10 +1,12 @@ import Cocoa import GRDB +import SQLite3 @main class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { _ = try! DatabaseQueue() + _ = sqlite3_libversion_number() } func applicationWillTerminate(_ aNotification: Notification) { diff --git a/Tests/Swift6Migration/LanguageMode5.xcconfig b/Tests/Swift6Migration/LanguageMode5.xcconfig new file mode 100644 index 000000000..4556c2d2a --- /dev/null +++ b/Tests/Swift6Migration/LanguageMode5.xcconfig @@ -0,0 +1,5 @@ +// Swift 5 mode +SWIFT_VERSION = 5.0 + +// Recommended settings +SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES = YES diff --git a/Tests/Swift6Migration/LanguageMode5StrictConcurrency.xcconfig b/Tests/Swift6Migration/LanguageMode5StrictConcurrency.xcconfig new file mode 100644 index 000000000..d74feda27 --- /dev/null +++ b/Tests/Swift6Migration/LanguageMode5StrictConcurrency.xcconfig @@ -0,0 +1,6 @@ +// Swift 5 mode with strict concurrency checkings +SWIFT_VERSION = 5.0 +SWIFT_STRICT_CONCURRENCY = complete + +// Recommended settings +SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES = YES diff --git a/Tests/Swift6Migration/LanguageMode6.xcconfig b/Tests/Swift6Migration/LanguageMode6.xcconfig new file mode 100644 index 000000000..3ce1f8ea2 --- /dev/null +++ b/Tests/Swift6Migration/LanguageMode6.xcconfig @@ -0,0 +1,5 @@ +// Swift 6 mode +SWIFT_VERSION = 6.0 + +// Recommended settings +// SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES = YES diff --git a/Tests/Swift6Migration/Swift6Migration.xcodeproj/project.pbxproj b/Tests/Swift6Migration/Swift6Migration.xcodeproj/project.pbxproj new file mode 100644 index 000000000..31c7cd6bc --- /dev/null +++ b/Tests/Swift6Migration/Swift6Migration.xcodeproj/project.pbxproj @@ -0,0 +1,361 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXBuildFile section */ + 56CFC7D22CA03647000B5023 /* GRDB in Frameworks */ = {isa = PBXBuildFile; productRef = 56CFC7D12CA03647000B5023 /* GRDB */; }; + 56CFC7ED2CA06ADD000B5023 /* LanguageMode5.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 56CFC7EC2CA06ADD000B5023 /* LanguageMode5.xcconfig */; }; + 56CFC7F02CA06B7E000B5023 /* LanguageMode6.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 56CFC7EF2CA06B7E000B5023 /* LanguageMode6.xcconfig */; }; + 56CFC7F12CA06B7E000B5023 /* LanguageMode5StrictConcurrency.xcconfig in Resources */ = {isa = PBXBuildFile; fileRef = 56CFC7EE2CA06B7E000B5023 /* LanguageMode5StrictConcurrency.xcconfig */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 56CFC7BF2CA035E7000B5023 /* Swift6Migration.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Swift6Migration.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 56CFC7EC2CA06ADD000B5023 /* LanguageMode5.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = LanguageMode5.xcconfig; sourceTree = ""; }; + 56CFC7EE2CA06B7E000B5023 /* LanguageMode5StrictConcurrency.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = LanguageMode5StrictConcurrency.xcconfig; sourceTree = ""; }; + 56CFC7EF2CA06B7E000B5023 /* LanguageMode6.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = LanguageMode6.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + 56CFC7C12CA035E7000B5023 /* Swift6Migration */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = Swift6Migration; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + 56CFC7BC2CA035E7000B5023 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 56CFC7D22CA03647000B5023 /* GRDB in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 56CFC7B62CA035E7000B5023 = { + isa = PBXGroup; + children = ( + 56CFC7EC2CA06ADD000B5023 /* LanguageMode5.xcconfig */, + 56CFC7EE2CA06B7E000B5023 /* LanguageMode5StrictConcurrency.xcconfig */, + 56CFC7EF2CA06B7E000B5023 /* LanguageMode6.xcconfig */, + 56CFC7C12CA035E7000B5023 /* Swift6Migration */, + 56CFC7C02CA035E7000B5023 /* Products */, + ); + sourceTree = ""; + }; + 56CFC7C02CA035E7000B5023 /* Products */ = { + isa = PBXGroup; + children = ( + 56CFC7BF2CA035E7000B5023 /* Swift6Migration.app */, + ); + name = Products; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 56CFC7BE2CA035E7000B5023 /* Swift6Migration */ = { + isa = PBXNativeTarget; + buildConfigurationList = 56CFC7CD2CA035E8000B5023 /* Build configuration list for PBXNativeTarget "Swift6Migration" */; + buildPhases = ( + 56CFC7BB2CA035E7000B5023 /* Sources */, + 56CFC7BC2CA035E7000B5023 /* Frameworks */, + 56CFC7BD2CA035E7000B5023 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + 56CFC7C12CA035E7000B5023 /* Swift6Migration */, + ); + name = Swift6Migration; + packageProductDependencies = ( + 56CFC7D12CA03647000B5023 /* GRDB */, + ); + productName = Swift6Migration; + productReference = 56CFC7BF2CA035E7000B5023 /* Swift6Migration.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 56CFC7B72CA035E7000B5023 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1600; + LastUpgradeCheck = 1600; + TargetAttributes = { + 56CFC7BE2CA035E7000B5023 = { + CreatedOnToolsVersion = 16.0; + }; + }; + }; + buildConfigurationList = 56CFC7BA2CA035E7000B5023 /* Build configuration list for PBXProject "Swift6Migration" */; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 56CFC7B62CA035E7000B5023; + minimizedProjectReferenceProxies = 1; + packageReferences = ( + 56CFC7D02CA03647000B5023 /* XCLocalSwiftPackageReference "../../../GRDB.swift" */, + ); + preferredProjectObjectVersion = 77; + productRefGroup = 56CFC7C02CA035E7000B5023 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 56CFC7BE2CA035E7000B5023 /* Swift6Migration */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 56CFC7BD2CA035E7000B5023 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 56CFC7ED2CA06ADD000B5023 /* LanguageMode5.xcconfig in Resources */, + 56CFC7F02CA06B7E000B5023 /* LanguageMode6.xcconfig in Resources */, + 56CFC7F12CA06B7E000B5023 /* LanguageMode5StrictConcurrency.xcconfig in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 56CFC7BB2CA035E7000B5023 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + 56CFC7CB2CA035E8000B5023 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 56CFC7EF2CA06B7E000B5023 /* LanguageMode6.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 56CFC7CC2CA035E8000B5023 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 18.0; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 56CFC7CE2CA035E8000B5023 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_ASSET_PATHS = "\"Swift6Migration/Preview Content\""; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.Swift6Migration; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 56CFC7CF2CA035E8000B5023 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_ASSET_PATHS = "\"Swift6Migration/Preview Content\""; + ENABLE_PREVIEWS = YES; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchScreen_Generation = YES; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.Swift6Migration; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 56CFC7BA2CA035E7000B5023 /* Build configuration list for PBXProject "Swift6Migration" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56CFC7CB2CA035E8000B5023 /* Debug */, + 56CFC7CC2CA035E8000B5023 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 56CFC7CD2CA035E8000B5023 /* Build configuration list for PBXNativeTarget "Swift6Migration" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56CFC7CE2CA035E8000B5023 /* Debug */, + 56CFC7CF2CA035E8000B5023 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 56CFC7D02CA03647000B5023 /* XCLocalSwiftPackageReference "../../../GRDB.swift" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ../../../GRDB.swift; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 56CFC7D12CA03647000B5023 /* GRDB */ = { + isa = XCSwiftPackageProductDependency; + productName = GRDB; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 56CFC7B72CA035E7000B5023 /* Project object */; +} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Tests/Swift6Migration/Swift6Migration.xcodeproj/project.xcworkspace/contents.xcworkspacedata similarity index 100% rename from Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.xcworkspace/contents.xcworkspacedata rename to Tests/Swift6Migration/Swift6Migration.xcodeproj/project.xcworkspace/contents.xcworkspacedata diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/LaunchIcon.imageset/Contents.json b/Tests/Swift6Migration/Swift6Migration/Assets.xcassets/AccentColor.colorset/Contents.json similarity index 67% rename from Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/LaunchIcon.imageset/Contents.json rename to Tests/Swift6Migration/Swift6Migration/Assets.xcassets/AccentColor.colorset/Contents.json index 2cbe59d5e..eb8789700 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/LaunchIcon.imageset/Contents.json +++ b/Tests/Swift6Migration/Swift6Migration/Assets.xcassets/AccentColor.colorset/Contents.json @@ -1,7 +1,6 @@ { - "images" : [ + "colors" : [ { - "filename" : "LaunchIcon.pdf", "idiom" : "universal" } ], diff --git a/Tests/Swift6Migration/Swift6Migration/Assets.xcassets/AppIcon.appiconset/Contents.json b/Tests/Swift6Migration/Swift6Migration/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..230588010 --- /dev/null +++ b/Tests/Swift6Migration/Swift6Migration/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,35 @@ +{ + "images" : [ + { + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "tinted" + } + ], + "idiom" : "universal", + "platform" : "ios", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/Contents.json b/Tests/Swift6Migration/Swift6Migration/Assets.xcassets/Contents.json similarity index 100% rename from Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/Resources/Assets.xcassets/Contents.json rename to Tests/Swift6Migration/Swift6Migration/Assets.xcassets/Contents.json diff --git a/Tests/Swift6Migration/Swift6Migration/AsyncOverload.swift b/Tests/Swift6Migration/Swift6Migration/AsyncOverload.swift new file mode 100644 index 000000000..5c366d279 --- /dev/null +++ b/Tests/Swift6Migration/Swift6Migration/AsyncOverload.swift @@ -0,0 +1,30 @@ +import GRDB + +private struct Player: Codable, FetchableRecord, PersistableRecord { } +let writer: any DatabaseWriter = { fatalError() }() + +private func fetchPlayers() async throws -> [Player] { + try await writer.read(Player.fetchAll) +} + +private func foo() { + Task { + let players = try writer.read(Player.fetchAll) + } +} + +private struct PlayerRepository { + var writer: any DatabaseWriter + + func fetchPlayers() throws -> [Player] { + try writer.read(Player.fetchAll) + } +} + + +private func bar() { + let repository = try! PlayerRepository(writer: DatabaseQueue()) + Task { + let players = try repository.fetchPlayers() + } +} diff --git a/Tests/Swift6Migration/Swift6Migration/ContentView.swift b/Tests/Swift6Migration/Swift6Migration/ContentView.swift new file mode 100644 index 000000000..a7b0b6368 --- /dev/null +++ b/Tests/Swift6Migration/Swift6Migration/ContentView.swift @@ -0,0 +1,24 @@ +// +// ContentView.swift +// Swift6Migration +// +// Created by Gwendal Roué on 22/09/2024. +// + +import SwiftUI + +struct ContentView: View { + var body: some View { + VStack { + Image(systemName: "globe") + .imageScale(.large) + .foregroundStyle(.tint) + Text("Hello, world!") + } + .padding() + } +} + +#Preview { + ContentView() +} diff --git a/Tests/Swift6Migration/Swift6Migration/InferSendableFromCaptures.swift b/Tests/Swift6Migration/Swift6Migration/InferSendableFromCaptures.swift new file mode 100644 index 000000000..0e510ba66 --- /dev/null +++ b/Tests/Swift6Migration/Swift6Migration/InferSendableFromCaptures.swift @@ -0,0 +1,9 @@ +import GRDB + +private struct Player: TableRecord { } + +private func fetchCount(_ writer: any DatabaseWriter) async throws -> Int { + // Converting non-sendable function value to + // '@Sendable (Database) throws -> Int' may introduce data races. + try await writer.read(Player.fetchCount) +} diff --git a/Tests/Swift6Migration/Swift6Migration/NonSendableConfiguration.swift b/Tests/Swift6Migration/Swift6Migration/NonSendableConfiguration.swift new file mode 100644 index 000000000..668682b93 --- /dev/null +++ b/Tests/Swift6Migration/Swift6Migration/NonSendableConfiguration.swift @@ -0,0 +1,21 @@ +import GRDB + +private struct Player1: Codable { } +private struct Player2: Codable { } + +#if swift(<6) +extension Player1: FetchableRecord, MutablePersistableRecord { + // Static property 'databaseSelection' is not concurrency-safe + // because non-'Sendable' type '[any SQLSelectable]' + // may have shared mutable state + static let databaseSelection: [any SQLSelectable] = [ + Column("id"), Column("name"), Column("score") + ] +} +#endif + +extension Player2: FetchableRecord, MutablePersistableRecord { + static var databaseSelection: [any SQLSelectable] { + [Column("id"), Column("name"), Column("score")] + } +} diff --git a/Tests/Swift6Migration/Swift6Migration/NonSendableRecord.swift b/Tests/Swift6Migration/Swift6Migration/NonSendableRecord.swift new file mode 100644 index 000000000..42ab94337 --- /dev/null +++ b/Tests/Swift6Migration/Swift6Migration/NonSendableRecord.swift @@ -0,0 +1,43 @@ +import GRDB + +private final class Player: Codable, Identifiable { + var id: Int64 + var name: String + var score: Int + + init(id: Int64, name: String, score: Int) { + self.id = id + self.name = name + self.score = score + } +} + +extension Player: FetchableRecord, PersistableRecord { } + +#if swift(<6) +private struct PlayerRepository { + var writer: any DatabaseWriter + + func fetch() async throws -> Player? { + // Type 'Player' does not conform to the 'Sendable' protocol + try await writer.read { db in + try Player.fetchOne(db, id: 42) + } + } + + func insert(_ player: Player) async throws { + // Capture of 'player' with non-sendable type 'Player' in a `@Sendable` closure + try await writer.read { db in + try player.insert(db) + } + } + + func observe() { + // Type 'Player' does not conform to the 'Sendable' protocol + let observation = ValueObservation.tracking { db in + try Player.fetchAll(db) + } + _ = observation + } +} +#endif diff --git a/Tests/Swift6Migration/Swift6Migration/Preview Content/Preview Assets.xcassets/Contents.json b/Tests/Swift6Migration/Swift6Migration/Preview Content/Preview Assets.xcassets/Contents.json new file mode 100644 index 000000000..73c00596a --- /dev/null +++ b/Tests/Swift6Migration/Swift6Migration/Preview Content/Preview Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Tests/Swift6Migration/Swift6Migration/Swift6MigrationApp.swift b/Tests/Swift6Migration/Swift6Migration/Swift6MigrationApp.swift new file mode 100644 index 000000000..9ef8b0b0c --- /dev/null +++ b/Tests/Swift6Migration/Swift6Migration/Swift6MigrationApp.swift @@ -0,0 +1,17 @@ +// +// Swift6MigrationApp.swift +// Swift6Migration +// +// Created by Gwendal Roué on 22/09/2024. +// + +import SwiftUI + +@main +struct Swift6MigrationApp: App { + var body: some Scene { + WindowGroup { + ContentView() + } + } +} diff --git a/Tests/generatePerformanceReport.rb b/Tests/generatePerformanceReport.rb index 2af6a9d45..73498145f 100755 --- a/Tests/generatePerformanceReport.rb +++ b/Tests/generatePerformanceReport.rb @@ -35,7 +35,7 @@ samples = JSON.parse(STDIN.read) # have checkouts for all dependencies. # BUILD_ROOT -exit 1 unless `xcodebuild -showBuildSettings -project Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj -target GRDBOSXPerformanceComparisonTests -disableAutomaticPackageResolution` =~ /BUILD_ROOT = (.*)$/ +exit 1 unless `xcodebuild -showBuildSettings -project Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj -scheme GRDBOSXPerformanceComparisonTests -disableAutomaticPackageResolution` =~ /BUILD_ROOT = (.*)$/ BUILD_ROOT = $1 # DERIVED_DATA