mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5ff2ad9e71 | ||
|
|
f5259af512 | ||
|
|
2dd2d2db35 | ||
|
|
9fd3e822e5 | ||
|
|
edbfc7749c | ||
|
|
2aa7e3c79f | ||
|
|
3592db997a | ||
|
|
4307f6a680 | ||
|
|
b7b83a965b | ||
|
|
fcfecc5a73 | ||
|
|
39a76ff929 | ||
|
|
aef2d087ae | ||
|
|
0b12e89e62 | ||
|
|
0379947ab1 | ||
|
|
2e5cf546c6 | ||
|
|
0c011b970b | ||
|
|
a08a86cc76 | ||
|
|
29a21302a2 | ||
|
|
13c804d1cc | ||
|
|
811d287bd9 | ||
|
|
1818534513 | ||
|
|
8d316dc969 | ||
|
|
38e7e649c7 | ||
|
|
3df9e8e5c1 | ||
|
|
c98d918bf6 | ||
|
|
c197e2f520 | ||
|
|
13b3f1d741 | ||
|
|
ad011a0974 | ||
|
|
a89dad2554 | ||
|
|
4f4553f4f0 | ||
|
|
9b505bb34b | ||
|
|
6c841bf96e | ||
|
|
76b05369ff | ||
|
|
e79b6a5622 | ||
|
|
13e1f4d7c2 | ||
|
|
8aaf1af9f0 | ||
|
|
3b10e1df41 | ||
|
|
6caa27cb20 | ||
|
|
6ca3bb051a | ||
|
|
901d010ab3 | ||
|
|
3c4ff5b26e | ||
|
|
2ade133b50 | ||
|
|
c57e76be52 | ||
|
|
9531a7f8fc | ||
|
|
9e3eebf4c2 | ||
|
|
1221cb703a | ||
|
|
59b40de83e | ||
|
|
0ac435744a | ||
|
|
589e53b231 | ||
|
|
125f112fb7 | ||
|
|
c6aa323cd8 | ||
|
|
1c7b618a89 | ||
|
|
d3ad7acd59 | ||
|
|
82b4d90a82 | ||
|
|
2a3318ef9a | ||
|
|
f2c46784a6 | ||
|
|
9340fdc7c2 | ||
|
|
b0f7493765 | ||
|
|
30234fde62 | ||
|
|
fdbcb07452 | ||
|
|
dced16bdce | ||
|
|
849be02906 | ||
|
|
b3f5b892a6 | ||
|
|
65efc413fe | ||
|
|
f3b8b7221c | ||
|
|
f04a02731d | ||
|
|
6add38e3e5 | ||
|
|
202b3e5620 | ||
|
|
49cce0aa8a | ||
|
|
ccf3486827 | ||
|
|
cb93979a44 | ||
|
|
628ac58535 | ||
|
|
373f95a6cb | ||
|
|
f2859ff8bf | ||
|
|
e2b412afc8 | ||
|
|
040e5d9d87 | ||
|
|
189430c1fe | ||
|
|
3d77a8da86 | ||
|
|
c40256600a | ||
|
|
b617f432c0 | ||
|
|
72ef13f4fb | ||
|
|
535f44c463 | ||
|
|
4c10899a3c | ||
|
|
524ee1d098 | ||
|
|
973b679baa | ||
|
|
0321c79c2d | ||
|
|
e82a03615f | ||
|
|
51c9071b3d | ||
|
|
91e5f838d3 | ||
|
|
d026232cbf | ||
|
|
c2e4aaf51d | ||
|
|
05b81df614 | ||
|
|
3e4b04d4d1 | ||
|
|
56cdaabd9c | ||
|
|
c65a19c50f | ||
|
|
5247a1537c | ||
|
|
58f970701f | ||
|
|
980f5247f0 | ||
|
|
d70032c483 | ||
|
|
14321e411c | ||
|
|
d3d2ad1b91 | ||
|
|
55f3c2f510 | ||
|
|
ffa183821c | ||
|
|
327911d057 | ||
|
|
c6657b7063 | ||
|
|
2a5626efea | ||
|
|
6bf346ccf5 | ||
|
|
1036dd4d6e | ||
|
|
48f14c7a8c | ||
|
|
2789444acd | ||
|
|
8f8b273424 | ||
|
|
37f0a0bb9a | ||
|
|
d2dd18b3e5 | ||
|
|
422e0ae85a | ||
|
|
8f562d3e11 | ||
|
|
a702fe6bc9 | ||
|
|
0ed9367b26 | ||
|
|
eda403bd31 | ||
|
|
c553d2d69e | ||
|
|
5243db7fbc | ||
|
|
4ced8c78e7 | ||
|
|
c38d903f4d | ||
|
|
1239c14e6d | ||
|
|
5004994344 | ||
|
|
c86581dedc | ||
|
|
546bba17fb | ||
|
|
27b65c9a80 | ||
|
|
1bfba945d3 | ||
|
|
4c73456f86 | ||
|
|
84940af3dc | ||
|
|
e0786537db | ||
|
|
496c2ae359 | ||
|
|
5b7c58faf4 | ||
|
|
0658808028 | ||
|
|
fb6ea57d74 | ||
|
|
0879311646 | ||
|
|
2f2cccacf9 | ||
|
|
e5d10ed8c1 | ||
|
|
070ee2c796 | ||
|
|
9a9406a69d | ||
|
|
b2eafd4a13 | ||
|
|
36892fee55 | ||
|
|
49a66e197b | ||
|
|
80ec31f588 | ||
|
|
c26ed6c280 | ||
|
|
eb98541923 | ||
|
|
895964de16 | ||
|
|
927fc21f00 | ||
|
|
a15f731042 | ||
|
|
3000cd3c7f | ||
|
|
2011776cbe | ||
|
|
33a039717c | ||
|
|
a20d543bcf | ||
|
|
55445dcc7c | ||
|
|
34a4fa6444 | ||
|
|
dba7f1b2dc | ||
|
|
180c8975ac | ||
|
|
11a6d53d8a | ||
|
|
42987dd849 | ||
|
|
7ffc332327 | ||
|
|
a9fcf1b9c1 | ||
|
|
c0c6b34869 | ||
|
|
dd55175978 | ||
|
|
58293befc9 | ||
|
|
458e1e2675 | ||
|
|
6f0d45eedb | ||
|
|
fe225fe452 | ||
|
|
78b9c543a3 | ||
|
|
86de843bda | ||
|
|
20dcab75c7 | ||
|
|
23cbf13af0 | ||
|
|
6da7d47394 | ||
|
|
fcb037bdf0 | ||
|
|
df0ae43c5f | ||
|
|
fc59b45493 | ||
|
|
a22113faa5 | ||
|
|
d1a32d1950 | ||
|
|
e150ca6864 | ||
|
|
9d7e27ced1 | ||
|
|
df7ba20ff2 | ||
|
|
8dc0168841 |
No files matched your search
+14
-46
@@ -32,29 +32,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.2.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.2.1, Swift 5.5.2"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.1, Swift 5.5.1"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_13.0.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 13.0, Swift 5.5.0"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.5.1.app"
|
||||
runsOn: macOS-11
|
||||
name: "macOS 11, Xcode 12.5.1, Swift 5.4"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
@@ -68,13 +48,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
@@ -88,9 +64,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
@@ -104,9 +80,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
@@ -120,13 +96,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
@@ -140,13 +112,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
shell: "/bin/zsh {0}"
|
||||
- xcode: "Xcode_12.4.app"
|
||||
runsOn: macOS-10.15
|
||||
name: "macOS 10.15, Xcode 12.4, Swift 5.3"
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
@@ -160,9 +128,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_13.3.1.app"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "macOS 12, Xcode 13.3.1, Swift 5.6"
|
||||
name: "macOS 12, Xcode 14.0.1, Swift 5.7"
|
||||
shell: "/bin/zsh {0}"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
+127
-1
@@ -5,9 +5,17 @@ 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.
|
||||
|
||||
#### 6.x Releases
|
||||
|
||||
- `6.3.x` Releases - [6.3.0](#630)
|
||||
- `6.2.x` Releases - [6.2.0](#620)
|
||||
- `6.1.x` Releases - [6.1.0](#610)
|
||||
- `6.0.x` Releases - [6.0.0](#600)
|
||||
- `6.0.0` Betas - [6.0.0-beta](#600-beta) | [6.0.0-beta.2](#600-beta2) | [6.0.0-beta.3](#600-beta3) | [6.0.0-beta.4](#600-beta4)
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.26.x` Releases - [5.26.0](#5260)
|
||||
- `5.26.x` Releases - [5.26.0](#5260) - [5.26.1](#5261)
|
||||
- `5.25.x` Releases - [5.25.0](#5250)
|
||||
- `5.24.x` Releases - [5.24.0](#5240) | [5.24.1](#5241)
|
||||
- `5.23.x` Releases - [5.23.0](#5230)
|
||||
@@ -93,6 +101,124 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 6.3.0
|
||||
|
||||
Released November 6, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.2.0...v6.3.0)
|
||||
|
||||
- **New**: [#1291](https://github.com/groue/GRDB.swift/pull/1291) by [@groue](https://github.com/groue): DocC inline documentation
|
||||
- **New**: The `Row.dataNoCopy` methods are deprecated. Use `Row.withUnsafeData` instead.
|
||||
|
||||
## 6.2.0
|
||||
|
||||
Released October 28, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.1.0...v6.2.0)
|
||||
|
||||
- **New**: [#1289](https://github.com/groue/GRDB.swift/pull/1289) by [@arkie](https://github.com/arkie): Add support for passing in categories to the FTS5 unicode61 tokenizer (SQLite 3.25+)
|
||||
- **Fixed**: The `FTS5Tokenizer.tokenize(query:)` method no longer returns incorrect results for certain tokenizer arguments.
|
||||
|
||||
## 6.1.0
|
||||
|
||||
Released October 20, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0...v6.1.0)
|
||||
|
||||
- **New**: [#1288](https://github.com/groue/GRDB.swift/pull/1288) by [@jcavar](https://github.com/jcavar): Support for strict tables
|
||||
|
||||
## 6.0.0
|
||||
|
||||
Released September 9, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0-beta.4...v6.0.0)
|
||||
|
||||
- **New**: Bump custom SQLite builds v3.39.3
|
||||
- **Fixed**: [#1274](https://github.com/groue/GRDB.swift/discussions/1274) Fixed a bug with HasManyThrough associations when the "through" association has the same association key as the association itself.
|
||||
- **Fixed**: [#1275](https://github.com/groue/GRDB.swift/issues/1275) Enhance error message for some requests involving associations on common table expressions.
|
||||
- **Fixed**: [#1276](https://github.com/groue/GRDB.swift/issues/1276) Fix build error with Xcode 14.0 RC (14A309)
|
||||
- **Breaking Change**: Request methods that accept a closure with a `Database` argument have been renamed with the `WhenConnected` suffix: `request.filterWhenConnected { db in ... }`, etc.
|
||||
|
||||
## 6.0.0-beta.4
|
||||
|
||||
Released August 28, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0-beta.3...v6.0.0-beta.4)
|
||||
|
||||
- **New**: [#1271](https://github.com/groue/GRDB.swift/pull/1271) by [@groue](https://github.com/groue): Bump custom SQLite builds v3.39.2
|
||||
- **New**: [SQLITE_OPEN_EXRESCODE](https://www.sqlite.org/c3ref/open.html), when available, exposes [extended result codes](README.md#databaseerror) when opening a database connection.
|
||||
- **Fixed**: [PRAGMA table_list](https://www.sqlite.org/pragma.html#pragma_table_list), when available, makes it possible for GRDB to detect [WITHOUT ROWID](https://www.sqlite.org/withoutrowid.html) tables without [polluting the SQLite error log](https://github.com/groue/GRDB.swift/issues/945).
|
||||
- **Breaking Change**: The`GRDB.xcodeproj` or `GRDBCustom.xcodeproj` projects now define cross-platforms targets.
|
||||
- **Documentation Update**: [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) describes how to update applications that directly embed the `GRDB.xcodeproj` or `GRDBCustom.xcodeproj` project.
|
||||
- **Documentation Update**: [Custom SQLite Builds](CustomSQLiteBuilds.md) was updated for the new cross-platform target defined by the `GRDBCustom.xcodeproj` project.
|
||||
|
||||
## 6.0.0-beta.3
|
||||
|
||||
Released August 25, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0-beta.2...v6.0.0-beta.3)
|
||||
|
||||
- **Fix**: [#1268](https://github.com/groue/GRDB.swift/pull/1268) by [@groue](https://github.com/groue): Fix SQL generation of CHECK constraints
|
||||
- **Breaking Change**: The `Column` type is no longer `Equatable`
|
||||
- **Documentation Update**: [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) describes in detail how to update records that customize their persistence methods.
|
||||
- **Documentation Update**: The [Single-Row Tables](Documentation/SingleRowTables.md) guide was updated for the new persistence callbacks.
|
||||
|
||||
## 6.0.0-beta.2
|
||||
|
||||
Released August 23, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v6.0.0-beta...v6.0.0-beta.2)
|
||||
|
||||
- **New**: Extended UPSERT apis with the ability to define the conflict target, and the assignments performed in case of conflicts.
|
||||
- **Documentation Update**: A new [Upsert](README.md#upsert) chapter describes upserts in detail.
|
||||
|
||||
## 6.0.0-beta
|
||||
|
||||
Released August 21, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.26.0...v6.0.0-beta)
|
||||
|
||||
### New
|
||||
|
||||
Upgrading your app can bring improvements: check [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md) for some suggestions.
|
||||
|
||||
- :star: Support for [`UPSERT`](https://www.sqlite.org/lang_UPSERT.html): `player.upsert(db)`, etc. See [Persistence Methods](README.md#persistence-methods).
|
||||
|
||||
- :star: Support for the [`RETURNING` clause](https://www.sqlite.org/lang_returning.html): `player.insertAndFetch(db)`, `Player.deleteAndFetchAll(db)`, etc. See [Persistence Methods and the `RETURNING` clause](README.md#persistence-methods-and-the-returning-clause).
|
||||
|
||||
- :star: [Persistence Callbacks](README.md#persistence-callbacks) allow record types to customize persistence methods: `didInsert`, `willSave`, etc.
|
||||
|
||||
- :star: Better support for unexpected database values. Where GRDB 5 would crash during encoding and decoding database values, GRDB 6 has learned to throw errors instead. Record protocols throw decoding and encoding errors, and value requests throw errors on invalid inputs.
|
||||
|
||||
- Request protocols and cursors now define primary associated types, enabled by [SE-0346](https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md).
|
||||
|
||||
- All persistence methods now accept an explicit conflict policy: `player.insert(db, onConflict: .replace)`, etc.
|
||||
|
||||
- You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`.
|
||||
|
||||
- `ValueObservation.map` now accepts a throwing closure argument.
|
||||
|
||||
### Documentation Updates
|
||||
|
||||
- :star: **[Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)**: suggestions for improving your applications, and guidance for handling the breaking changes.
|
||||
- The [Persistence Methods](README.md#persistence-methods) chapter introduces the `upsert` method.
|
||||
- The [Persistence Methods and the `RETURNING` clause](README.md#persistence-methods-and-the-returning-clause) chapter introduces persistence methods that fetch inserted, updated and deleted values.
|
||||
- The [Persistence Callbacks](README.md#persistence-callbacks) chapter introduces the callback invoked from persistence methods, such as `didInsert`, `willSave`, etc.
|
||||
- The [DatabaseRegionObservation](README.md#databaseregionobservation) chapter was updated for the new `DatabaseRegionObservation.start` method.
|
||||
- The [Transaction Hook](README.md#transaction-hook) chapter describes the new `Database.afterNextTransaction(onCommit:onRollback:)` method.
|
||||
- The [Value Queries](README.md#value-queries) chapter explains how to distinguish a request that returns no value from a request that fetches a NULL value.
|
||||
|
||||
### Breaking Changes
|
||||
|
||||
- Removed deprecated methods
|
||||
- :star: Bumped requirements:
|
||||
- Swift 5.7+ and Xcode 14+ are required.
|
||||
- iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ / SQLite 3.19.3+ are required.
|
||||
- :star: Record protocols were refactored:
|
||||
- The `FetchableRecord.init(row:)` initializer can now throw errors.
|
||||
- The `EncodableRecord.encode(to:)` method can now throw errors.
|
||||
- Record types can no longer override persistence methods. You use [Persistence Callbacks](README.md#persistence-callbacks) instead.
|
||||
- Various breaking changes:
|
||||
- The in-memory `DatabaseQueue()` initializer can now throw errors.
|
||||
- The `selectID()` method is replaced with `selectPrimaryKey(as:)`.
|
||||
- `Cursor.isEmpty` is now a throwing property, instead of a method.
|
||||
- The `Record.copy()` method was removed, without replacement.
|
||||
- The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement.
|
||||
- `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable.
|
||||
- The `DatabaseRegionObservation.extent` property was removed.
|
||||
- The `statement` property of database cursors was replaced with read-only properties such as `sql` or `columnNames`.
|
||||
- The `Database.afterNextTransactionCommit(_:)` method was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits.
|
||||
|
||||
## 5.26.1
|
||||
|
||||
Released September 8, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.26.0...v5.26.1)
|
||||
|
||||
- **Fixed**: [#1276](https://github.com/groue/GRDB.swift/issues/1276) Fix build error with Xcode 14.0 RC (14A309)
|
||||
|
||||
## 5.26.0
|
||||
|
||||
Released July 9, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.25.0...v5.26.0)
|
||||
|
||||
+4
-2
@@ -40,7 +40,7 @@ How you can Contribute
|
||||
|
||||
5. **Run tests**
|
||||
|
||||
You can run tests from `GRDB.xcworkspace`, after selecting your target (GRDBOSX, GRDBiOS, GRDBtvOS, from `GRDB.xcodeproj` or `GRDBCustom.xcodeproj`).
|
||||
You can run tests from `GRDB.xcworkspace`, after selecting your scheme (`GRDB` from `GRDB.xcodeproj` or `GRDBCustom` from `GRDBCustom.xcodeproj`).
|
||||
|
||||
Before submitting a pull request, please run in the terminal:
|
||||
|
||||
@@ -69,7 +69,9 @@ How you can Contribute
|
||||
|
||||
7. **Please provide documentation for your changes**
|
||||
|
||||
GRDB documentation is provided as reference (inline doc comments starting with `///`, see [Documentation Comment Syntax](https://github.com/apple/swift/blob/main/docs/DocumentationComments.md)), and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
|
||||
GRDB documentation is provided as a DocC reference, and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
|
||||
|
||||
Please keep the reference and the guides up-to-date. Use Xcode > Product > Build Documentation in order to control the quality of your reference documentation.
|
||||
|
||||
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what is the purpose of your contribution, how to use it, and what are its eventual caveats and corner cases. When the documentation is hard to write, or reveals too many caveats, it is the sign that the api needs to be fixed.
|
||||
|
||||
|
||||
@@ -712,9 +712,9 @@ struct Author: TableRecord {
|
||||
}
|
||||
```
|
||||
|
||||
> :point_up: **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns.
|
||||
> **Note**: Generally speaking, all foreign keys are supported, including composite keys that span several columns.
|
||||
>
|
||||
> :warning: **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either.
|
||||
> **Warning**: SQLite voids foreign key constraints when one or more of a foreign key column is NULL (see [SQLite Foreign Key Support](https://www.sqlite.org/foreignkeys.html)). GRDB does not match foreign keys that involve a NULL value either.
|
||||
|
||||
Sometimes the database schema does not define any foreign key. And sometimes, there are *several* foreign keys from a table to another.
|
||||
|
||||
@@ -1210,7 +1210,7 @@ In the description of the [joining methods] above, we have seen that you need to
|
||||
|
||||
In this chapter, we take the reversed perspective. We list various shapes of decoded record types. When you find the type you want, you'll know the joining method you need.
|
||||
|
||||
> :point_up: **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level apis described in [Decoding a Joined Request with FetchableRecord].
|
||||
> **Note**: If you don't find the type you want, chances are that you are fighting the framework, and should reconsider your position. Your escape hatch is the low-level apis described in [Decoding a Joined Request with FetchableRecord].
|
||||
|
||||
- [`including(required:)`]
|
||||
|
||||
@@ -1435,7 +1435,7 @@ struct BookInfo: FetchableRecord, Decodable {
|
||||
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
> :warning: **Warning**: you can not currently chain a required association behind an optional association:
|
||||
> **Warning**: you can not currently chain a required association behind an optional association:
|
||||
>
|
||||
> ```swift
|
||||
> // Not implemented
|
||||
@@ -1751,7 +1751,7 @@ Associations support more refinements:
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
> :warning: **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc.
|
||||
> **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc.
|
||||
|
||||
|
||||
## Table Aliases
|
||||
@@ -1823,7 +1823,7 @@ let request = Book.aliased(bookAlias)
|
||||
.filter(sql: "b.publishDate >= a.deathDate")
|
||||
```
|
||||
|
||||
> :point_up: **Note**: avoid reusing table aliases between several tables or requests, because you will get a fatal error:
|
||||
> **Note**: avoid reusing table aliases between several tables or requests, because you will get a fatal error:
|
||||
>
|
||||
> ```swift
|
||||
> // Fatal error: A TableAlias most not be used to refer to multiple tables
|
||||
@@ -1832,7 +1832,7 @@ let request = Book.aliased(bookAlias)
|
||||
> let people = Person.aliased(alias)...
|
||||
> ```
|
||||
>
|
||||
> :point_up: **Note**: you can't use the `including(all:)` method and use table aliases to filter the associated records on other records:
|
||||
> **Note**: you can't use the `including(all:)` method and use table aliases to filter the associated records on other records:
|
||||
>
|
||||
> ```swift
|
||||
> // NOT IMPLEMENTED: loading all authors along with their posthumous books
|
||||
@@ -1899,7 +1899,7 @@ For example, we can start by defining base requests as extensions to the [Deriva
|
||||
|
||||
```swift
|
||||
// Author requests
|
||||
extension DerivableRequest where RowDecoder == Author {
|
||||
extension DerivableRequest<Author> {
|
||||
/// Filters authors by country
|
||||
func filter(country: String) -> Self {
|
||||
filter(Column("country") == country)
|
||||
@@ -1907,7 +1907,7 @@ extension DerivableRequest where RowDecoder == Author {
|
||||
}
|
||||
|
||||
// Book requests
|
||||
extension DerivableRequest where RowDecoder == Book {
|
||||
extension DerivableRequest<Book> {
|
||||
/// Filters books by author country
|
||||
func filter(authorCountry: String) -> Self {
|
||||
joining(required: Book.author.filter(country: country))
|
||||
@@ -2165,8 +2165,8 @@ struct BookInfo: FetchableRecord {
|
||||
var country: Country?
|
||||
var coverImage: CoverImage?
|
||||
|
||||
init(row: Row) {
|
||||
book = Book(row: row)
|
||||
init(row: Row) throws {
|
||||
book = try Book(row: row)
|
||||
author = row["author"]
|
||||
country = row["country"]
|
||||
coverImage = row["coverImage"]
|
||||
@@ -2200,8 +2200,8 @@ struct AuthorInfo: FetchableRecord {
|
||||
var author: Author
|
||||
var books: [Book]
|
||||
|
||||
init(row: Row) {
|
||||
author = Author(row: row)
|
||||
init(row: Row) throws {
|
||||
author = try Author(row: row)
|
||||
books = row["books"]
|
||||
}
|
||||
}
|
||||
@@ -2843,7 +2843,7 @@ let request = Book.all().filter(country: "ES")
|
||||
Those methods are defined on extensions to the `DerivableRequest` protocol:
|
||||
|
||||
```swift
|
||||
extension DerivableRequest where RowDecoder == Author {
|
||||
extension DerivableRequest<Author> {
|
||||
func filter(country: String) -> Self {
|
||||
filter(Column("country") == country)
|
||||
}
|
||||
@@ -2853,7 +2853,7 @@ extension DerivableRequest where RowDecoder == Author {
|
||||
}
|
||||
}
|
||||
|
||||
extension DerivableRequest where RowDecoder == Book {
|
||||
extension DerivableRequest<Book> {
|
||||
func filter(country: String) -> Self {
|
||||
joining(required: Book.author.filter(country: country))
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ In this guide, you will learn how to:
|
||||
- [Fetch Values From Common Table Expressions]
|
||||
- Join CTEs with [Associations to Common Table Expressions]
|
||||
|
||||
> :point_up: **Note**: most code examples will be trivial, and not very "useful". This is because the goal of this guide is to stay focused on the GRDB support for CTEs. Rich setup would just be distracting. So bring your own good ideas with you!
|
||||
> **Note**: most code examples will be trivial, and not very "useful". This is because the goal of this guide is to stay focused on the GRDB support for CTEs. Rich setup would just be distracting. So bring your own good ideas with you!
|
||||
|
||||
|
||||
## Define Common Table Expressions
|
||||
@@ -82,7 +82,7 @@ let counterCTE = CommonTableExpression(
|
||||
""")
|
||||
```
|
||||
|
||||
> :point_up: **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs.
|
||||
> **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs.
|
||||
|
||||
|
||||
## Embed Common Table Expressions in Requests
|
||||
@@ -126,13 +126,13 @@ let request = Player
|
||||
.filter(Column("name") == playerNameCTE.all())
|
||||
```
|
||||
|
||||
> :point_up: **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
|
||||
> **Note**: the `with(_:)` method can be called as many times as a there are common table expressions in your request.
|
||||
>
|
||||
> :point_up: **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`.
|
||||
> **Note**: the `with(_:)` method can be called at any time, as all request methods: `Player.with(...).filter(...).with(...)`.
|
||||
>
|
||||
> :point_up: **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it.
|
||||
> **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it.
|
||||
>
|
||||
> :point_up: **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
|
||||
> **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be mismatched with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
|
||||
>
|
||||
> ```swift
|
||||
> cte.all().select(...).filter(...).group(...).order(...)
|
||||
@@ -234,7 +234,7 @@ Parent.including(optional: childAssociation)
|
||||
Parent.including(required: childAssociation)
|
||||
```
|
||||
|
||||
> :point_up: **Note**: common table expressions currently only define "to-one" associations, so the `including(all:)` joining method is unavailable.
|
||||
> **Note**: common table expressions currently only define "to-one" associations, so the `including(all:)` joining method is unavailable.
|
||||
|
||||
CTE associations are generally built with the `association(to:on:)` method, which needs:
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ let playerCount = try dbQueue.read { db in
|
||||
}
|
||||
|
||||
let newPlayerCount = try dbQueue.write { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
try Player(name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
@@ -137,7 +137,7 @@ try dbQueue.write { db in
|
||||
<details>
|
||||
<summary><b>Swift concurrency</b> (async/await)</summary>
|
||||
|
||||
[**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features) GRDB support for Swift concurrency requires Xcode 13.3.1+.
|
||||
[**:fire: EXPERIMENTAL**](../README.md#what-are-experimental-features)
|
||||
|
||||
```swift
|
||||
let playerCount = try await dbQueue.read { db in
|
||||
@@ -145,7 +145,7 @@ let playerCount = try await dbQueue.read { db in
|
||||
}
|
||||
|
||||
let newPlayerCount = try await dbQueue.write { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
try Player(name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
@@ -163,7 +163,7 @@ let playerCountPublisher = dbQueue.readPublisher { db in
|
||||
}
|
||||
|
||||
let newPlayerCountPublisher = dbQueue.writePublisher { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
try Player(name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
@@ -181,7 +181,7 @@ let playerCountObservable = dbQueue.rx.read { db in
|
||||
}
|
||||
|
||||
let newPlayerCountObservable = dbQueue.rx.write { db -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
try Player(name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}
|
||||
```
|
||||
@@ -196,27 +196,24 @@ Those observables do not access the database until they are subscribed. They com
|
||||
```swift
|
||||
dbQueue.asyncRead { (dbResult: Result<Database, Error>) in
|
||||
do {
|
||||
// Maybe read access could not be established
|
||||
let db = try dbResult.get()
|
||||
let playerCount = try Player.fetchCount(db)
|
||||
... // Handle playerCount
|
||||
} catch {
|
||||
... // Handle error
|
||||
// Handle error
|
||||
}
|
||||
}
|
||||
|
||||
dbQueue.asyncWrite({ (db: Database) -> Int in
|
||||
try Player(id: 12, name: "Arthur").insert(db)
|
||||
dbQueue.asyncWrite { (db: Database) -> Int in
|
||||
try Player(name: "Arthur").insert(db)
|
||||
return try Player.fetchCount(db)
|
||||
}, completion: { (db: Database, result: Result<Int, Error>) in
|
||||
// Handle write transaction result:
|
||||
} completion: { (db: Database, result: Result<Int, Error>) in
|
||||
switch result {
|
||||
case let .success(newPlayerCount):
|
||||
... // Handle newPlayerCount
|
||||
// Handle success
|
||||
case let .failure(error):
|
||||
... // Handle error
|
||||
// Handle error
|
||||
}
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -506,7 +503,7 @@ try snapshot2.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
> :point_up: **Note**: snapshots currently serialize all database accesses. In the future, snapshots may allow concurrent reads.
|
||||
> **Note**: snapshots currently serialize all database accesses. In the future, snapshots may allow concurrent reads.
|
||||
|
||||
[^1]: This immutable view of the database is called [snapshot isolation](https://www.sqlite.org/isolation.html).
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ 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.37.2](https://www.sqlite.org/changes.html).**
|
||||
**You can build GRDB with a custom build of [SQLite 3.39.3](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](../../../#support-for-sqlite-pre-update-hooks).
|
||||
|
||||
@@ -111,9 +111,9 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
|
||||
|
||||
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
|
||||
|
||||
6. Add the `GRDBCustomSQLiteOSX` or `GRDBCustomSQLiteiOS` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
|
||||
6. Add the `GRDBCustom` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
|
||||
|
||||
7. Add the `GRDBCustomSQLite.framework` from the targeted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
|
||||
7. Add the `GRDBCustom.framework` from the targeted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
|
||||
|
||||
8. Add a Run Script phase for your target in the **Pre-actions** section of the **Build** tab of your **application scheme**:
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@
|
||||
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 */; };
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78E2F9E5261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -37,13 +36,6 @@
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBAsyncDemo;
|
||||
};
|
||||
78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBAsyncDemo;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
@@ -82,9 +74,6 @@
|
||||
567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = "<group>"; };
|
||||
56F8A12E27359A350011ACBE /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = "<group>"; };
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBAsyncDemoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBAsyncDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBAsyncDemoUITests.swift; sourceTree = "<group>"; };
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -104,13 +93,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
@@ -140,7 +122,6 @@
|
||||
children = (
|
||||
567C3E182520B6DE0011F6E9 /* GRDBAsyncDemo */,
|
||||
56026C9925B8A7D000D1DF3F /* GRDBAsyncDemoTests */,
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBAsyncDemoUITests */,
|
||||
567C3E172520B6DE0011F6E9 /* Products */,
|
||||
567C3E4D2520B70E0011F6E9 /* Frameworks */,
|
||||
56F8A12E27359A350011ACBE /* GRDB.swift */,
|
||||
@@ -152,7 +133,6 @@
|
||||
children = (
|
||||
567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */,
|
||||
56026C9825B8A7D000D1DF3F /* GRDBAsyncDemoTests.xctest */,
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBAsyncDemoUITests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -200,15 +180,6 @@
|
||||
path = Views;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBAsyncDemoUITests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift */,
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */,
|
||||
);
|
||||
path = GRDBAsyncDemoUITests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
@@ -253,24 +224,6 @@
|
||||
productReference = 567C3E162520B6DE0011F6E9 /* GRDBAsyncDemo.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBAsyncDemoUITests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoUITests" */;
|
||||
buildPhases = (
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */,
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */,
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBAsyncDemoUITests;
|
||||
productName = GRDBAsyncDemoUITests;
|
||||
productReference = 78E2F9E3261EEC22005D1F7F /* GRDBAsyncDemoUITests.xctest */;
|
||||
productType = "com.apple.product-type.bundle.ui-testing";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
@@ -287,10 +240,6 @@
|
||||
567C3E152520B6DE0011F6E9 = {
|
||||
CreatedOnToolsVersion = 12.0;
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F = {
|
||||
CreatedOnToolsVersion = 12.5;
|
||||
TestTargetID = 567C3E152520B6DE0011F6E9;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBAsyncDemo" */;
|
||||
@@ -311,7 +260,6 @@
|
||||
targets = (
|
||||
567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */,
|
||||
56026C9725B8A7D000D1DF3F /* GRDBAsyncDemoTests */,
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBAsyncDemoUITests */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -335,13 +283,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
@@ -372,14 +313,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBAsyncDemoUITests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
@@ -392,11 +325,6 @@
|
||||
isa = PBXTargetDependency;
|
||||
productRef = 56F8A13027359A540011ACBE /* GRDB */;
|
||||
};
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 567C3E152520B6DE0011F6E9 /* GRDBAsyncDemo */;
|
||||
targetProxy = 78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin PBXVariantGroup section */
|
||||
@@ -617,44 +545,6 @@
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBAsyncDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBAsyncDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBAsyncDemo;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
78E2F9EB261EEC22005D1F7F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBAsyncDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBAsyncDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBAsyncDemo;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
@@ -685,15 +575,6 @@
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBAsyncDemoUITests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */,
|
||||
78E2F9EB261EEC22005D1F7F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
|
||||
+3
-12
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -29,7 +29,8 @@
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
skipped = "NO"
|
||||
parallelizable = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56026C9725B8A7D000D1DF3F"
|
||||
@@ -38,16 +39,6 @@
|
||||
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "78E2F9E2261EEC22005D1F7F"
|
||||
BuildableName = "GRDBAsyncDemoUITests.xctest"
|
||||
BlueprintName = "GRDBAsyncDemoUITests"
|
||||
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
|
||||
@@ -7,7 +7,7 @@ import GRDB
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
init(_ dbWriter: any DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
}
|
||||
@@ -18,7 +18,7 @@ struct AppDatabase {
|
||||
/// can use a fast in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
|
||||
private let dbWriter: DatabaseWriter
|
||||
private let dbWriter: any DatabaseWriter
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
|
||||
@@ -59,7 +59,7 @@ extension AppDatabase {
|
||||
static func empty() -> AppDatabase {
|
||||
// Connect to an in-memory database
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try! DatabaseQueue()
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
|
||||
@@ -60,8 +60,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
}
|
||||
|
||||
/// Updates a player id after it has been inserted in the database.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
|
||||
// When we instantiate an AppDatabase
|
||||
_ = try AppDatabase(dbQueue)
|
||||
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_inserts() async throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
@@ -29,12 +29,13 @@ class AppDatabaseTests: XCTestCase {
|
||||
try await appDatabase.savePlayer(&player)
|
||||
|
||||
// Then the player exists in the database
|
||||
try XCTAssertTrue(dbQueue.read(player.exists))
|
||||
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 = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = try await dbQueue.write { db in
|
||||
try Player(id: nil, name: "Arthur", score: 100).inserted(db)
|
||||
@@ -54,14 +55,14 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deletePlayers() async throws {
|
||||
// Given a players database that contains four players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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.selectID().fetchAll(db)
|
||||
return try Player.selectPrimaryKey().fetchAll(db)
|
||||
}
|
||||
|
||||
// When we delete two players
|
||||
@@ -76,12 +77,13 @@ class AppDatabaseTests: XCTestCase {
|
||||
}
|
||||
|
||||
// Then the database still contains two players
|
||||
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 2)
|
||||
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 = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
try await dbQueue.write { db in
|
||||
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
|
||||
@@ -94,24 +96,26 @@ class AppDatabaseTests: XCTestCase {
|
||||
try await appDatabase.deleteAllPlayers()
|
||||
|
||||
// Then the database does not contain any player
|
||||
try XCTAssertEqual(dbQueue.read(Player.fetchCount), 0)
|
||||
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 = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
try await appDatabase.refreshPlayers()
|
||||
|
||||
// Then the database is not empty
|
||||
try XCTAssert(dbQueue.read(Player.fetchCount) > 0)
|
||||
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 = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
@@ -123,7 +127,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
|
||||
// Given a players database that contains one player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class PlayerRequestTests: XCTestCase {
|
||||
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
@@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
|
||||
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testInsert() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player
|
||||
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testRoundtrip() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player and fetch the player with the same id
|
||||
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScore() throws {
|
||||
// Given a players database that contains players with distinct scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScoreSortsIdenticalScoresByName() throws {
|
||||
// Given a players database that contains players with common scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByName() throws {
|
||||
// Given a players database that contains players with distinct names
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
//
|
||||
// GRDBAsyncDemoUITests.swift
|
||||
// GRDBAsyncDemoUITests
|
||||
//
|
||||
// Created by Peter Steinberger on 08.04.21.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class GRDBAsyncDemoUITests: XCTestCase {
|
||||
|
||||
override func setUpWithError() throws {
|
||||
// In UI tests it is usually best to stop immediately when a failure occurs.
|
||||
continueAfterFailure = false
|
||||
}
|
||||
|
||||
override func tearDownWithError() throws {
|
||||
}
|
||||
|
||||
func runApp() -> XCUIApplication {
|
||||
// UI tests must launch the application that they test.
|
||||
let app = XCUIApplication()
|
||||
// We enforce a fresh database to ensure 8 random players.
|
||||
app.launchArguments = ["-reset", "-fixedTestData"]
|
||||
app.launch()
|
||||
return app
|
||||
}
|
||||
|
||||
// This test, introduced in 481f6e93, tests the @Query fix added in
|
||||
// 68874412. The fix expresses itself when a view defines an @Query
|
||||
// property that is replaced in the view initializer, as in 481f6e93.
|
||||
//
|
||||
// It happens that I did not find that this particular view setup was suited
|
||||
// for a demo app. The demo has to find a delicate balance, not too trivial,
|
||||
// but without gratuitous complexity.
|
||||
//
|
||||
// I simplified the demo app in a5ffc52d, and we no longer have any view
|
||||
// that defines an @Query property which is replaced in the view
|
||||
// initializer. This means that this test no longer checks against
|
||||
// 68874412 regressions!
|
||||
//
|
||||
// Whenever the @Query property wrapper ships with GRDB itself, make sure
|
||||
// we test for those regressions!
|
||||
func testInitialSortingIsByScore() throws {
|
||||
let app = runApp()
|
||||
|
||||
let getFirstCell = { () -> XCUIElement in
|
||||
app.tables.element(boundBy: 0).cells.element(boundBy: 0)
|
||||
}
|
||||
|
||||
// Given default sorting, Henriette must be on top
|
||||
XCTAssertEqual(getFirstCell().label, "Craig, 8 points")
|
||||
|
||||
// Reverse sorting will bring Arthur on top (sort by name)
|
||||
app.buttons["Score"].tap()
|
||||
XCTAssertEqual(getFirstCell().label, "Arthur, 5 points")
|
||||
}
|
||||
|
||||
func testListAndAddPlayer() throws {
|
||||
let app = runApp()
|
||||
|
||||
// Ensure we have 8 players visible
|
||||
XCTAssert(app.tables.cells.count == 8)
|
||||
|
||||
// add a player
|
||||
app.buttons["New Player"].tap()
|
||||
|
||||
let playerNameField = app.textFields["Player Name"]
|
||||
playerNameField.tap()
|
||||
playerNameField.typeText("Tim Apple")
|
||||
|
||||
app.buttons["Save"].tap()
|
||||
|
||||
// This is suboptimal, but we need to wait for the animation to finish
|
||||
// A better way could be to disable animations globally,
|
||||
// and/or a hook to detect when the async fetch completes.
|
||||
sleep(2)
|
||||
|
||||
XCTAssert(app.tables.cells.count == 9)
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -7,7 +7,7 @@ Async/Await + SwiftUI Demo Application
|
||||
|
||||
**Requirements**: iOS 15.0+ / Xcode 13.1+
|
||||
|
||||
> :point_up: **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.
|
||||
> **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:
|
||||
|
||||
|
||||
@@ -26,7 +26,6 @@
|
||||
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 */; };
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -37,13 +36,6 @@
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBCombineDemo;
|
||||
};
|
||||
78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 567C3E152520B6DE0011F6E9;
|
||||
remoteInfo = GRDBCombineDemo;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
@@ -82,9 +74,6 @@
|
||||
567C3E782520BB650011F6E9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
|
||||
56B6D1082619EC1B003CC455 /* PlayerRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerRequest.swift; sourceTree = "<group>"; };
|
||||
56F8A11C2735988F0011ACBE /* GRDB.swift */ = {isa = PBXFileReference; lastKnownFileType = folder; name = GRDB.swift; path = ../../..; sourceTree = "<group>"; };
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCombineDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoUITests.swift; sourceTree = "<group>"; };
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -104,13 +93,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
@@ -140,7 +122,6 @@
|
||||
children = (
|
||||
567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */,
|
||||
56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */,
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */,
|
||||
567C3E172520B6DE0011F6E9 /* Products */,
|
||||
567C3E4D2520B70E0011F6E9 /* Frameworks */,
|
||||
56F8A11C2735988F0011ACBE /* GRDB.swift */,
|
||||
@@ -152,7 +133,6 @@
|
||||
children = (
|
||||
567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */,
|
||||
56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */,
|
||||
78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -200,15 +180,6 @@
|
||||
path = Views;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
78E2F9E4261EEC22005D1F7F /* GRDBCombineDemoUITests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
78E2F9E5261EEC22005D1F7F /* GRDBCombineDemoUITests.swift */,
|
||||
78E2F9E7261EEC22005D1F7F /* Info.plist */,
|
||||
);
|
||||
path = GRDBCombineDemoUITests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
@@ -253,24 +224,6 @@
|
||||
productReference = 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBCombineDemoUITests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = 78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoUITests" */;
|
||||
buildPhases = (
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */,
|
||||
78E2F9E0261EEC22005D1F7F /* Frameworks */,
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBCombineDemoUITests;
|
||||
productName = GRDBCombineDemoUITests;
|
||||
productReference = 78E2F9E3261EEC22005D1F7F /* GRDBCombineDemoUITests.xctest */;
|
||||
productType = "com.apple.product-type.bundle.ui-testing";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
@@ -287,10 +240,6 @@
|
||||
567C3E152520B6DE0011F6E9 = {
|
||||
CreatedOnToolsVersion = 12.0;
|
||||
};
|
||||
78E2F9E2261EEC22005D1F7F = {
|
||||
CreatedOnToolsVersion = 12.5;
|
||||
TestTargetID = 567C3E152520B6DE0011F6E9;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */;
|
||||
@@ -311,7 +260,6 @@
|
||||
targets = (
|
||||
567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */,
|
||||
56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */,
|
||||
78E2F9E2261EEC22005D1F7F /* GRDBCombineDemoUITests */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -335,13 +283,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9E1261EEC22005D1F7F /* Resources */ = {
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
@@ -372,14 +313,6 @@
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
78E2F9DF261EEC22005D1F7F /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
78E2F9E6261EEC22005D1F7F /* GRDBCombineDemoUITests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
@@ -392,11 +325,6 @@
|
||||
isa = PBXTargetDependency;
|
||||
productRef = 56F8A11D273598960011ACBE /* GRDB */;
|
||||
};
|
||||
78E2F9E9261EEC22005D1F7F /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */;
|
||||
targetProxy = 78E2F9E8261EEC22005D1F7F /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin PBXVariantGroup section */
|
||||
@@ -615,44 +543,6 @@
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBCombineDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBCombineDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBCombineDemo;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
78E2F9EB261EEC22005D1F7F /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
DEVELOPMENT_TEAM = "";
|
||||
INFOPLIST_FILE = GRDBCombineDemoUITests/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
"@loader_path/Frameworks",
|
||||
);
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.groue.GRDBCombineDemoUITests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TARGETED_DEVICE_FAMILY = "1,2";
|
||||
TEST_TARGET_NAME = GRDBCombineDemo;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
@@ -683,15 +573,6 @@
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
78E2F9F3261EEC22005D1F7F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoUITests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
78E2F9EA261EEC22005D1F7F /* Debug */,
|
||||
78E2F9EB261EEC22005D1F7F /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
|
||||
+3
-12
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -29,7 +29,8 @@
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
skipped = "NO"
|
||||
parallelizable = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56026C9725B8A7D000D1DF3F"
|
||||
@@ -38,16 +39,6 @@
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "78E2F9E2261EEC22005D1F7F"
|
||||
BuildableName = "GRDBCombineDemoUITests.xctest"
|
||||
BlueprintName = "GRDBCombineDemoUITests"
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
|
||||
@@ -8,7 +8,7 @@ import GRDB
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
init(_ dbWriter: any DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
}
|
||||
@@ -19,7 +19,7 @@ struct AppDatabase {
|
||||
/// can use a fast in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
|
||||
private let dbWriter: DatabaseWriter
|
||||
private let dbWriter: any DatabaseWriter
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
|
||||
@@ -59,7 +59,7 @@ extension AppDatabase {
|
||||
static func empty() -> AppDatabase {
|
||||
// Connect to an in-memory database
|
||||
// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try! DatabaseQueue()
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
|
||||
@@ -60,8 +60,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
}
|
||||
|
||||
/// Updates a player id after it has been inserted in the database.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
|
||||
// When we instantiate an AppDatabase
|
||||
_ = try AppDatabase(dbQueue)
|
||||
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_inserts() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_updates() throws {
|
||||
// Given a players database that contains a player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deletePlayers() throws {
|
||||
// Given a players database that contains four players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 200)
|
||||
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deleteAllPlayers() throws {
|
||||
// Given a players database that contains players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 200)
|
||||
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_refreshPlayers_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
|
||||
// Given a players database that contains one player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
|
||||
+2
-2
@@ -5,7 +5,7 @@ import GRDB
|
||||
class PlayerRequestTests: XCTestCase {
|
||||
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
@@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase {
|
||||
|
||||
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
|
||||
// Given a players database that contains two players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 1000)
|
||||
|
||||
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testInsert() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player
|
||||
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testRoundtrip() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player and fetch the player with the same id
|
||||
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScore() throws {
|
||||
// Given a players database that contains players with distinct scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScoreSortsIdenticalScoresByName() throws {
|
||||
// Given a players database that contains players with common scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByName() throws {
|
||||
// Given a players database that contains players with distinct names
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
|
||||
-81
@@ -1,81 +0,0 @@
|
||||
//
|
||||
// GRDBCombineDemoUITests.swift
|
||||
// GRDBCombineDemoUITests
|
||||
//
|
||||
// Created by Peter Steinberger on 08.04.21.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
|
||||
class GRDBCombineDemoUITests: XCTestCase {
|
||||
|
||||
override func setUpWithError() throws {
|
||||
// In UI tests it is usually best to stop immediately when a failure occurs.
|
||||
continueAfterFailure = false
|
||||
}
|
||||
|
||||
override func tearDownWithError() throws {
|
||||
}
|
||||
|
||||
func runApp() -> XCUIApplication {
|
||||
// UI tests must launch the application that they test.
|
||||
let app = XCUIApplication()
|
||||
// We enforce a fresh database to ensure 8 random players.
|
||||
app.launchArguments = ["-reset", "-fixedTestData"]
|
||||
app.launch()
|
||||
return app
|
||||
}
|
||||
|
||||
// This test, introduced in 481f6e93, tests the @Query fix added in
|
||||
// 68874412. The fix expresses itself when a view defines an @Query
|
||||
// property that is replaced in the view initializer, as in 481f6e93.
|
||||
//
|
||||
// It happens that I did not find that this particular view setup was suited
|
||||
// for a demo app. The demo has to find a delicate balance, not too trivial,
|
||||
// but without gratuitous complexity.
|
||||
//
|
||||
// I simplified the demo app in a5ffc52d, and we no longer have any view
|
||||
// that defines an @Query property which is replaced in the view
|
||||
// initializer. This means that this test no longer checks against
|
||||
// 68874412 regressions!
|
||||
//
|
||||
// Whenever the @Query property wrapper ships with GRDB itself, make sure
|
||||
// we test for those regressions!
|
||||
func testInitialSortingIsByScore() throws {
|
||||
let app = runApp()
|
||||
|
||||
let getFirstCell = { () -> XCUIElement in
|
||||
app.tables.element(boundBy: 0).cells.element(boundBy: 0)
|
||||
}
|
||||
|
||||
// Given default sorting, Henriette must be on top
|
||||
XCTAssertEqual(getFirstCell().label, "Craig, 8 points")
|
||||
|
||||
// Reverse sorting will bring Arthur on top (sort by name)
|
||||
app.buttons["Score"].tap()
|
||||
XCTAssertEqual(getFirstCell().label, "Arthur, 5 points")
|
||||
}
|
||||
|
||||
func testListAndAddPlayer() throws {
|
||||
let app = runApp()
|
||||
|
||||
// Ensure we have 8 players visible
|
||||
XCTAssert(app.tables.cells.count == 8)
|
||||
|
||||
// add a player
|
||||
app.buttons["New Player"].tap()
|
||||
|
||||
let playerNameField = app.textFields["Player Name"]
|
||||
playerNameField.tap()
|
||||
playerNameField.typeText("Tim Apple")
|
||||
|
||||
app.buttons["Save"].tap()
|
||||
|
||||
// This is suboptimal, but we need to wait for the animation to finish
|
||||
// A better way could be to disable animations globally,
|
||||
// and/or a hook to detect when the async fetch completes.
|
||||
sleep(2)
|
||||
|
||||
XCTAssert(app.tables.cells.count == 9)
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>$(PRODUCT_BUNDLE_PACKAGE_TYPE)</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -7,7 +7,7 @@ Combine + SwiftUI Demo Application
|
||||
|
||||
**Requirements**: iOS 15.0+ / Xcode 12+
|
||||
|
||||
> :point_up: **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.
|
||||
> **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:
|
||||
|
||||
|
||||
@@ -10,13 +10,13 @@
|
||||
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 */; };
|
||||
56606D202355938A00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; };
|
||||
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
56606D24235593AB00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; };
|
||||
56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
|
||||
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 App Extensions */ = {isa = PBXBuildFile; fileRef = 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
|
||||
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 */; };
|
||||
@@ -54,62 +54,6 @@
|
||||
remoteGlobalIDString = 56E5D7F91B4D422D00430942;
|
||||
remoteInfo = GRDBOSXTests;
|
||||
};
|
||||
56606D112355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56553C181C3E906C00522B5C;
|
||||
remoteInfo = GRDBOSXCrashTests;
|
||||
};
|
||||
56606D132355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7CA1B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
56606D152355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 56E5D7D31B4D3FEE00430942;
|
||||
remoteInfo = GRDBiOSTests;
|
||||
};
|
||||
56606D172355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = 565490A01D5A4798005622CB;
|
||||
remoteInfo = GRDBWatchOS;
|
||||
};
|
||||
56606D192355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = AAA4DCFE230F1E0600C74B15;
|
||||
remoteInfo = GRDBtvOS;
|
||||
};
|
||||
56606D1B2355931F00185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 2;
|
||||
remoteGlobalIDString = AAA4DDD4230F262000C74B15;
|
||||
remoteInfo = GRDBtvOSTests;
|
||||
};
|
||||
56606D1D2355937900185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 56E5D7C91B4D3FED00430942;
|
||||
remoteInfo = GRDBiOS;
|
||||
};
|
||||
56606D22235593A300185962 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = 5654909F1D5A4798005622CB;
|
||||
remoteInfo = GRDBWatchOS;
|
||||
};
|
||||
568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */;
|
||||
@@ -127,15 +71,15 @@
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
568E5FDD1E926430002582E0 /* Embed App Extensions */ = {
|
||||
568E5FDD1E926430002582E0 /* Embed Foundation Extensions */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 13;
|
||||
files = (
|
||||
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed App Extensions */,
|
||||
568E5FCC1E926430002582E0 /* GRDBDemoWatchOS Extension.appex in Embed Foundation Extensions */,
|
||||
);
|
||||
name = "Embed App Extensions";
|
||||
name = "Embed Foundation Extensions";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
568E5FE11E926430002582E0 /* Embed Watch Content */ = {
|
||||
@@ -155,7 +99,7 @@
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */,
|
||||
567940C828BA33DE004A0298 /* GRDB.framework in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -166,7 +110,7 @@
|
||||
dstPath = "";
|
||||
dstSubfolderSpec = 10;
|
||||
files = (
|
||||
56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */,
|
||||
567940C628BA33D2004A0298 /* GRDB.framework in Embed Frameworks */,
|
||||
);
|
||||
name = "Embed Frameworks";
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
@@ -214,7 +158,7 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56606D24235593AB00185962 /* GRDB.framework in Frameworks */,
|
||||
567940C728BA33DE004A0298 /* GRDB.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -222,7 +166,7 @@
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56606D202355938A00185962 /* GRDB.framework in Frameworks */,
|
||||
567940C528BA33D2004A0298 /* GRDB.framework in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -243,13 +187,7 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56606D0A2355931F00185962 /* GRDB.framework */,
|
||||
56606D0C2355931F00185962 /* GRDBOSXTests.xctest */,
|
||||
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */,
|
||||
56606D142355931F00185962 /* GRDB.framework */,
|
||||
56606D162355931F00185962 /* GRDBiOSTests.xctest */,
|
||||
56606D182355931F00185962 /* GRDB.framework */,
|
||||
56606D1A2355931F00185962 /* GRDB.framework */,
|
||||
56606D1C2355931F00185962 /* GRDBtvOSTests.xctest */,
|
||||
56606D0C2355931F00185962 /* GRDBTests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
@@ -366,7 +304,7 @@
|
||||
buildConfigurationList = 568E5FDE1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS" */;
|
||||
buildPhases = (
|
||||
568E5FBD1E926430002582E0 /* Resources */,
|
||||
568E5FDD1E926430002582E0 /* Embed App Extensions */,
|
||||
568E5FDD1E926430002582E0 /* Embed Foundation Extensions */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
@@ -390,7 +328,6 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
56606D23235593A300185962 /* PBXTargetDependency */,
|
||||
);
|
||||
name = "GRDBDemoWatchOS Extension";
|
||||
productName = "GRDBDemoWatchOS Extension";
|
||||
@@ -410,7 +347,6 @@
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
56606D1E2355937900185962 /* PBXTargetDependency */,
|
||||
568E5FD81E926430002582E0 /* PBXTargetDependency */,
|
||||
);
|
||||
name = GRDBDemoiOS;
|
||||
@@ -425,7 +361,7 @@
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 1230;
|
||||
LastUpgradeCheck = 1200;
|
||||
LastUpgradeCheck = 1400;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
56185BEF25B80B8900B9C30F = {
|
||||
@@ -488,55 +424,13 @@
|
||||
remoteRef = 56606D092355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D0C2355931F00185962 /* GRDBOSXTests.xctest */ = {
|
||||
56606D0C2355931F00185962 /* GRDBTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXTests.xctest;
|
||||
path = GRDBTests.xctest;
|
||||
remoteRef = 56606D0B2355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D122355931F00185962 /* GRDBOSXCrashTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBOSXCrashTests.xctest;
|
||||
remoteRef = 56606D112355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D142355931F00185962 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56606D132355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D162355931F00185962 /* GRDBiOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBiOSTests.xctest;
|
||||
remoteRef = 56606D152355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D182355931F00185962 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56606D172355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D1A2355931F00185962 /* GRDB.framework */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.framework;
|
||||
path = GRDB.framework;
|
||||
remoteRef = 56606D192355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
56606D1C2355931F00185962 /* GRDBtvOSTests.xctest */ = {
|
||||
isa = PBXReferenceProxy;
|
||||
fileType = wrapper.cfbundle;
|
||||
path = GRDBtvOSTests.xctest;
|
||||
remoteRef = 56606D1B2355931F00185962 /* PBXContainerItemProxy */;
|
||||
sourceTree = BUILT_PRODUCTS_DIR;
|
||||
};
|
||||
/* End PBXReferenceProxy section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
@@ -617,16 +511,6 @@
|
||||
target = 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */;
|
||||
targetProxy = 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */;
|
||||
};
|
||||
56606D1E2355937900185962 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBiOS;
|
||||
targetProxy = 56606D1D2355937900185962 /* PBXContainerItemProxy */;
|
||||
};
|
||||
56606D23235593A300185962 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
name = GRDBWatchOS;
|
||||
targetProxy = 56606D22235593A300185962 /* PBXContainerItemProxy */;
|
||||
};
|
||||
568E5FCE1E926430002582E0 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = 568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */;
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1200"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
+3
-2
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -29,7 +29,8 @@
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
skipped = "NO"
|
||||
parallelizable = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56185BEF25B80B8900B9C30F"
|
||||
|
||||
@@ -6,7 +6,7 @@ import GRDB
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
final class AppDatabase {
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: DatabaseWriter) throws {
|
||||
init(_ dbWriter: any DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
}
|
||||
@@ -17,7 +17,7 @@ final class AppDatabase {
|
||||
/// in-memory `DatabaseQueue`.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections>
|
||||
private let dbWriter: DatabaseWriter
|
||||
private let dbWriter: any DatabaseWriter
|
||||
|
||||
/// The DatabaseMigrator that defines the database schema.
|
||||
///
|
||||
|
||||
@@ -59,8 +59,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
}
|
||||
|
||||
/// Updates a player id after it has been inserted in the database.
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
extension DerivableRequest where RowDecoder == Player {
|
||||
extension DerivableRequest<Player> {
|
||||
/// A request of players ordered by name.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
+1
-1
@@ -144,7 +144,7 @@ class PlayerListViewController: UITableViewController {
|
||||
scheduling: .immediate,
|
||||
onError: { error in fatalError("Unexpected error: \(error)") },
|
||||
onChange: { [weak self] players in
|
||||
guard let self = self else { return }
|
||||
guard let self else { return }
|
||||
self.configureTitle(from: players)
|
||||
self.configureDataSource(from: players)
|
||||
})
|
||||
|
||||
@@ -5,7 +5,7 @@ import GRDB
|
||||
class AppDatabaseTests: XCTestCase {
|
||||
func test_database_schema() throws {
|
||||
// Given an empty database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
|
||||
// When we instantiate an AppDatabase
|
||||
_ = try AppDatabase(dbQueue)
|
||||
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_inserts() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we save a new player
|
||||
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_savePlayer_updates() throws {
|
||||
// Given a players database that contains a player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deletePlayers() throws {
|
||||
// Given a players database that contains four players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 200)
|
||||
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_deleteAllPlayers() throws {
|
||||
// Given a players database that contains players
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: nil, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: nil, name: "Barbara", score: 200)
|
||||
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_refreshPlayers_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we refresh players
|
||||
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
|
||||
// When we create random players
|
||||
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
|
||||
|
||||
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
|
||||
// Given a players database that contains one player
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
|
||||
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testInsert() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player
|
||||
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testRoundtrip() throws {
|
||||
// Given an empty players database
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
|
||||
// When we insert a player and fetch the player with the same id
|
||||
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScore() throws {
|
||||
// Given a players database that contains players with distinct scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByScoreSortsIdenticalScoresByName() throws {
|
||||
// Given a players database that contains players with common scores
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
|
||||
|
||||
func testOrderedByName() throws {
|
||||
// Given a players database that contains players with distinct names
|
||||
let dbQueue = DatabaseQueue()
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = try AppDatabase(dbQueue)
|
||||
var player1 = Player(id: 1, name: "Arthur", score: 100)
|
||||
var player2 = Player(id: 2, name: "Barbara", score: 200)
|
||||
|
||||
@@ -7,7 +7,7 @@ UIKit Demo Application
|
||||
|
||||
**Requirements**: iOS 15.0+ / Xcode 12+
|
||||
|
||||
> :point_up: **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.
|
||||
> **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:
|
||||
|
||||
|
||||
@@ -186,7 +186,7 @@ A FTS5WrapperTokenizer lets the hard tokenization job to another tokenizer, the
|
||||
|
||||
```swift
|
||||
protocol FTS5WrapperTokenizer : FTS5CustomTokenizer {
|
||||
var wrappedTokenizer: FTS5Tokenizer { get }
|
||||
var wrappedTokenizer: any FTS5Tokenizer { get }
|
||||
func accept(
|
||||
token: String,
|
||||
flags: FTS5TokenFlags,
|
||||
@@ -207,7 +207,7 @@ The `wrappedTokenizer` property is the mandatory wrapped tokenizer. You instanti
|
||||
|
||||
```swift
|
||||
final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
let wrappedTokenizer: any FTS5Tokenizer
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
// Wrap the unicode61 tokenizer
|
||||
@@ -255,7 +255,7 @@ For example, your custom tokenizer can wrap [unicode61](https://www.sqlite.org/f
|
||||
```swift
|
||||
final class MyTokenizer : FTS5WrapperTokenizer {
|
||||
static let name = "custom"
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
let wrappedTokenizer: any FTS5Tokenizer
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
if arguments.isEmpty {
|
||||
@@ -309,7 +309,7 @@ We'll also take care of the SQLite advice:
|
||||
```swift
|
||||
final class SynonymsTokenizer : FTS5WrapperTokenizer {
|
||||
static let name = "synonyms"
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
let wrappedTokenizer: any FTS5Tokenizer
|
||||
let synonyms: [Set<String>] = [["first", "1st"]]
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
@@ -361,7 +361,7 @@ The tokenizer wrapping is provided by the [FTS5WrapperTokenizer](#fts5wrappertok
|
||||
```swift
|
||||
final class LatinAsciiTokenizer : FTS5WrapperTokenizer {
|
||||
static let name = "latinascii"
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
let wrappedTokenizer: any FTS5Tokenizer
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
wrappedTokenizer = try db.makeTokenizer(.unicode61())
|
||||
@@ -375,8 +375,6 @@ final class LatinAsciiTokenizer : FTS5WrapperTokenizer {
|
||||
}
|
||||
```
|
||||
|
||||
> :point_up: **Note**: String.applyingTransform is not available before macOS 10.11. Use the Core Foundation function [CFStringTransform](https://developer.apple.com/reference/corefoundation/1542411-cfstringtransform) instead.
|
||||
|
||||
Remember to register LatinAsciiTokenizer before using it:
|
||||
|
||||
```swift
|
||||
|
||||
@@ -87,7 +87,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
|
||||
|
||||
- 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.
|
||||
|
||||
> :point_up: **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).
|
||||
> **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).
|
||||
|
||||
|
||||
## Create FTS3 and FTS4 Virtual Tables
|
||||
@@ -304,7 +304,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](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
|
||||
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -344,9 +344,9 @@ The version of SQLite that ships with iOS, macOS, tvOS and watchOS does not alwa
|
||||
end
|
||||
```
|
||||
|
||||
> :warning: **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version.
|
||||
> **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version.
|
||||
|
||||
> :point_up: **Note**: there used to be a GRDBPlus CocoaPod with pre-enabled FTS5 support. This CocoaPod is deprecated: please switch to the above technique.
|
||||
> **Note**: there used to be a GRDBPlus CocoaPod with pre-enabled FTS5 support. This CocoaPod is deprecated: please switch to the above technique.
|
||||
|
||||
2. Use the GRDB.swift/SQLCipher CocoaPod subspec (see [encryption](../README.md#encryption)):
|
||||
|
||||
@@ -587,7 +587,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](http://groue.github.io/GRDB.swift/docs/5.26/Structs/StatementArguments.html):
|
||||
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/grdb/documentation/grdb/statementarguments):
|
||||
|
||||
```swift
|
||||
let documents = try Document.fetchAll(db,
|
||||
@@ -683,7 +683,7 @@ try db.drop(table: "book_ft")
|
||||
try db.dropFTS4SynchronizationTriggers(forTable: "book_ft")
|
||||
```
|
||||
|
||||
> :warning: **Warning**: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers **twice**: once with the name of the deleted full-text table, and once with the name of the content table:
|
||||
> **Warning**: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers **twice**: once with the name of the deleted full-text table, and once with the name of the content table:
|
||||
>
|
||||
> ```swift
|
||||
> // Drop full-text table
|
||||
|
||||
@@ -0,0 +1,383 @@
|
||||
Migrating From GRDB 5 to GRDB 6
|
||||
===============================
|
||||
|
||||
**This guide aims at helping you upgrading your applications from GRDB 5 to GRDB 6.**
|
||||
|
||||
- [Preparing the Migration to GRDB 6](#preparing-the-migration-to-grdb-6)
|
||||
- [New requirements](#new-requirements)
|
||||
- [Primary Associated Types](#primary-associated-types)
|
||||
- [Record Changes](#record-changes)
|
||||
- [Other Changes](#other-changes)
|
||||
|
||||
|
||||
## Preparing the Migration to GRDB 6
|
||||
|
||||
If you haven't made it yet, upgrade to the [latest GRDB 5 release](https://github.com/groue/GRDB.swift/tags) first, and fix any deprecation warning prior to the GRDB 6 upgrade.
|
||||
|
||||
You can then upgrade to GRDB 6. Due to the breaking changes, it is possible that your application code no longer compiles. Follow the fix-its that suggest simple syntactic changes. Other modifications that you need to apply are described below.
|
||||
|
||||
## New requirements
|
||||
|
||||
GRDB requirements have been bumped:
|
||||
|
||||
- **Swift 5.7+** (was Swift 5.3+)
|
||||
- **Xcode 14.0+** (was Xcode 12.0+)
|
||||
- iOS 11.0+ (unchanged)
|
||||
- **macOS 10.13+** (was macOS 10.10+)
|
||||
- **tvOS 11.0+** (was tvOS 11.0+)
|
||||
- **watchOS 4.0+** (was watchOS 2.0+)
|
||||
- **SQLite 3.19.3+** (was SQLite 3.8.5+)
|
||||
|
||||
## Primary Associated Types
|
||||
|
||||
Request protocols now come with a primary associated type, enabled by [SE-0346](https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md). This is a great opportunity to simplify your extensions:
|
||||
|
||||
```diff
|
||||
-extension DerivableRequest where RowDecoder == Book {
|
||||
+extension DerivableRequest<Book> {
|
||||
/// Order books by title, in a localized case-insensitive fashion
|
||||
func orderByTitle() -> Self {
|
||||
order(Column("title").collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Your extensions to `QueryInterfaceRequest` can be streamlined as well, thanks to [SE-0361](https://github.com/apple/swift-evolution/blob/main/proposals/0361-bound-generic-extensions.md):
|
||||
|
||||
```diff
|
||||
-extension QueryInterfaceRequest where RowDecoder == Player {
|
||||
+extension QueryInterfaceRequest<Player> {
|
||||
func selectID() -> QueryInterfaceRequest<Int64> {
|
||||
selectPrimaryKey()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `Cursor` protocol has also gained a primary associated type (the type of its elements).
|
||||
|
||||
## Record Changes
|
||||
|
||||
The record protocols have been refactored. We tried to keep the amount of modifications to your existing code as small as possible, but some changes could not be avoided.
|
||||
|
||||
- **The `FetchableRecord.init(row:)` initializer can now throw errors.**
|
||||
|
||||
```diff
|
||||
-let player = Player(row: row)
|
||||
+let player = try Player(row: row)
|
||||
```
|
||||
|
||||
Decodable records that derive their `FetchableRecord` implementation from the standard `Decodable` protocol now throw errors when they find unexpected database values (they used to crash in GRDB 5).
|
||||
|
||||
If you subclass the `Record` type, you have to update your override of `init(row:)`:
|
||||
|
||||
```diff
|
||||
class Player: Record {
|
||||
- required init(row: Row) {
|
||||
+ required init(row: Row) throws {
|
||||
self.id = row["id"]
|
||||
self.name = row["name"]
|
||||
- super.init(row: row)
|
||||
+ try super.init(row: row)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In record types that do not derive their `FetchableRecord.init(row:)` implementation from the standard `Decodable` protocol, you are responsible for throwing decoding errors, as in the sample code below:
|
||||
|
||||
<details>
|
||||
<summary>Handling untrusted input</summary>
|
||||
|
||||
For example:
|
||||
|
||||
```swift
|
||||
struct LogEntry: FetchableRecord {
|
||||
var date: Date
|
||||
|
||||
init(row: Row) throws {
|
||||
let dbValue: DatabaseValue = row["date"]
|
||||
if dbValue.isNull {
|
||||
// Handle NULL
|
||||
throw ...
|
||||
} else if let date = Date.fromDatabaseValue(dbValue) {
|
||||
self.date = date
|
||||
} else {
|
||||
// Handle invalid date
|
||||
throw ...
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
- **The `EncodableRecord.encode(to:)` method can now throw errors.**
|
||||
|
||||
Encodable records that derive their `EncodableRecord` implementation from the standard `Encodable` protocol now throw errors when they can't be encoded into database values (they used to crash in GRDB 5).
|
||||
|
||||
If you subclass the `Record` type, you have to update your override of `encode(to:)`:
|
||||
|
||||
```diff
|
||||
class Player: Record {
|
||||
- override func encode(to container: inout PersistenceContainer) {
|
||||
+ override func encode(to container: inout PersistenceContainer) throws {
|
||||
container["id"] = id
|
||||
container["name"] = name
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This change has an impact on a few other apis, that can now throw errors as well:
|
||||
|
||||
```diff
|
||||
-let dictionary = player.databaseDictionary
|
||||
-let changes = newPlayer.databaseChanges(from: oldPlayer)
|
||||
-let changes = player.databaseChanges // Record class only
|
||||
+let dictionary = try player.databaseDictionary
|
||||
+let changes = try newPlayer.databaseChanges(from: oldPlayer)
|
||||
+let changes = try player.databaseChanges // Record class only
|
||||
```
|
||||
|
||||
- **The signature of the `didInsert` method has changed**.
|
||||
|
||||
You have to update all the `didInsert` methods in your application:
|
||||
|
||||
```diff
|
||||
struct Player: MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
|
||||
// Update auto-incremented id upon successful insertion
|
||||
- mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
- id = rowID
|
||||
+ mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
+ id = inserted.rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If you subclass the `Record` class, you have to call `super` at some point of your implementation:
|
||||
|
||||
```diff
|
||||
class Player: Record {
|
||||
var id: Int64?
|
||||
|
||||
// Update auto-incremented id upon successful insertion
|
||||
- override func didInsert(with rowID: Int64, for column: String?) {
|
||||
- id = rowID
|
||||
+ override func didInsert(_ inserted: InsertionSuccess) {
|
||||
+ super.didInsert(inserted)
|
||||
+ id = inserted.rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **PersistableRecord types now customize persistence methods with "persistence callbacks"**.
|
||||
|
||||
It is no longer possible to override persistence methods such as `insert` or `update`. Customizing the persistence methods is now possible with callbacks such as `willSave`, `willInsert`, or `didDelete` (see [persistence callbacks] for the full list of callbacks).
|
||||
|
||||
**You have to remove the methods below from your own code base**:
|
||||
|
||||
```swift
|
||||
// GRDB 6: remove those methods from your code
|
||||
func insert(_ db: Database) throws
|
||||
func didInsert(with rowID: Int64, for column: String?)
|
||||
func update(_ db: Database, columns: Set<String>) throws
|
||||
func save(_ db: Database) throws
|
||||
func delete(_ db: Database) throws -> Bool
|
||||
func exists(_ db: Database) throws -> Bool
|
||||
```
|
||||
|
||||
- `insert(_:)`: customization is now made with [persistence callbacks].
|
||||
- `didInsert(with:for:)`: this method was renamed `didInsert(_:)` (see previous bullet point).
|
||||
- `update(_:columns:)`: customization is now made with [persistence callbacks].
|
||||
- `save(_:)`: customization is now made with [persistence callbacks].
|
||||
- `delete(_:)`: customization is now made with [persistence callbacks].
|
||||
- `exists(_:)`: this method is no longer customizable.
|
||||
|
||||
To help you update your applications with persistence callbacks, let's look at two examples.
|
||||
|
||||
First, check the updated [Single-Row Tables](SingleRowTables.md) 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:
|
||||
|
||||
```swift
|
||||
// GRDB 5
|
||||
struct Link: PersistableRecord {
|
||||
var url: URL
|
||||
|
||||
func insert(_ db: Database) throws {
|
||||
try validate()
|
||||
try performInsert(db)
|
||||
}
|
||||
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
try validate()
|
||||
try performUpdate(db, columns: columns)
|
||||
}
|
||||
|
||||
func validate() throws {
|
||||
if url.host == nil {
|
||||
throw ValidationError("url must be absolute.")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
With GRDB 6, record validation can be implemented with the `willSave` callback:
|
||||
|
||||
```swift
|
||||
// GRDB 6
|
||||
struct Link: PersistableRecord {
|
||||
var url: URL
|
||||
|
||||
func willSave(_ db: Database) throws {
|
||||
if url.host == nil {
|
||||
throw ValidationError("url must be absolute.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try link.insert(db) // Calls the willSave callback
|
||||
try link.update(db) // Calls the willSave callback
|
||||
try link.save(db) // Calls the willSave callback
|
||||
try link.upsert(db) // Calls the willSave callback
|
||||
```
|
||||
|
||||
If you subclass the `Record` class, you have to call `super` at some point of your implementation:
|
||||
|
||||
```swift
|
||||
// GRDB 6
|
||||
class Link: Record {
|
||||
var url: URL
|
||||
|
||||
override func willSave(_ db: Database) throws {
|
||||
try super.willSave(db)
|
||||
if url.host == nil {
|
||||
throw ValidationError("url must be absolute.")
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **Handling of the `IGNORE` conflict policy**
|
||||
|
||||
The SQLite [IGNORE](https://www.sqlite.org/lang_conflict.html) conflict policy has SQLite skip insertions and updates that violate a schema constraint, without reporting any error. You can skip this paragraph if you do not use this policy.
|
||||
|
||||
GRDB 6 has slightly changed the handling of the `IGNORE` policy.
|
||||
|
||||
The `didInsert` callback is now always called on `INSERT OR IGNORE` insertions. In GRDB 5, `didInsert` was not called for record types that specify the `.ignore` conflict policy on inserts:
|
||||
|
||||
```swift
|
||||
// Given a record with ignore conflict policy for inserts...
|
||||
struct Player: TableRecord, FetchableRecord {
|
||||
static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .ignore)
|
||||
}
|
||||
|
||||
// GRDB 5: Does not call didInsert
|
||||
// GRDB 6: Calls didInsert
|
||||
try player.insert(db)
|
||||
```
|
||||
|
||||
Since `INSERT OR IGNORE` may silently fail, the `didInsert` method will be called with some random rowid in case of failed insert. You can detect failed insertions with the new method `insertAndFetch`:
|
||||
|
||||
```swift
|
||||
// How to detect failed `INSERT OR IGNORE`:
|
||||
// INSERT OR IGNORE INTO player ... RETURNING *
|
||||
if let insertedPlayer = try player.insertAndFetch(db) {
|
||||
// Succesful insertion
|
||||
} else {
|
||||
// Ignored failure
|
||||
}
|
||||
```
|
||||
|
||||
## Other Changes
|
||||
|
||||
- The initializer of in-memory databases can now throw errors:
|
||||
|
||||
```diff
|
||||
-let dbQueue = DatabaseQueue()
|
||||
+let dbQueue = try DatabaseQueue()
|
||||
```
|
||||
|
||||
- The `selectID()` method is removed. You can provide your own implementation, based on the new `selectPrimaryKey(as:)` method:
|
||||
|
||||
```swift
|
||||
extension QueryInterfaceRequest<Player> {
|
||||
func selectID() -> QueryInterfaceRequest<Int64> {
|
||||
selectPrimaryKey()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `Cursor.isEmpty` is now a throwing property, instead of a method:
|
||||
|
||||
```diff
|
||||
-if try cursor.isEmpty() { ... }
|
||||
+if try cursor.isEmpty { ... }
|
||||
```
|
||||
|
||||
- The `Record.copy()` method was removed, without replacement.
|
||||
|
||||
- The `DerivableRequest.limit(_:offset_:)` method was removed, without replacement.
|
||||
|
||||
You can still limit `QueryInterfaceRequest`, but associations can no longer be limited:
|
||||
|
||||
```swift
|
||||
// Still OK: a limited request of authors
|
||||
let request = Author.limit(10)
|
||||
|
||||
// Still OK: a limited request of books
|
||||
let request = author.request(for: Author.books).limit(10)
|
||||
|
||||
// No longer possible: including a limited association
|
||||
let request = Author.including(all: Author.books.limit(10))
|
||||
```
|
||||
|
||||
- `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable.
|
||||
|
||||
```swift
|
||||
let observation = DatabaseRegionObservation.tracking(Player.all())
|
||||
|
||||
// GRDB 5
|
||||
do {
|
||||
let observer = try observation.start(in: dbQueue) { db in
|
||||
print("Players were modified")
|
||||
}
|
||||
} catch {
|
||||
// handle error
|
||||
}
|
||||
|
||||
// GRDB 6
|
||||
let cancellable = observation.start(
|
||||
in: dbQueue,
|
||||
onError: { error in /* handle error */ },
|
||||
onChange: { db in
|
||||
print("Players were modified")
|
||||
})
|
||||
```
|
||||
|
||||
The `DatabaseRegionObservation.extent` property was removed. You now control the duration of the observation with the cancellable returned from the `start` method.
|
||||
|
||||
- Database cursors no longer have a `statement` property. When you want information about the database statement used by a cursor, use dedicated cursor properties. For example:
|
||||
|
||||
```diff
|
||||
-let sql = cursor.statement.sql
|
||||
-let columns = cursor.statement.columnNames
|
||||
+let sql = cursor.sql
|
||||
+let columns = cursor.columnNames
|
||||
```
|
||||
|
||||
- The transaction hook `Database.afterNextTransactionCommit(_:)` was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits.
|
||||
|
||||
```diff
|
||||
-db.afterNextTransactionCommit { db in
|
||||
+db.afterNextTransaction { db in
|
||||
print("Succesful commit")
|
||||
}
|
||||
```
|
||||
|
||||
- If your application directly embeds the `GRDB.xcodeproj` or `GRDBCustom.xcodeproj` project, then you have to update your dependencies. Those projects now define cross-platform targets, and you must perform the following actions:
|
||||
|
||||
- In the **Target Dependencies** section of the **Build Phases** tab of your **application targets**, replace the GRDB target with `GRDB` or `GRDBCustom`.
|
||||
- In the **Embedded Binaries** section of the **General** tab of your **application target**, replace the GRDB framework with `GRDB.framework` or `GRDBCustom.framework`.
|
||||
|
||||
[persistence callbacks]: ../README.md#persistence-callbacks
|
||||
@@ -109,29 +109,33 @@ struct Book: Codable, Identifiable {
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
}
|
||||
```
|
||||
|
||||
We add database powers to our types with [record protocols]. Since our records use auto-incremented ids, we provide an implementation of the `didInsert` method:
|
||||
|
||||
```swift
|
||||
// Add Database access
|
||||
|
||||
extension Author: FetchableRecord, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
extension Book: FetchableRecord, MutablePersistableRecord {
|
||||
// Update auto-incremented id upon successful insertion
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`. See [record protocols] for more information.
|
||||
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`.
|
||||
|
||||
> :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property.
|
||||
>
|
||||
> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(with:for:)` method:
|
||||
> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(_:)` method:
|
||||
>
|
||||
> ```swift
|
||||
> try dbQueue.write { db in
|
||||
@@ -234,7 +238,7 @@ Let's look at three examples:
|
||||
|
||||
> :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface.
|
||||
|
||||
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#customizing-the-persistence-methods) before they enter the database.
|
||||
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#persistence-callbacks) before they enter the database.
|
||||
|
||||
|
||||
## Singleton Records
|
||||
@@ -299,8 +303,8 @@ When you find yourself build similar requests over and over in your application,
|
||||
To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc:
|
||||
|
||||
```swift
|
||||
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
extension DerivableRequest where RowDecoder == Author {
|
||||
// Author requests
|
||||
extension DerivableRequest<Author> {
|
||||
/// Order authors by name, in a localized case-insensitive fashion
|
||||
func orderByName() -> Self {
|
||||
let name = Author.Columns.name
|
||||
@@ -342,8 +346,8 @@ try dbQueue.read { db in
|
||||
Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors:
|
||||
|
||||
```swift
|
||||
// Book requests ~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
extension DerivableRequest where RowDecoder == Book {
|
||||
// Book requests
|
||||
extension DerivableRequest<Book> {
|
||||
/// Filters books by kind
|
||||
func filter(kind: Book.Kind) -> Self {
|
||||
filter(Book.Columns.kind == kind)
|
||||
@@ -368,16 +372,16 @@ try dbQueue.read { db in
|
||||
Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example:
|
||||
|
||||
```swift
|
||||
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
extension QueryInterfaceRequest where RowDecoder == Author {
|
||||
// Author requests
|
||||
extension QueryInterfaceRequest<Author> {
|
||||
// Selects author ids
|
||||
func id() -> QueryInterfaceRequest<Int64> {
|
||||
select(Author.Columns.id)
|
||||
func selectId() -> QueryInterfaceRequest<Int64> {
|
||||
selectPrimaryKey(as: Int64.self)
|
||||
}
|
||||
}
|
||||
|
||||
// IDs of French authors
|
||||
let ids: [Int64] = try Author.all().filter(country: "France").id().fetchAll(db)
|
||||
let ids: [Int64] = try Author.all().filter(country: "France").selectId().fetchAll(db)
|
||||
```
|
||||
|
||||
## Compose Records
|
||||
@@ -424,7 +428,7 @@ As in the sample code above, requests which feed from several associated records
|
||||
|
||||
Unlike the primitive persistable record types `Author` and `Book`, those records can not write in the database. They are simple data types, passive views on the database content. Remember, only [Persistable Record Types are Responsible for Their Tables].
|
||||
|
||||
> :question: **Note**: The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
|
||||
> **Note**: The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
|
||||
>
|
||||
> That is because other ORMs perform lazy loading:
|
||||
>
|
||||
@@ -747,7 +751,7 @@ When a new screen is added to your application, and you want to make sure it dis
|
||||
|
||||
In other words: since GRDB is an unmanaged ORM, some amount of management must be imported into your application in order to make it fully thread-safe.
|
||||
|
||||
> :question: **Note**: Wrapping several fetches in a single `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
|
||||
> **Note**: Wrapping several fetches in a single `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
|
||||
>
|
||||
> ```ruby
|
||||
> # Ruby's Active Record
|
||||
|
||||
@@ -77,7 +77,7 @@ try dbQueue.read { db in
|
||||
}
|
||||
```
|
||||
|
||||
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.26/Structs/DatabaseMigrator.html) for more migrator methods.
|
||||
See the [DatabaseMigrator reference](https://swiftpackageindex.com/groue/grdb/documentation/grdb/databasemigrator) for more migrator methods.
|
||||
|
||||
|
||||
## The `eraseDatabaseOnSchemaChange` Option
|
||||
@@ -89,7 +89,7 @@ var migrator = DatabaseMigrator()
|
||||
migrator.eraseDatabaseOnSchemaChange = true
|
||||
```
|
||||
|
||||
> :warning: **Warning**: This option can destroy your precious users' data!
|
||||
> **Warning**: This option can destroy your precious users' data!
|
||||
|
||||
Setting `eraseDatabaseOnSchemaChange` is useful during application development, as you are still designing migrations, and the schema changes often.
|
||||
|
||||
@@ -153,9 +153,9 @@ The detailed sequence of operations is described below, some of them are perform
|
||||
|
||||
12. GRDB: If foreign keys constraints were originally enabled, reenable them now.
|
||||
|
||||
> :point_up: **Note**: Take care to follow the procedure above precisely, in the same order, or you might corrupt triggers, views, and foreign key constraints. Have a second look at [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes) if necessary.
|
||||
> **Note**: Take care to follow the procedure above precisely, in the same order, or you might corrupt triggers, views, and foreign key constraints. Have a second look at [Making Other Kinds Of Table Schema Changes](https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes) if necessary.
|
||||
>
|
||||
> :point_up: **Note**: By default, all migrations perform, at step 10, a full check of all foreign keys in your database. When your database is big, those checks may have a noticeable impact on migration performances. See [Foreign Key Checks] for a discussion of your ways to avoid this toll.
|
||||
> **Note**: By default, all migrations perform, at step 10, a full check of all foreign keys in your database. When your database is big, those checks may have a noticeable impact on migration performances. See [Foreign Key Checks] for a discussion of your ways to avoid this toll.
|
||||
|
||||
|
||||
## Foreign Key Checks
|
||||
@@ -274,9 +274,12 @@ The `asyncMigrate(_:completion:)` method:
|
||||
|
||||
```swift
|
||||
// Completes in a protected dispatch queue that can write in the database
|
||||
migrator.asyncMigrate(dbQueue, completion: { db, error in
|
||||
if let error = error {
|
||||
migrator.asyncMigrate(dbQueue, completion: { result in
|
||||
switch result {
|
||||
case .failure:
|
||||
// Some error occurred during migrations
|
||||
case let .success(db):
|
||||
// Migrations succeeded
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
|
||||
//: - Select the GRDB scheme: menu Product > Scheme > GRDB
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
@@ -14,7 +14,7 @@ var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { print("SQL> \($0)") }
|
||||
}
|
||||
let dbQueue = DatabaseQueue(configuration: configuration)
|
||||
let dbQueue = try DatabaseQueue(configuration: configuration)
|
||||
|
||||
//: Use a migrator to define the database schema
|
||||
|
||||
@@ -44,8 +44,8 @@ struct Author: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,8 +54,8 @@ struct Book: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var authorId: Int64
|
||||
var title: String
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,469 +0,0 @@
|
||||
//: # Customized Decoding of Database Rows
|
||||
//:
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
|
||||
import GRDB
|
||||
|
||||
//: This playground demonstrates how one can implement **customized decoding of
|
||||
//: database rows**.
|
||||
//:
|
||||
//: Customized row decoding allows you to go beyond the built-in support for
|
||||
//: requests of raw rows, values, or types that adopt the
|
||||
//: FetchableRecord protocol.
|
||||
//:
|
||||
//: For example:
|
||||
//:
|
||||
//: - Your application needs polymorphic row decoding: it decodes some class or
|
||||
//: another, depending on the values contained in a database row.
|
||||
//:
|
||||
//: - Your application needs to decode rows with a context: each decoded value
|
||||
//: should be initialized with some extra value that does not come from
|
||||
//: the database.
|
||||
//:
|
||||
//: - Your application needs a record type that supports untrusted databases,
|
||||
//: and may fail at decoding database rows (throw an error when a row contains
|
||||
//: invalid values).
|
||||
//:
|
||||
//: None of those use cases can be handled by the built-in `FetchableRecord`
|
||||
//: protocol and its `init(row:)` initializer. They need *customized
|
||||
//: row decoding*.
|
||||
//:
|
||||
//: ## An Example: Polymorphic Decoding
|
||||
//:
|
||||
//: In this playground, we will provide some sample code that performs
|
||||
//: polymorphic row decoding. Given a base class, `Base`, and two subclasses
|
||||
//: `Foo` and `Bar`, we'd like to fetch Foo or Bar instances, depending on the
|
||||
//: value found in the `type` column of the `base` database table.
|
||||
//:
|
||||
//: From this sample code, we hope that you will be able to derive your own
|
||||
//: customized decoding.
|
||||
//:
|
||||
//: Everything starts from our class hierarchy:
|
||||
|
||||
class Base {
|
||||
var description: String { "Base" }
|
||||
init() { }
|
||||
}
|
||||
|
||||
class Foo: Base {
|
||||
var name: String
|
||||
override var description: String { "Foo: \(name)" }
|
||||
init(name: String) {
|
||||
self.name = name
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
class Bar: Base {
|
||||
var score: Int
|
||||
override var description: String { "Bar: \(score)" }
|
||||
init(score: Int) {
|
||||
self.score = score
|
||||
super.init()
|
||||
}
|
||||
}
|
||||
|
||||
//: We need a database, a table, and a few values so that we can do a real demo:
|
||||
|
||||
// An in-memory database is good enough
|
||||
let dbQueue = DatabaseQueue()
|
||||
|
||||
try dbQueue.write { db in
|
||||
// Database table
|
||||
try db.create(table: "base") { t in
|
||||
t.column("type", .text).notNull() // Contains "Foo" or "Bar"
|
||||
t.column("fooName", .text) // Contains a Foo's name
|
||||
t.column("barScore", .integer) // Contains a Bar's score
|
||||
}
|
||||
|
||||
// Demo values: two Foo and one Bar
|
||||
try db.execute(
|
||||
sql: """
|
||||
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
|
||||
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
|
||||
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
|
||||
""",
|
||||
arguments: [
|
||||
"Foo", "Arthur", nil,
|
||||
"Bar", nil, 100,
|
||||
"Foo", "Barbara", nil,
|
||||
])
|
||||
}
|
||||
|
||||
//: We also need a method that decodes database rows into `Foo` or `Bar`
|
||||
//: instances: let's call it `Base.decode(row:)`:
|
||||
|
||||
extension Base {
|
||||
static func decode(row: Row) -> Base {
|
||||
switch row["type"] as String {
|
||||
case "Foo":
|
||||
return Foo(name: row["fooName"])
|
||||
case "Bar":
|
||||
return Bar(score: row["barScore"])
|
||||
case let type:
|
||||
fatalError("Unknown Base type: \(type)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//: Now we are able to express the kind of request we'd like to write. For
|
||||
//: example, we could fetch all Base values from the database:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: // An array [Base] that contains Foo and Bar instances
|
||||
//: let bases = try Base.fetchAll(db)
|
||||
//: }
|
||||
//:
|
||||
//: But so far, we have a compiler error:
|
||||
|
||||
// Compiler error: Type 'Base' has no member 'fetchAll'
|
||||
//try dbQueue.read { db in
|
||||
// let bases = try Base.fetchAll(db)
|
||||
//}
|
||||
|
||||
//: We'll see that this goal can be achieved by declaring a protocol, writing a
|
||||
//: few extensions that guarantee the most efficient use of GRDB, and have the
|
||||
//: Base class adopt this protocol.
|
||||
//:
|
||||
//: ### Keep It Simple, Stupid!
|
||||
//:
|
||||
//: But first, let's see how polymorphic decoding can be done as simply as
|
||||
//: possible. After all, it is useless to design a full-fledged protocol unless
|
||||
//: we need to use this protocol several times, or write code that is as
|
||||
//: streamlined as possible.
|
||||
//:
|
||||
//: Can we fetch Foo and Bar values from an SQL request? Sure:
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> KISS: Fetch from SQL")
|
||||
let rows = try Row.fetchAll(db, sql: "SELECT * FROM base") // Fetch database rows
|
||||
let bases = rows.map { row in // Decode database rows
|
||||
Base.decode(row: row)
|
||||
}
|
||||
for base in bases { // Use fetched values
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: Can we have GRDB generate SQL for us? Sure, we just need to adopt the
|
||||
//: `TableRecord` protocol:
|
||||
|
||||
extension Base: TableRecord {
|
||||
static let databaseTableName = "base"
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> KISS: Fetch from query interface request")
|
||||
let request = Base.filter(Column("type") == "Foo") // Define a request
|
||||
let rows = try Row.fetchAll(db, request) // Fetch database rows
|
||||
let bases = rows.map { row in // Decode database rows
|
||||
Base.decode(row: row)
|
||||
}
|
||||
for base in bases { // Use fetched values
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: As seen above, we can perform polymorphic requests with the standard GRDB,
|
||||
//: by fetching raw rows and mapping them through a decoding method.
|
||||
//:
|
||||
//: The resulting code is not as streamlined as usual GRDB code, but we could
|
||||
//: already do what we needed without much effort.
|
||||
//:
|
||||
//: ### Custom Protocol: MyDatabaseDecoder
|
||||
//:
|
||||
//: In the rest of this playground, we will define a **new realm of requests**.
|
||||
//:
|
||||
//: GRDB ships with three built-in realms of requests: requests of raw rows,
|
||||
//: requests of values, and requests of record types that adopt the
|
||||
//: `FetchableRecord` protocol.
|
||||
//:
|
||||
//: We'll define requests of record types that adopt the custom
|
||||
//: `MyDatabaseDecoder` protocol:
|
||||
|
||||
protocol MyDatabaseDecoder {
|
||||
associatedtype DecodedType
|
||||
static func decode(row: Row) -> DecodedType
|
||||
}
|
||||
|
||||
//: Types that adopt the MyDatabaseDecoder protocol are able, among other
|
||||
//: things, to perform polymorphic decoding. Our Base class, for example:
|
||||
|
||||
extension Base: MyDatabaseDecoder {
|
||||
// Already declared above:
|
||||
// static func decode(row: Row) -> Base { ... }
|
||||
}
|
||||
|
||||
//: Now let's see how we can define a new realm of requests based on the
|
||||
//: `MyDatabaseDecoder` protocol. Our goal is to make them just as powerful as
|
||||
//: ready-made requests of rows, values and FetchableRecord.
|
||||
//:
|
||||
//: All we need is a set of *extensions* that define the classic GRDB fetching
|
||||
//: methods: `fetchOne`, `fetchAll`, and `fetchCursor`. The most fundamental one
|
||||
//: is `fetchCursor`, because from it we can derive the two others.
|
||||
//:
|
||||
//: The first extension is the most low-level one: fetching from SQLite
|
||||
//: **prepared statement**:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: let statement = try db.makeStatement(sql: "SELECT ...")
|
||||
//: try Base.fetchCursor(statement) // Cursor of Base
|
||||
//: try Base.fetchAll(statement) // [Base]
|
||||
//: try Base.fetchOne(statement) // Base?
|
||||
//: }
|
||||
|
||||
extension MyDatabaseDecoder {
|
||||
// MARK: - Fetch from Prepared Statement
|
||||
|
||||
// Statement, StatementArguments, and RowAdapter are the fundamental
|
||||
// fetching parameters of GRDB. Make sure to accept them all:
|
||||
static func fetchCursor(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
// Turn the cursor of raw rows into a cursor of decoded rows
|
||||
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
|
||||
self.decode(row: $0)
|
||||
}
|
||||
}
|
||||
|
||||
static func fetchAll(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
|
||||
// Turn the cursor into an Array
|
||||
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
static func fetchOne(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
|
||||
// Consume the first value of the cursor
|
||||
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next()
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch from prepared statement")
|
||||
let statement = try db.makeStatement(sql: "SELECT * FROM base")
|
||||
let bases = try Base.fetchAll(statement)
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: Now that we can fetch from prepared statements, we can fetch when given a
|
||||
//: **request**, as defined by the `FetchRequest` protocol. This is the
|
||||
//: protocol for query interface requests such as `Base.all()`, or
|
||||
//: `SQLRequest`, etc.
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: let request = Base.all()
|
||||
//: try Base.fetchCursor(db, request) // Cursor of Base
|
||||
//: try Base.fetchAll(db, request) // [Base]
|
||||
//: try Base.fetchOne(db, request) // Base?
|
||||
//: }
|
||||
extension MyDatabaseDecoder {
|
||||
// MARK: - Fetch from FetchRequest
|
||||
|
||||
static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchCursor(preparedRequest.statement, adapter: preparedRequest.adapter)
|
||||
}
|
||||
|
||||
static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [DecodedType] {
|
||||
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(preparedRequest.statement, adapter: preparedRequest.adapter)
|
||||
}
|
||||
|
||||
static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> DecodedType? {
|
||||
// The `forSingleResult: true` argument hints the request that a single
|
||||
// row will be consumed. Some requests will add a LIMIT SQL clause.
|
||||
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: true)
|
||||
return try fetchOne(preparedRequest.statement, adapter: preparedRequest.adapter)
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch given a request")
|
||||
let request = Base.all()
|
||||
let bases = try Base.fetchAll(db, request)
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: When it's fine to fetch given a request, it's even better when requests can
|
||||
//: fetch, too:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: let request = Base.all()
|
||||
//: try request.fetchCursor(db) // Cursor of Base
|
||||
//: try request.fetchAll(db) // [Base]
|
||||
//: try request.fetchOne(db) // Base?
|
||||
//: }
|
||||
extension FetchRequest where RowDecoder: MyDatabaseDecoder {
|
||||
// MARK: - FetchRequest fetching methods
|
||||
|
||||
func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, RowDecoder.DecodedType> {
|
||||
try RowDecoder.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
func fetchAll(_ db: Database) throws -> [RowDecoder.DecodedType] {
|
||||
try RowDecoder.fetchAll(db, self)
|
||||
}
|
||||
|
||||
func fetchOne(_ db: Database) throws -> RowDecoder.DecodedType? {
|
||||
try RowDecoder.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch from request")
|
||||
let request = Base.all()
|
||||
let bases = try request.fetchAll(db)
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: Types that adopt both FetchableRecord and TableRecord are able to fetch
|
||||
//: right from the base type. Let's allow this as well for MyDatabaseDecoder:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: try Base.fetchCursor(db) // Cursor of Base
|
||||
//: try Base.fetchAll(db) // [Base]
|
||||
//: try Base.fetchOne(db) // Base?
|
||||
//: }
|
||||
extension MyDatabaseDecoder where Self: TableRecord {
|
||||
// MARK: - Static fetching methods
|
||||
|
||||
static func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
try all().fetchCursor(db)
|
||||
}
|
||||
|
||||
static func fetchAll(_ db: Database) throws -> [DecodedType] {
|
||||
try all().fetchAll(db)
|
||||
}
|
||||
|
||||
static func fetchOne(_ db: Database) throws -> DecodedType? {
|
||||
try all().fetchOne(db)
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch from base type")
|
||||
let bases = try Base.fetchAll(db)
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: Finally, you can support raw SQL as well:
|
||||
//:
|
||||
//: try dbQueue.read { db in
|
||||
//: try Base.fetchAll(db,
|
||||
//: sql: "SELECT ... WHERE name = ?",
|
||||
//: arguments: ["O'Brien"]) // [Base]
|
||||
//: }
|
||||
extension MyDatabaseDecoder {
|
||||
// MARK: - Fetch from SQL
|
||||
|
||||
static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
|
||||
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [DecodedType] {
|
||||
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DecodedType? {
|
||||
try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
try dbQueue.read { db in
|
||||
print("> Fetch from SQL")
|
||||
let bases = try Base.fetchAll(db, sql: "SELECT * FROM base")
|
||||
for base in bases {
|
||||
print(base.description)
|
||||
}
|
||||
}
|
||||
|
||||
//: Voilà! Our `MyDatabaseDecoder` protocol is now as able as the built-in
|
||||
//: `FetchableRecord` protocol.
|
||||
//:
|
||||
//: To sum up, you have learned:
|
||||
//:
|
||||
//: - how to keep things simple: as long as you can fetch rows, you can decode
|
||||
//: them the way you want.
|
||||
//: - how to define a whole new realm of requests based on a custom protocol.
|
||||
//: This involves writing a few extensions that give your protocol the same
|
||||
//: fluent interface that is ready-made for the built-in FetchableRecord
|
||||
//: protocol. This is more work, but you are granted with the full
|
||||
//: customization freedom.
|
||||
//:
|
||||
//: To end this tour, let's quickly look at two other possible customized
|
||||
//: row decoding strategies.
|
||||
//:
|
||||
//: ## An Example: Contextualized Records
|
||||
//:
|
||||
//: Your application needs to decode rows with a context: each decoded value
|
||||
//: should be initialized with some extra value that does not come from
|
||||
//: the database.
|
||||
//:
|
||||
//: In this case, you may define a `ContextFetchableRecord` protocol, and
|
||||
//: derive all other fetching methods from the most fundamental one, which
|
||||
//: fetches a cursor from a prepared statement (as we did for the
|
||||
//: MyDatabaseDecoder protocol, above):
|
||||
|
||||
protocol ContextFetchableRecord {
|
||||
associatedtype Context
|
||||
init(row: Row, context: Context)
|
||||
}
|
||||
|
||||
extension ContextFetchableRecord {
|
||||
static func fetchCursor(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil,
|
||||
context: Context)
|
||||
throws -> MapCursor<RowCursor, Self>
|
||||
{
|
||||
// Turn the cursor of raw rows into a cursor of decoded rows
|
||||
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
|
||||
self.init(row: $0, context: context)
|
||||
}
|
||||
}
|
||||
|
||||
// Define fetchAll, fetchOne, and other extensions...
|
||||
}
|
||||
|
||||
//: ## An Example: Failable Records
|
||||
//:
|
||||
//: Your application needs a record type that supports untrusted databases,
|
||||
//: and may fail at decoding database rows (throw an error when a row contains
|
||||
//: invalid values).
|
||||
//:
|
||||
//: In this case, you may define a `FailableFetchableRecord` protocol, and
|
||||
//: derive all other fetching methods from the most fundamental one, which
|
||||
//: fetches a cursor from a prepared statement (as we did for the
|
||||
//: MyDatabaseDecoder protocol, above):
|
||||
|
||||
protocol FailableFetchableRecord {
|
||||
init(row: Row) throws
|
||||
}
|
||||
|
||||
extension FailableFetchableRecord {
|
||||
static func fetchCursor(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> MapCursor<RowCursor, Self>
|
||||
{
|
||||
// Turn the cursor of raw rows into a cursor of decoded rows
|
||||
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
|
||||
try self.init(row: $0)
|
||||
}
|
||||
}
|
||||
|
||||
// Define fetchAll, fetchOne, and other extensions...
|
||||
}
|
||||
-4
@@ -1,4 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<playground version='5.0' target-platform='macos' display-mode='rendered' buildActiveScheme='true'>
|
||||
<timeline fileName='timeline.xctimeline'/>
|
||||
</playground>
|
||||
@@ -1,4 +1,4 @@
|
||||
// To run this playground, select and build the GRDBOSX scheme.
|
||||
// To run this playground, select and build the GRDB scheme.
|
||||
|
||||
import GRDB
|
||||
|
||||
@@ -6,15 +6,15 @@ var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { print("SQL> \($0)") }
|
||||
}
|
||||
let dbQueue = DatabaseQueue(configuration: configuration)
|
||||
let dbQueue = try DatabaseQueue(configuration: configuration)
|
||||
|
||||
struct Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
var id: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
|
||||
//: - Select the GRDB scheme: menu Product > Scheme > GRDB
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
@@ -22,7 +22,7 @@ var configuration = Configuration()
|
||||
configuration.prepareDatabase { db in
|
||||
db.trace { print("SQL> \($0)") }
|
||||
}
|
||||
let dbQueue = DatabaseQueue(configuration: configuration)
|
||||
let dbQueue = try DatabaseQueue(configuration: configuration)
|
||||
|
||||
|
||||
//: Execute SQL queries
|
||||
@@ -92,7 +92,7 @@ extension Place : TableRecord {
|
||||
|
||||
// Adopt MutablePersistableRecord
|
||||
extension Place : MutablePersistableRecord {
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
func encode(to container: inout PersistenceContainer) throws {
|
||||
container["id"] = id
|
||||
container["title"] = title
|
||||
container["favorite"] = favorite
|
||||
@@ -100,8 +100,8 @@ extension Place : MutablePersistableRecord {
|
||||
container["longitude"] = coordinate.longitude
|
||||
}
|
||||
|
||||
mutating func didInsert(with rowID: Int64, for column: String?) {
|
||||
id = rowID
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
id = inserted.rowID
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//: To run this playground:
|
||||
//:
|
||||
//: - Open GRDB.xcworkspace
|
||||
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
|
||||
//: - Select the GRDB scheme: menu Product > Scheme > GRDB
|
||||
//: - Build: menu Product > Build
|
||||
//: - Select the playground in the Playgrounds Group
|
||||
//: - Run the playground
|
||||
@@ -11,7 +11,7 @@ import GRDB
|
||||
|
||||
// Create the database
|
||||
|
||||
let dbQueue = DatabaseQueue() // Memory database
|
||||
let dbQueue = try DatabaseQueue() // Memory database
|
||||
var migrator = DatabaseMigrator()
|
||||
migrator.registerMigration("createPerson") { db in
|
||||
try db.create(table: "person") { t in
|
||||
|
||||
@@ -179,9 +179,9 @@ protocol DatabaseValueConvertible: SQLExpressible {
|
||||
`DerivableRequest` is the protocol for query interface requests and associations that can be refined. It is adopted by [QueryInterfaceRequest] and [Association].
|
||||
|
||||
```swift
|
||||
protocol DerivableRequest: AggregatingRequest, FilteredRequest,
|
||||
JoinableRequest, OrderedRequest,
|
||||
SelectionRequest, TableRequest
|
||||
protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredRequest,
|
||||
JoinableRequest, OrderedRequest,
|
||||
SelectionRequest, TableRequest
|
||||
{
|
||||
func distinct() -> Self
|
||||
func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self
|
||||
@@ -202,7 +202,7 @@ DerivableRequest makes it possible to build reusable code snippets that apply to
|
||||
`FetchRequest` is the protocol for requests that can fetch. It is adopted by [QueryInterfaceRequest] and [SQLRequest]. It conforms to [SQLSubqueryable] and [DatabaseRegionConvertible].
|
||||
|
||||
```swift
|
||||
protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
|
||||
@@ -13,18 +13,14 @@ To release a new GRDB version:
|
||||
- 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
|
||||
- Update GRDB version number and release date in:
|
||||
- Makefile
|
||||
- CHANGELOG.md
|
||||
- GRDB.swift.podspec
|
||||
- README.md
|
||||
- Documentation/FullTextSearch.md
|
||||
- Documentation/Migrations.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
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- `make doc`, and update index.html in the `gh-pages` branch
|
||||
- Update http://github.com/groue/WWDCCompanion
|
||||
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
|
||||
|
||||
|
||||
@@ -389,7 +389,7 @@ This chapter lists all kinds of supported interpolations.
|
||||
|
||||
struct AltPlayer: TableRecord {
|
||||
static let databaseTableName = "player"
|
||||
static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")]
|
||||
static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")]
|
||||
}
|
||||
|
||||
// SELECT player.id, player.name FROM player
|
||||
|
||||
@@ -116,16 +116,14 @@ We make our record able to access the database:
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
```
|
||||
|
||||
We have seen in the [The Single-Row Table] chapter that by default, updates throw an error if the database table is empty. To avoid this error, we instruct GRDB to perform an insert in case of a failed update (see [Persistence Methods] for more information):
|
||||
We have seen in the [The Single-Row Table] chapter that by default, updates throw an error if the database table is empty. To avoid this error, we instruct GRDB to insert the missing default configuration before attempting to update (see [Persistence Callbacks] for more information about the `willSave` method):
|
||||
|
||||
```swift
|
||||
// Customize the default PersistableRecord behavior
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
do {
|
||||
try performUpdate(db, columns: columns)
|
||||
} catch PersistenceError.recordNotFound {
|
||||
// No row was updated: perform an insert
|
||||
try performInsert(db)
|
||||
func willUpdate(_ db: Database, columns: Set<String>) throws {
|
||||
// Insert the default configuration if it does not exist yet.
|
||||
if try !exists(db) {
|
||||
try AppConfiguration.default.insert(db)
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -165,12 +163,13 @@ try dbQueue.write { db in
|
||||
try config.update(db)
|
||||
try config.save(db)
|
||||
try config.insert(db)
|
||||
try config.upsert(db)
|
||||
}
|
||||
```
|
||||
|
||||
The three `update`, `save` and `insert` methods can be used interchangeably: all three make sure the configuration is stored in the database.
|
||||
The four `update`, `save`, `insert` and `upsert` methods can be used interchangeably. They all make sure the configuration is stored in the database.
|
||||
|
||||
The `updateChanges` method only updates the values changed by its closure argument (and performs an insert if the database table is empty).
|
||||
The `updateChanges` method only updates the values changed by its closure argument (and performs an initial insert of default configuration if the database table is empty).
|
||||
|
||||
See [Persistence Methods] for more information.
|
||||
|
||||
@@ -215,12 +214,10 @@ extension AppConfiguration {
|
||||
// Database Access
|
||||
extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
// Customize the default PersistableRecord behavior
|
||||
func update(_ db: Database, columns: Set<String>) throws {
|
||||
do {
|
||||
try performUpdate(db, columns: columns)
|
||||
} catch PersistenceError.recordNotFound {
|
||||
// No row was updated: perform an insert
|
||||
try performInsert(db)
|
||||
func willUpdate(_ db: Database, columns: Set<String>) throws {
|
||||
// Insert the default configuration if it does not exist yet.
|
||||
if try !exists(db) {
|
||||
try AppConfiguration.default.insert(db)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -239,4 +236,5 @@ extension AppConfiguration: FetchableRecord, PersistableRecord {
|
||||
[The Single-Row Record]: #the-single-row-record
|
||||
[Wrap-Up]: #wrap-up
|
||||
[DRY]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
|
||||
[Persistence Callbacks]: ../README.md#persistence-callbacks
|
||||
[Persistence Methods]: ../README.md#persistence-methods
|
||||
+6
-6
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.26.0'
|
||||
s.version = '6.3.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.3', '5.4', '5.5']
|
||||
s.swift_versions = ['5.7']
|
||||
s.ios.deployment_target = '11.0'
|
||||
s.osx.deployment_target = '10.10'
|
||||
s.watchos.deployment_target = '2.0'
|
||||
s.tvos.deployment_target = '9.0'
|
||||
s.osx.deployment_target = '10.13'
|
||||
s.watchos.deployment_target = '4.0'
|
||||
s.tvos.deployment_target = '11.0'
|
||||
s.default_subspec = 'standard'
|
||||
|
||||
s.subspec 'standard' do |ss|
|
||||
@@ -25,7 +25,7 @@ Pod::Spec.new do |s|
|
||||
s.subspec 'SQLCipher' do |ss|
|
||||
ss.source_files = 'GRDB/**/*.swift', 'Support/SQLCipher_config.h'
|
||||
ss.framework = 'Foundation'
|
||||
ss.dependency 'SQLCipher', '>= 3.4.0'
|
||||
ss.dependency 'SQLCipher', '>= 3.4.2'
|
||||
ss.xcconfig = {
|
||||
'OTHER_SWIFT_FLAGS' => '$(inherited) -D SQLITE_HAS_CODEC -D GRDBCIPHER -D SQLITE_ENABLE_FTS5',
|
||||
'OTHER_CFLAGS' => '$(inherited) -DSQLITE_HAS_CODEC -DGRDBCIPHER -DSQLITE_ENABLE_FTS5',
|
||||
|
||||
+96
-2562
File diff suppressed because it is too large.
Load diff
+10
-9
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -16,7 +16,7 @@
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "DC3773F219C8CBB3004FCF85"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBOSX"
|
||||
BlueprintName = "GRDB"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
@@ -29,8 +29,8 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7F81B4D422D00430942"
|
||||
BuildableName = "GRDBOSXTests.xctest"
|
||||
BlueprintName = "GRDBOSXTests"
|
||||
BuildableName = "GRDBTests.xctest"
|
||||
BlueprintName = "GRDBTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
@@ -44,12 +44,13 @@
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
skipped = "NO"
|
||||
parallelizable = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7F81B4D422D00430942"
|
||||
BuildableName = "GRDBOSXTests.xctest"
|
||||
BlueprintName = "GRDBOSXTests"
|
||||
BuildableName = "GRDBTests.xctest"
|
||||
BlueprintName = "GRDBTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
@@ -70,7 +71,7 @@
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "DC3773F219C8CBB3004FCF85"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBOSX"
|
||||
BlueprintName = "GRDB"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
@@ -86,7 +87,7 @@
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "DC3773F219C8CBB3004FCF85"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBOSX"
|
||||
BlueprintName = "GRDB"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
@@ -1,76 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5654909F1D5A4798005622CB"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBWatchOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5654909F1D5A4798005622CB"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBWatchOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "5654909F1D5A4798005622CB"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBWatchOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,87 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7C91B4D3FED00430942"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7D21B4D3FEE00430942"
|
||||
BuildableName = "GRDBiOSTests.xctest"
|
||||
BlueprintName = "GRDBiOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7C91B4D3FED00430942"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "56E5D7C91B4D3FED00430942"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBiOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
@@ -1,87 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
codeCoverageEnabled = "YES">
|
||||
<Testables>
|
||||
<TestableReference
|
||||
skipped = "NO">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DD07230F262000C74B15"
|
||||
BuildableName = "GRDBtvOSTests.xctest"
|
||||
BlueprintName = "GRDBtvOSTests"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</TestableReference>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<MacroExpansion>
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "AAA4DC75230F1E0600C74B15"
|
||||
BuildableName = "GRDB.framework"
|
||||
BlueprintName = "GRDBtvOS"
|
||||
ReferencedContainer = "container:GRDB.xcodeproj">
|
||||
</BuildableReference>
|
||||
</MacroExpansion>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
-3
@@ -10,9 +10,6 @@
|
||||
<FileRef
|
||||
location = "group:TransactionObserver.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:CustomizedDecodingOfDatabaseRows.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Associations.playground">
|
||||
</FileRef>
|
||||
|
||||
+183
-134
@@ -1,37 +1,54 @@
|
||||
import Dispatch
|
||||
import Foundation
|
||||
|
||||
/// Configuration for a DatabaseQueue or DatabasePool.
|
||||
/// The configuration of a ``Database``, ``DatabaseQueue``, or ``DatabasePool``.
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.readonly = true
|
||||
/// config.foreignKeysEnabled = true // Default is already true
|
||||
/// config.label = "MyDatabase" // Useful when your app opens multiple databases
|
||||
/// config.maximumReaderCount = 10 // (DatabasePool only) The default is 5
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue( // or DatabasePool
|
||||
/// path: "/path/to/database.sqlite",
|
||||
/// configuration: config)
|
||||
/// ```
|
||||
public struct Configuration {
|
||||
|
||||
// MARK: - Misc options
|
||||
|
||||
/// If true (the default), support for foreign keys is enabled.
|
||||
/// See <https://www.sqlite.org/foreignkeys.html> for more information.
|
||||
/// A boolean value indicating whether foreign key support is enabled.
|
||||
///
|
||||
/// Default: true
|
||||
/// The default is true.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/foreignkeys.html>.
|
||||
public var foreignKeysEnabled = true
|
||||
|
||||
/// If true, database modifications are disallowed.
|
||||
/// A boolean value indicating whether an SQLite connection is read-only.
|
||||
///
|
||||
/// Default: false
|
||||
/// The default is false.
|
||||
public var readonly = false
|
||||
|
||||
/// The configuration label.
|
||||
/// A label that describes a database connection.
|
||||
///
|
||||
/// You can query this label at runtime:
|
||||
///
|
||||
/// var configuration = Configuration()
|
||||
/// configuration.label = "MyDatabase"
|
||||
/// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
|
||||
/// ```swift
|
||||
/// var configuration = Configuration()
|
||||
/// configuration.label = "MyDatabase"
|
||||
/// let dbQueue = try DatabaseQueue(path: ..., configuration: configuration)
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// print(db.configuration.label) // Prints "MyDatabase"
|
||||
/// }
|
||||
/// try dbQueue.read { db in
|
||||
/// print(db.configuration.label) // Prints "MyDatabase"
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The configuration label is also used to name Database connections (the
|
||||
/// `Database.description` property), and the various dispatch queues
|
||||
/// created by GRDB, visible in debugging sessions and crash logs.
|
||||
/// The configuration label is also used to name ``Database`` connections
|
||||
/// (their ``Database/description`` property), and the various dispatch
|
||||
/// queues created by GRDB, visible in debugging sessions and crash logs.
|
||||
///
|
||||
/// Those connection names and dispatch queue labels are intended for
|
||||
/// debugging only. Their format may change between GRDB releases.
|
||||
@@ -66,62 +83,73 @@ public struct Configuration {
|
||||
/// The default configuration label is nil.
|
||||
public var label: String? = nil
|
||||
|
||||
/// If false, SQLite from version 3.29.0 will not interpret a double-quoted
|
||||
/// string as a string literal if it does not match any valid identifier.
|
||||
/// A boolean value indicating whether SQLite 3.29+ interprets
|
||||
/// double-quoted strings as string literals when they does not match any
|
||||
/// valid identifier.
|
||||
///
|
||||
/// The default and recommended value is false.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // Error: no such column: foo
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // Error: no such column: foo
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// When true, or before version 3.29.0, such strings are interpreted as
|
||||
/// string literals, as in the example below. This is a well known SQLite
|
||||
/// [misfeature](https://sqlite.org/quirks.html#dblquote).
|
||||
/// When true, or before SQLite version 3.29.0, such strings are interpreted
|
||||
/// as string literals, as in the example below. This is a well known SQLite
|
||||
/// [misfeature](https://sqlite.org/quirks.html#dblquote):
|
||||
///
|
||||
/// // Success: "foo"
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// """)
|
||||
///
|
||||
/// - Recommended value: false
|
||||
/// - Default value: false
|
||||
/// ```swift
|
||||
/// // Success: "foo"
|
||||
/// let name = try String.fetchOne(db, sql: """
|
||||
/// SELECT "foo" FROM "player"
|
||||
/// """)
|
||||
/// ```
|
||||
public var acceptsDoubleQuotedStringLiterals = false
|
||||
|
||||
/// When true, the `Database.suspendNotification` and
|
||||
/// `Database.resumeNotification` suspend and resume the database. Database
|
||||
/// suspension helps avoiding the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
/// A boolean value indicating whether the database connection listens to
|
||||
/// the ``Database/suspendNotification`` and ``Database/resumeNotification``
|
||||
/// notifications.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// Database suspension helps avoiding the
|
||||
/// [`0xdead10cc` exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
///
|
||||
/// During suspension, all database accesses but reads in WAL mode may throw
|
||||
/// a DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`. You can
|
||||
/// check for those error codes with the
|
||||
/// `DatabaseError.isInterruptionError` property.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// a ``DatabaseError`` of code `SQLITE_INTERRUPT` or `SQLITE_ABORT`. You
|
||||
/// can check for those error codes with the
|
||||
/// ``DatabaseError/isInterruptionError`` property.
|
||||
public var observesSuspensionNotifications = false
|
||||
|
||||
/// If false (the default), statement arguments are not visible in the
|
||||
/// description of database errors and trace events, preventing sensitive
|
||||
/// A boolean value indicating whether statement arguments are visible in
|
||||
/// the description of database errors and trace events.
|
||||
///
|
||||
/// The default and recommended value is false: statement arguments are not
|
||||
/// visible in database errors and trace events, preventing sensitive
|
||||
/// information from leaking in unexpected places.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // Error: sensitive information is not printed when an error occurs:
|
||||
/// do {
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
///
|
||||
/// // Trace: sensitive information is not printed when a statement is traced:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// // Error: sensitive information is not printed when an error occurs:
|
||||
/// do {
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
///
|
||||
/// // Trace: sensitive information is not printed when a statement is traced:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// let email = "..." // sensitive information
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
/// For debugging purpose, you can set this flag to true, and get more
|
||||
/// precise database reports. It is your responsibility to prevent sensitive
|
||||
@@ -129,57 +157,65 @@ public struct Configuration {
|
||||
/// this flag in release builds (think about GDPR and other
|
||||
/// privacy-related rules):
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// #if DEBUG
|
||||
/// // Protect sensitive information by enabling verbose debugging in DEBUG builds only
|
||||
/// config.publicStatementArguments = true
|
||||
/// #endif
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// #if DEBUG
|
||||
/// // Protect sensitive information by enabling verbose debugging in DEBUG builds only
|
||||
/// config.publicStatementArguments = true
|
||||
/// #endif
|
||||
///
|
||||
/// // The descriptions of trace events and errors now contain the
|
||||
/// // sensitive information:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// do {
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
/// // The descriptions of trace events and errors now contain the
|
||||
/// // sensitive information:
|
||||
/// db.trace { event in
|
||||
/// print(event)
|
||||
/// }
|
||||
/// do {
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// print(error)
|
||||
/// }
|
||||
/// ```
|
||||
public var publicStatementArguments = false
|
||||
|
||||
// MARK: - Managing SQLite Connections
|
||||
|
||||
private var setups: [(Database) throws -> Void] = []
|
||||
|
||||
/// The function argument is run when an SQLite connection is opened,
|
||||
/// before the connection is made available for database access methods.
|
||||
/// Defines a function to run whenever an SQLite connection is opened.
|
||||
///
|
||||
/// The preparation function is run before the connection is made available
|
||||
/// for database access methods.
|
||||
///
|
||||
/// This method can be called several times. The preparation functions are
|
||||
/// run in the same order.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
|
||||
/// }
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// When you use a `DatabasePool`, preparation functions are called for
|
||||
/// When you use a ``DatabasePool``, preparation functions are called for
|
||||
/// the writer connection and all reader connections. You can distinguish
|
||||
/// them by querying `db.configuration.readonly`:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// if db.configuration.readonly {
|
||||
/// // reader connection
|
||||
/// } else {
|
||||
/// // writer connection
|
||||
/// }
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.prepareDatabase { db in
|
||||
/// if db.configuration.readonly {
|
||||
/// // reader connection
|
||||
/// } else {
|
||||
/// // writer connection
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// On newly created databases, `DatabasePool` the WAL mode is activated
|
||||
/// after the preparation functions have run.
|
||||
/// 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) {
|
||||
setups.append(setup)
|
||||
}
|
||||
@@ -188,64 +224,72 @@ public struct Configuration {
|
||||
|
||||
/// The default kind of transaction.
|
||||
///
|
||||
/// Default: deferred
|
||||
/// The default is ``Database/TransactionKind/deferred``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_transaction.html>
|
||||
public var defaultTransactionKind: Database.TransactionKind = .deferred
|
||||
|
||||
/// If false, it is a programmer error to leave a transaction opened at the
|
||||
/// end of a database access block.
|
||||
/// A boolean value indicating whether it is valid to leave a transaction
|
||||
/// opened at the end of a database access method.
|
||||
///
|
||||
/// For example:
|
||||
/// The default value is false: not completing a transaction is a
|
||||
/// programmer error:
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// ```swift
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
///
|
||||
/// // fatal error: A transaction has been left opened at the end of a database access
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
/// // fatal error: A transaction has been left opened at the end of a database access
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If true, one can leave opened transaction at the end of database access
|
||||
/// blocks:
|
||||
/// When true, one can leave opened transaction at the end of database
|
||||
/// access method:
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.allowsUnsafeTransactions = true
|
||||
/// let dbQueue = DatabaseQueue(configuration: config)
|
||||
/// ```swift
|
||||
/// var config = Configuration()
|
||||
/// config.allowsUnsafeTransactions = true
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.commit()
|
||||
/// }
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.commit()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This configuration flag has no effect on DatabasePool readers: those
|
||||
/// never allow leaving a transaction opened at the end of a read access.
|
||||
///
|
||||
/// Default: false
|
||||
/// This configuration flag has no effect on ``DatabasePool`` reader
|
||||
/// connections: those never allow leaving a transaction opened at the end
|
||||
/// of a read access.
|
||||
public var allowsUnsafeTransactions = false
|
||||
|
||||
// MARK: - Concurrency
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error. See <https://www.sqlite.org/rescode.html#busy>
|
||||
/// Defines the how `SQLITE_BUSY` errors are handled.
|
||||
///
|
||||
/// Default: immediateError
|
||||
/// The default is ``Database/BusyMode/immediateError``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html#busy>
|
||||
public var busyMode: Database.BusyMode = .immediateError
|
||||
|
||||
/// The behavior in case of SQLITE_BUSY error, for read-only connections.
|
||||
/// If nil, GRDB picks a default one.
|
||||
var readonlyBusyMode: Database.BusyMode? = nil
|
||||
|
||||
/// The maximum number of concurrent readers (applies to database
|
||||
/// pools only).
|
||||
/// The maximum number of concurrent readers.
|
||||
///
|
||||
/// Default: 5
|
||||
/// This configuration applies to ``DatabasePool`` only. The default value
|
||||
/// is 5.
|
||||
public var maximumReaderCount: Int = 5
|
||||
|
||||
/// The quality of service class for the work performed by the database.
|
||||
/// The quality of service, or the execution priority, or database accesses.
|
||||
///
|
||||
/// The quality of service is ignored if you supply a target queue.
|
||||
/// The quality of service is ignored if you supply a ``targetQueue``.
|
||||
///
|
||||
/// Default: .userInitiated
|
||||
/// The default is `userInitiated`.
|
||||
public var qos: DispatchQoS = .userInitiated
|
||||
|
||||
/// The quality of service of read accesses
|
||||
@@ -253,40 +297,42 @@ public struct Configuration {
|
||||
targetQueue?.qos ?? self.qos
|
||||
}
|
||||
|
||||
/// A target queue for database accesses.
|
||||
/// The target dispatch queue for database accesses.
|
||||
///
|
||||
/// Database connections which are not read-only will prefer
|
||||
/// `writeTargetQueue` instead, if it is not nil.
|
||||
/// ``writeTargetQueue`` instead, if it is not nil.
|
||||
///
|
||||
/// When you use a database pool, make sure this queue is concurrent. This
|
||||
/// When you use ``DatabasePool``, make sure this queue is concurrent. This
|
||||
/// is because in a serial dispatch queue, no concurrent database access can
|
||||
/// happen, and you may experience deadlocks.
|
||||
///
|
||||
/// If the queue is nil, all database accesses happen in unspecified
|
||||
/// dispatch queues whose quality of service is determined by the
|
||||
/// `qos` property.
|
||||
/// ``qos`` property.
|
||||
///
|
||||
/// Default: nil
|
||||
/// The default is nil.
|
||||
public var targetQueue: DispatchQueue? = nil
|
||||
|
||||
/// The target queue for database connections which are not read-only.
|
||||
/// The target dispatch queue for database accesses which are not read-only.
|
||||
///
|
||||
/// If this queue is nil, writer connections are controlled by `targetQueue`.
|
||||
/// If this queue is nil, writer connections are controlled
|
||||
/// by ``targetQueue``.
|
||||
///
|
||||
/// Default: nil
|
||||
/// The default is nil.
|
||||
public var writeTargetQueue: DispatchQueue? = nil
|
||||
|
||||
#if os(iOS)
|
||||
/// Sets whether GRDB will release memory when entering the background or
|
||||
/// upon receiving a memory warning in iOS.
|
||||
/// A boolean value indicating whether the database connection releases
|
||||
/// memory when entering the background or upon receiving a memory warning
|
||||
/// in iOS.
|
||||
///
|
||||
/// Default: true
|
||||
/// The default is true.
|
||||
public var automaticMemoryManagement = true
|
||||
#endif
|
||||
|
||||
// MARK: - Factory Configuration
|
||||
|
||||
/// Creates a factory configuration
|
||||
/// Creates a factory configuration.
|
||||
public init() { }
|
||||
|
||||
// MARK: - Not Public
|
||||
@@ -295,9 +341,12 @@ public struct Configuration {
|
||||
var SQLiteConnectionDidOpen: (() -> Void)?
|
||||
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
|
||||
var SQLiteConnectionDidClose: (() -> Void)?
|
||||
var SQLiteOpenFlags: Int32 {
|
||||
let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
|
||||
return threadingMode.SQLiteOpenFlags | readWriteFlags
|
||||
var SQLiteOpenFlags: CInt {
|
||||
var flags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
|
||||
if sqlite3_libversion_number() >= 3037000 {
|
||||
flags |= 0x02000000 // SQLITE_OPEN_EXRESCODE
|
||||
}
|
||||
return threadingMode.SQLiteOpenFlags | flags
|
||||
}
|
||||
|
||||
func setUp(_ db: Database) throws {
|
||||
|
||||
+123
-95
@@ -19,12 +19,9 @@ extension RangeReplaceableCollection {
|
||||
/// let strings = try Array(cursor)
|
||||
///
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
public init(_ cursor: some Cursor<Element>) throws {
|
||||
self.init()
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { append($0) }
|
||||
try append(contentsOf: cursor)
|
||||
}
|
||||
|
||||
/// Creates a collection containing the elements of a cursor.
|
||||
@@ -36,13 +33,23 @@ extension RangeReplaceableCollection {
|
||||
/// - parameter cursor: The cursor whose elements feed the collection.
|
||||
/// - parameter minimumCapacity: Prepares the returned collection to store
|
||||
/// the specified number of elements.
|
||||
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
|
||||
public init(_ cursor: some Cursor<Element>, minimumCapacity: Int) throws {
|
||||
self.init()
|
||||
reserveCapacity(minimumCapacity)
|
||||
try append(contentsOf: cursor)
|
||||
}
|
||||
|
||||
/// Adds the elements of a cursor to the end of this collection.
|
||||
///
|
||||
/// In case of error, an unspecified amount of elements have been added to
|
||||
/// the collection.
|
||||
///
|
||||
/// - parameter newElements: The elements to append to the collection.
|
||||
public mutating func append(contentsOf newElements: some Cursor<Element>) throws {
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
// database cursors.
|
||||
try cursor.forEach { append($0) }
|
||||
try newElements.forEach { append($0) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,9 +119,7 @@ extension Dictionary {
|
||||
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
|
||||
/// new dictionary. Every key in `keysAndValues` must be unique.
|
||||
/// - precondition: The cursor must not have duplicate keys.
|
||||
public init<C: Cursor>(uniqueKeysWithValues keysAndValues: C)
|
||||
throws where C.Element == (Key, Value)
|
||||
{
|
||||
public init(uniqueKeysWithValues keysAndValues: some Cursor<(Key, Value)>) throws {
|
||||
self.init()
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
@@ -144,9 +149,7 @@ extension Dictionary {
|
||||
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
|
||||
/// new dictionary. Every key in `keysAndValues` must be unique.
|
||||
/// - precondition: The cursor must not have duplicate keys.
|
||||
public init<C: Cursor>(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: C)
|
||||
throws where C.Element == (Key, Value)
|
||||
{
|
||||
public init(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: some Cursor<(Key, Value)>) throws {
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
@@ -167,7 +170,7 @@ extension Set {
|
||||
/// let strings = try Set(cursor)
|
||||
///
|
||||
/// - parameter cursor: A cursor of values to gather into a set.
|
||||
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
|
||||
public init(_ cursor: some Cursor<Element>) throws {
|
||||
self.init()
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
@@ -185,7 +188,7 @@ extension Set {
|
||||
/// - parameter minimumCapacity: The minimum number of elements that the
|
||||
/// newly created set should be able to store without reallocating its
|
||||
/// storage buffer.
|
||||
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
|
||||
public init(_ cursor: some Cursor<Element>, minimumCapacity: Int) throws {
|
||||
self.init(minimumCapacity: minimumCapacity)
|
||||
// Prefer `forEach` over `next()` looping, as a slight performance
|
||||
// improvement due to the single `sqlite3_stmt_busy` check for
|
||||
@@ -211,13 +214,13 @@ extension Sequence {
|
||||
///
|
||||
/// ## Overview
|
||||
///
|
||||
/// The most common way to iterate over the elements of a cursor is to use a
|
||||
/// `while` loop:
|
||||
/// To iterate over the elements of a cursor, use a `while` loop:
|
||||
///
|
||||
/// let cursor = ...
|
||||
/// while let element = try cursor.next() {
|
||||
/// ...
|
||||
/// }
|
||||
/// ```swift
|
||||
/// while let element = try cursor.next() {
|
||||
/// print(element)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Relationship with standard Sequence and IteratorProtocol
|
||||
///
|
||||
@@ -234,12 +237,28 @@ extension Sequence {
|
||||
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
|
||||
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
|
||||
/// `suffix`.
|
||||
public protocol Cursor: AnyObject {
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyCursor``
|
||||
/// - ``DropFirstCursor``
|
||||
/// - ``DropWhileCursor``
|
||||
/// - ``EnumeratedCursor``
|
||||
/// - ``FilterCursor``
|
||||
/// - ``FlattenCursor``
|
||||
/// - ``MapCursor``
|
||||
/// - ``PrefixCursor``
|
||||
/// - ``PrefixWhileCursor``
|
||||
public protocol Cursor<Element>: AnyObject {
|
||||
/// The type of element traversed by the cursor.
|
||||
associatedtype Element
|
||||
|
||||
/// Advances to the next element and returns it, or nil if no next element
|
||||
/// exists. Once nil has been returned, all subsequent calls return nil.
|
||||
/// exists.
|
||||
///
|
||||
/// Once nil has been returned, all subsequent calls return nil.
|
||||
func next() throws -> Element?
|
||||
|
||||
/// Calls the given closure on each element in the cursor.
|
||||
@@ -247,10 +266,12 @@ public protocol Cursor: AnyObject {
|
||||
}
|
||||
|
||||
extension Cursor {
|
||||
/// Returns a Boolean value indicating whether the cursor contains
|
||||
/// an element.
|
||||
public func isEmpty() throws -> Bool {
|
||||
try next() == nil
|
||||
/// Returns a Boolean value indicating whether the cursor does not contain
|
||||
/// any element.
|
||||
///
|
||||
/// - important: This property may consume elements.
|
||||
public var isEmpty: Bool {
|
||||
get throws { try next() == nil }
|
||||
}
|
||||
|
||||
/// Returns a Boolean value indicating whether the cursor contains an
|
||||
@@ -311,7 +332,7 @@ extension Cursor {
|
||||
/// Returns a cursor that skips any initial elements that satisfy
|
||||
/// `predicate`.
|
||||
///
|
||||
/// - Parameter predicate: A closure that takes an element of the cursir as
|
||||
/// - Parameter predicate: A closure that takes an element of the cursor as
|
||||
/// its argument and returns `true` if the element should be skipped or
|
||||
/// `false` otherwise. Once `predicate` returns `false` it will not be
|
||||
/// called again.
|
||||
@@ -667,36 +688,37 @@ extension Cursor where Element: StringProtocol {
|
||||
|
||||
// MARK: Specialized Cursors
|
||||
|
||||
/// A type-erased cursor of Element.
|
||||
/// A type-erased cursor.
|
||||
///
|
||||
/// This cursor forwards its next() method to an arbitrary underlying cursor
|
||||
/// having the same Element type, hiding the specifics of the underlying
|
||||
/// cursor.
|
||||
/// An instance of `AnyCursor` forwards its operations to an underlying base
|
||||
/// cursor having the same `Element` type, hiding the specifics of the
|
||||
/// underlying cursor.
|
||||
public final class AnyCursor<Element>: Cursor {
|
||||
private let _next: () throws -> Element?
|
||||
private let _forEach: ((Element) throws -> Void) throws -> Void
|
||||
|
||||
/// Creates a cursor that wraps a base cursor but whose type depends only on
|
||||
/// the base cursor’s element type
|
||||
/// Creates a new cursor that wraps and forwards operations to `base`.
|
||||
public init<C: Cursor>(_ base: C) where C.Element == Element {
|
||||
_next = base.next
|
||||
_forEach = base.forEach
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps a base iterator but whose type depends only
|
||||
/// on the base iterator’s element type
|
||||
public convenience init<I: IteratorProtocol>(iterator: I) where I.Element == Element {
|
||||
/// Creates a new cursor whose elements are elements of `iterator`.
|
||||
public convenience init<I>(iterator: I)
|
||||
where I: IteratorProtocol, I.Element == Element
|
||||
{
|
||||
var iterator = iterator
|
||||
self.init { iterator.next() }
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps a base sequence but whose type depends only
|
||||
/// on the base sequence’s element type
|
||||
public convenience init<S: Sequence>(_ s: S) where S.Element == Element {
|
||||
self.init(iterator: s.makeIterator())
|
||||
/// Creates a new cursor whose elements are elements of `sequence`.
|
||||
public convenience init<S>(_ sequence: S)
|
||||
where S: Sequence, S.Element == Element
|
||||
{
|
||||
self.init(iterator: sequence.makeIterator())
|
||||
}
|
||||
|
||||
/// Creates a cursor that wraps the given closure in its next() method
|
||||
/// Creates a cursor that wraps the given closure in its ``next()`` method.
|
||||
public init(_ next: @escaping () throws -> Element?) {
|
||||
_next = next
|
||||
_forEach = {
|
||||
@@ -711,8 +733,9 @@ public final class AnyCursor<Element>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public final class DropFirstCursor<Base: Cursor>: Cursor {
|
||||
/// A `Cursor` that consumes and drops n elements from an underlying `Base`
|
||||
/// cursor before possibly returning the first available element.
|
||||
public final class DropFirstCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let limit: Int
|
||||
private var dropped: Int = 0
|
||||
@@ -722,7 +745,9 @@ public final class DropFirstCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.limit = limit
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension DropFirstCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
while dropped < limit {
|
||||
if try base.next() == nil {
|
||||
@@ -735,11 +760,9 @@ public final class DropFirstCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements that follow the initial
|
||||
/// consecutive elements of some base cursor that satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class DropWhileCursor<Base: Cursor>: Cursor {
|
||||
/// A `Cursor` whose elements consist of the elements that follow the initial
|
||||
/// consecutive elements of some `Base` cursor that satisfy a given predicate.
|
||||
public final class DropWhileCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
@@ -748,7 +771,9 @@ public final class DropWhileCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension DropWhileCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if predicateHasFailed {
|
||||
return try base.next()
|
||||
@@ -766,19 +791,24 @@ public final class DropWhileCursor<Base: Cursor>: Cursor {
|
||||
|
||||
/// An enumeration of the elements of a cursor.
|
||||
///
|
||||
/// To create an instance of `EnumeratedCursor`, call the `enumerated()` method
|
||||
/// on a cursor:
|
||||
/// `EnumeratedCursor` is a cursor of pairs _(n, x)_, where _ns_ are consecutive
|
||||
/// `Int` values starting at zero, and _xs_ are the elements of a `Base` cursor.
|
||||
///
|
||||
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
|
||||
/// let c = cursor.enumerated()
|
||||
/// while let (n, x) = c.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
/// To create an instance of `EnumeratedCursor`, call `enumerated()` on a
|
||||
/// cursor. For example:
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class EnumeratedCursor<Base: Cursor>: Cursor {
|
||||
/// ```swift
|
||||
/// let base = try String.fetchCursor(db, sql: """
|
||||
/// SELECT 'foo' UNION ALL SELECT 'bar'
|
||||
/// """)
|
||||
/// let cursor = base.enumerated()
|
||||
/// while let (n, x) = cursor.next() {
|
||||
/// print("\(n): \(x)")
|
||||
/// }
|
||||
/// // Prints: "0: foo"
|
||||
/// // Prints: "1: bar"
|
||||
/// ```
|
||||
public final class EnumeratedCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private var index: Int
|
||||
|
||||
@@ -786,7 +816,9 @@ public final class EnumeratedCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.index = 0
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension EnumeratedCursor: Cursor {
|
||||
public func next() throws -> (Int, Base.Element)? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
defer { index += 1 }
|
||||
@@ -801,11 +833,9 @@ public final class EnumeratedCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the elements of some base cursor that
|
||||
/// A `Cursor` whose elements consist of the elements of some `Base` cursor that
|
||||
/// also satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FilterCursor<Base: Cursor>: Cursor {
|
||||
public final class FilterCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let isIncluded: (Base.Element) throws -> Bool
|
||||
|
||||
@@ -813,7 +843,9 @@ public final class FilterCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.isIncluded = isIncluded
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension FilterCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
while let element = try base.next() {
|
||||
if try isIncluded(element) {
|
||||
@@ -832,20 +864,18 @@ public final class FilterCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor consisting of all the elements contained in each segment contained
|
||||
/// in some Base cursor.
|
||||
///
|
||||
/// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:)
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class FlattenCursor<Base: Cursor>: Cursor where Base.Element: Cursor {
|
||||
/// A `Cursor` consisting of all the elements contained in each segment
|
||||
/// contained in some `Base` cursor.
|
||||
public final class FlattenCursor<Base: Cursor> where Base.Element: Cursor {
|
||||
private let base: Base
|
||||
private var inner: Base.Element?
|
||||
|
||||
init(_ base: Base) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension FlattenCursor: Cursor {
|
||||
public func next() throws -> Base.Element.Element? {
|
||||
while true {
|
||||
if let element = try inner?.next() {
|
||||
@@ -859,13 +889,9 @@ public final class FlattenCursor<Base: Cursor>: Cursor where Base.Element: Curso
|
||||
}
|
||||
}
|
||||
|
||||
/// A Cursor whose elements consist of those in a Base Cursor passed through a
|
||||
/// transform function returning Element.
|
||||
///
|
||||
/// See Cursor.map(_:)
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class MapCursor<Base: Cursor, Element>: Cursor {
|
||||
/// A `Cursor` whose elements consist of those in a `Base` cursor passed through
|
||||
/// a transform function returning Element.
|
||||
public final class MapCursor<Base: Cursor, Element> {
|
||||
private let base: Base
|
||||
private let transform: (Base.Element) throws -> Element
|
||||
|
||||
@@ -873,7 +899,9 @@ public final class MapCursor<Base: Cursor, Element>: Cursor {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension MapCursor: Cursor {
|
||||
public func next() throws -> Element? {
|
||||
guard let element = try base.next() else { return nil }
|
||||
return try transform(element)
|
||||
@@ -886,11 +914,9 @@ public final class MapCursor<Base: Cursor, Element>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor that only consumes up to `n` elements from an underlying
|
||||
/// A `Cursor` that only consumes up to `n` elements from an underlying
|
||||
/// `Base` cursor.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixCursor<Base: Cursor>: Cursor {
|
||||
public final class PrefixCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let maxLength: Int
|
||||
private var taken = 0
|
||||
@@ -899,7 +925,9 @@ public final class PrefixCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.maxLength = maxLength
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension PrefixCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if taken >= maxLength { return nil }
|
||||
taken += 1
|
||||
@@ -913,11 +941,9 @@ public final class PrefixCursor<Base: Cursor>: Cursor {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor whose elements consist of the initial consecutive elements of
|
||||
/// some base cursor that satisfy a given predicate.
|
||||
///
|
||||
/// :nodoc:
|
||||
public final class PrefixWhileCursor<Base: Cursor>: Cursor {
|
||||
/// A `Cursor` whose elements consist of the initial consecutive elements of
|
||||
/// some `Base` cursor that satisfy a given predicate.
|
||||
public final class PrefixWhileCursor<Base: Cursor> {
|
||||
private let base: Base
|
||||
private let predicate: (Base.Element) throws -> Bool
|
||||
private var predicateHasFailed = false
|
||||
@@ -926,7 +952,9 @@ public final class PrefixWhileCursor<Base: Cursor>: Cursor {
|
||||
self.base = base
|
||||
self.predicate = predicate
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension PrefixWhileCursor: Cursor {
|
||||
public func next() throws -> Base.Element? {
|
||||
if !predicateHasFailed, let nextElement = try base.next() {
|
||||
if try predicate(nextElement) {
|
||||
|
||||
+448
-217
File diff suppressed because it is too large.
Load diff
+233
-344
@@ -6,50 +6,61 @@ extension Database {
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```swift
|
||||
/// let statement = try db.makeStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// let statement = try db.makeStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sql: An SQL string.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func makeStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql, prepFlags: 0)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```swift
|
||||
/// let statement = try db.makeStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
/// let statement = try db.makeStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// // OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. An error is raised otherwise. For example:
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK (first argument is not set, but second is)
|
||||
/// try makeStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func makeStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try makeStatement(sql: sql)
|
||||
@@ -62,56 +73,18 @@ extension Database {
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.makeSelectStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
@available(*, deprecated, renamed: "makeStatement(sql:)")
|
||||
public func makeSelectStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try makeSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try makeSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "makeStatement(literal:)")
|
||||
public func makeSelectStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try makeStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?", prepFlags: 0)
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - parameter sql: An SQL string.
|
||||
/// - parameter prepFlags: Flags for sqlite3_prepare_v3 (available from
|
||||
/// SQLite 3.20.0, see <http://www.sqlite.org/c3ref/prepare.html>)
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
func makeStatement(sql: String, prepFlags: Int32) throws -> Statement {
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
func makeStatement(sql: String, prepFlags: CUnsignedInt) throws -> Statement {
|
||||
let statements = SQLStatementCursor(database: self, sql: sql, arguments: nil, prepFlags: prepFlags)
|
||||
guard let statement = try statements.next() else {
|
||||
throw DatabaseError(
|
||||
@@ -145,53 +118,64 @@ extension Database {
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```swift
|
||||
/// let statement = try db.cachedStatement(sql: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// let statement = try db.cachedStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - parameter sql: An SQL string.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func cachedStatement(sql: String) throws -> Statement {
|
||||
try publicStatementCache.statement(sql)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
/// For example:
|
||||
///
|
||||
/// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```swift
|
||||
/// let statement = try db.cachedStatement(literal: "SELECT * FROM player WHERE id = ?")
|
||||
/// let player1 = try Player.fetchOne(statement, arguments: [1])!
|
||||
/// let player2 = try Player.fetchOne(statement, arguments: [2])!
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
/// let statement = try db.cachedStatement(literal: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// ```
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. An error is raised otherwise. For example:
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK (first argument is not set, but second is)
|
||||
/// try cachedStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - returns: A prepared statement.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func cachedStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
let (sql, arguments) = try sqlLiteral.build(self)
|
||||
let statement = try cachedStatement(sql: sql)
|
||||
@@ -202,213 +186,100 @@ extension Database {
|
||||
return statement
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedSelectStatement(sql: "SELECT COUNT(*) FROM player WHERE score > ?")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement, arguments: [20])!
|
||||
/// let moreThanThirtyCount = try Int.fetchOne(statement, arguments: [30])!
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
@available(*, deprecated, renamed: "cachedStatement(sql:)")
|
||||
public func cachedSelectStatement(sql: String) throws -> Statement {
|
||||
try cachedStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// let statement = try db.cachedSelectStatement(literal: "SELECT COUNT(*) FROM player WHERE score > \(20)")
|
||||
/// let moreThanTwentyCount = try Int.fetchOne(statement)!
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?
|
||||
/// """)
|
||||
/// try cachedSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000)
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedSelectStatement(literal: """
|
||||
/// SELECT COUNT(*) FROM player
|
||||
/// WHERE color = ? AND score > \(1000)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "cachedStatement(literal:)")
|
||||
public func cachedSelectStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try cachedStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a cached statement that does not conflict with user's cached statements.
|
||||
func internalCachedStatement(sql: String) throws -> Statement {
|
||||
try internalStatementCache.statement(sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
/// Returns a cursor of prepared statements.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
/// For example:
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: An UpdateStatement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
@available(*, deprecated, renamed: "makeStatement(sql:)")
|
||||
public func makeUpdateStatement(sql: String) throws -> Statement {
|
||||
try makeStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
/// ```swift
|
||||
/// let statements = try db.allStatements(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
/// The `arguments` parameter must be nil, or all arguments must be set. The
|
||||
/// returned cursor will throw an error otherwise. For example:
|
||||
///
|
||||
/// // OK
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?
|
||||
/// """)
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = \("O'Brien")
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?, score = \(10)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "makeStatement(literal:)")
|
||||
public func makeUpdateStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try makeStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000, 1000])
|
||||
///
|
||||
/// let statement = try db.cachedUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// The returned statement may have already been used: it may or may not
|
||||
/// contain values for its eventual arguments.
|
||||
///
|
||||
/// - parameter sql: An SQL query.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
@available(*, deprecated, renamed: "cachedStatement(sql:)")
|
||||
public func cachedUpdateStatement(sql: String) throws -> Statement {
|
||||
try cachedStatement(sql: sql)
|
||||
}
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A Statement.
|
||||
/// - throws: A DatabaseError whenever SQLite could not parse the sql query.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// An error is raised otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try cachedUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?
|
||||
/// """)
|
||||
/// try cachedUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = \("O'Brien")
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try cachedUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?, score = \(10)
|
||||
/// """)
|
||||
@available(*, deprecated, renamed: "cachedStatement(sql:)")
|
||||
public func cachedUpdateStatement(literal sqlLiteral: SQL) throws -> Statement {
|
||||
try cachedStatement(literal: sqlLiteral)
|
||||
}
|
||||
|
||||
/// Returns a cursor of all SQL statements separated by semi-colons.
|
||||
///
|
||||
/// let statements = try db.allStatements(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
/// // NOT OK (first argument is set, but second is not)
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000])
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - returns: A cursor of `Statement`
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - precondition: Arguments must be nil, or all arguments must be set.
|
||||
/// The returned cursor will throw an error otherwise.
|
||||
///
|
||||
/// // OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000, 1000])
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try allStatements(sql: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """, arguments: [1000])
|
||||
/// - returns: A cursor of prepared ``Statement``.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func allStatements(sql: String, arguments: StatementArguments? = nil)
|
||||
throws -> SQLStatementCursor
|
||||
{
|
||||
SQLStatementCursor(database: self, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Returns a cursor of all SQL statements separated by semi-colons.
|
||||
/// Returns a cursor of prepared statements.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let statements = try db.allStatements(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let statements = try db.allStatements(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// while let statement = try statements.next() {
|
||||
/// try statement.execute()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - returns: A cursor of `Statement`
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - precondition: No argument must be set, or all arguments must be set.
|
||||
/// The returned cursor will throw an error otherwise.
|
||||
/// In the provided literal, no argument must be set, or all arguments must
|
||||
/// be set. The returned cursor will throw an error otherwise. For example:
|
||||
///
|
||||
/// // OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000);
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// // OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < ?;
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > \(1000);
|
||||
/// """)
|
||||
///
|
||||
/// // NOT OK (first argument is set, but second is not)
|
||||
/// try allStatements(literal: """
|
||||
/// SELECT COUNT(*) FROM player WHERE score < \(1000);
|
||||
/// SELECT COUNT(*) FROM player WHERE score > ?;
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - returns: A cursor of prepared ``Statement``.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func allStatements(literal sqlLiteral: SQL) throws -> SQLStatementCursor {
|
||||
let context = SQLGenerationContext(self)
|
||||
let sql = try sqlLiteral.sql(context)
|
||||
@@ -418,47 +289,49 @@ extension Database {
|
||||
return SQLStatementCursor(database: self, sql: sql, arguments: arguments)
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
/// Executes one or several SQL statements.
|
||||
///
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
/// For example:
|
||||
///
|
||||
/// try db.execute(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// ```swift
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
/// try db.execute(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func execute(sql: String, arguments: StatementArguments = StatementArguments()) throws {
|
||||
try execute(literal: SQL(sql: sql, arguments: arguments))
|
||||
}
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
/// Executes one or several SQL statements.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"))
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"))
|
||||
/// """)
|
||||
///
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// try db.execute(literal: """
|
||||
/// INSERT INTO player (name) VALUES (\("Arthur"));
|
||||
/// INSERT INTO player (name) VALUES (\("Barbara"));
|
||||
/// INSERT INTO player (name) VALUES (\("O'Brien"));
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameter sqlLiteral: An `SQL` literal.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - parameter sqlLiteral: An ``SQL`` literal.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public func execute(literal sqlLiteral: SQL) throws {
|
||||
let statements = try allStatements(literal: sqlLiteral)
|
||||
while let statement = try statements.next() {
|
||||
@@ -467,17 +340,18 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
public class SQLStatementCursor: Cursor {
|
||||
/// A cursor over all statements in an SQL string.
|
||||
public class SQLStatementCursor {
|
||||
private let database: Database
|
||||
private let cString: ContiguousArray<CChar>
|
||||
private let prepFlags: CInt
|
||||
private let prepFlags: CUnsignedInt
|
||||
private let initialArgumentCount: Int?
|
||||
|
||||
// Mutated by iteration
|
||||
private var offset: Int // offset in the C string
|
||||
private var arguments: StatementArguments? // Nil when arguments are set later
|
||||
|
||||
init(database: Database, sql: String, arguments: StatementArguments?, prepFlags: CInt = 0) {
|
||||
init(database: Database, sql: String, arguments: StatementArguments?, prepFlags: CUnsignedInt = 0) {
|
||||
self.database = database
|
||||
self.cString = sql.utf8CString
|
||||
self.prepFlags = prepFlags
|
||||
@@ -485,30 +359,32 @@ public class SQLStatementCursor: Cursor {
|
||||
self.offset = 0
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension SQLStatementCursor: Cursor {
|
||||
public func next() throws -> Statement? {
|
||||
guard offset < cString.count - 1 /* trailing \0 */ else {
|
||||
// End of C string -> end of cursor.
|
||||
try checkArgumentsAreEmpty()
|
||||
return nil
|
||||
}
|
||||
|
||||
return try cString.withUnsafeBufferPointer { buffer in
|
||||
guard let baseAddress = buffer.baseAddress else {
|
||||
// Should never happen since buffer contains at least
|
||||
// the trailing \0
|
||||
return nil
|
||||
}
|
||||
let baseAddress = buffer.baseAddress! // never nil because the buffer contains the trailing \0.
|
||||
|
||||
// Compile next statement
|
||||
var statementEnd: UnsafePointer<Int8>? = nil
|
||||
let compiledStatement = try Statement(
|
||||
let statement = try Statement(
|
||||
database: database,
|
||||
statementStart: baseAddress + offset,
|
||||
statementEnd: &statementEnd,
|
||||
prepFlags: prepFlags)
|
||||
|
||||
offset = statementEnd! - baseAddress
|
||||
// Advance to next statement
|
||||
offset = statementEnd! - baseAddress // never nil because statement compilation did not fail.
|
||||
|
||||
guard let statement = compiledStatement else {
|
||||
guard let statement else {
|
||||
// No statement found -> end of cursor.
|
||||
try checkArgumentsAreEmpty()
|
||||
return nil
|
||||
}
|
||||
@@ -545,18 +421,22 @@ extension Database {
|
||||
/// Makes sure statement can be executed, and prepares database observation.
|
||||
@usableFromInline
|
||||
func statementWillExecute(_ statement: Statement) throws {
|
||||
// Two things must prevent the statement from executing: aborted
|
||||
// transactions, and database suspension.
|
||||
// Aborted transactions prevent statement execution (see the
|
||||
// documentation of this method for more information).
|
||||
try checkForAbortedTransaction(sql: statement.sql, arguments: statement.arguments)
|
||||
|
||||
// Suspended databases must not execute statements that create the risk
|
||||
// of `0xdead10cc` exception (see the documentation of this method for
|
||||
// more information).
|
||||
try checkForSuspensionViolation(from: statement)
|
||||
|
||||
// Database observation: record what the statement is looking at.
|
||||
// Record the database region selected by the statement execution.
|
||||
if isRecordingSelectedRegion {
|
||||
selectedRegion.formUnion(statement.databaseRegion)
|
||||
}
|
||||
|
||||
// Database observation: prepare transaction observers.
|
||||
observationBroker.statementWillExecute(statement)
|
||||
observationBroker?.statementWillExecute(statement)
|
||||
}
|
||||
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
@@ -567,13 +447,14 @@ extension Database {
|
||||
clearSchemaCache()
|
||||
}
|
||||
|
||||
try observationBroker.statementDidExecute(statement)
|
||||
// Database observation: cleanup
|
||||
try observationBroker?.statementDidExecute(statement)
|
||||
}
|
||||
|
||||
/// Always throws an error
|
||||
@usableFromInline
|
||||
func statementDidFail(_ statement: Statement, withResultCode resultCode: Int32) throws -> Never {
|
||||
// Failed statements can not be reused, because sqlite3_reset won't
|
||||
func statementDidFail(_ statement: Statement, withResultCode resultCode: CInt) throws -> Never {
|
||||
// Failed statements can not be reused, because `sqlite3_reset` won't
|
||||
// be able to restore the statement to its initial state:
|
||||
// https://www.sqlite.org/c3ref/reset.html
|
||||
//
|
||||
@@ -581,15 +462,25 @@ extension Database {
|
||||
internalStatementCache.remove(statement)
|
||||
publicStatementCache.remove(statement)
|
||||
|
||||
/// Exposes the user-provided cancelled commit error, if a transaction
|
||||
/// observer has cancelled a transaction.
|
||||
try observationBroker.statementDidFail(statement)
|
||||
// Extract values that may be modified by the user in their
|
||||
// `TransactionObserver.databaseDidRollback(_:)` implementation
|
||||
// (see below).
|
||||
let message = lastErrorMessage
|
||||
let arguments = statement.arguments
|
||||
|
||||
// Database observation: cleanup.
|
||||
//
|
||||
// If the statement failure is due to a transaction observer that has
|
||||
// cancelled a transaction, this calls `TransactionObserver.databaseDidRollback(_:)`,
|
||||
// and throws the user-provided cancelled commit error.
|
||||
try observationBroker?.statementDidFail(statement)
|
||||
|
||||
// Throw statement failure
|
||||
throw DatabaseError(
|
||||
resultCode: resultCode,
|
||||
message: lastErrorMessage,
|
||||
message: message,
|
||||
sql: statement.sql,
|
||||
arguments: statement.arguments,
|
||||
arguments: arguments,
|
||||
publicStatementArguments: configuration.publicStatementArguments)
|
||||
}
|
||||
}
|
||||
@@ -618,14 +509,12 @@ struct StatementCache {
|
||||
// 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: SQLITE_PREPARE_PERSISTENT)
|
||||
let statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
|
||||
#else
|
||||
let statement: Statement
|
||||
if #available(iOS 12.0, OSX 10.14, watchOS 5.0, *) {
|
||||
// SQLite 3.24.0 or more
|
||||
statement = try db.makeStatement(sql: sql, prepFlags: SQLITE_PREPARE_PERSISTENT)
|
||||
statement = try db.makeStatement(sql: sql, prepFlags: CUnsignedInt(SQLITE_PREPARE_PERSISTENT))
|
||||
} else {
|
||||
// SQLite 3.19.3 or less
|
||||
statement = try db.makeStatement(sql: sql)
|
||||
}
|
||||
#endif
|
||||
|
||||
+594
-369
File diff suppressed because it is too large.
Load diff
@@ -1,22 +1,27 @@
|
||||
/// An instance of `DatabaseBackupProgress` is passed to a callback of the
|
||||
/// `DatabaseReader.backup` or `Database.backup` methods to report
|
||||
/// database backup progress to the caller.
|
||||
/// Describe the progress of a database backup.
|
||||
///
|
||||
/// This is an advanced API for expert users. It is based directly on the SQLite
|
||||
/// [online backup API](https://www.sqlite.org/c3ref/backup_finish.html).
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
public struct DatabaseBackupProgress {
|
||||
/// Total page count is defined by the `sqlite3_backup_remaining` function
|
||||
/// The number of pages still to be backed up.
|
||||
///
|
||||
/// It is the result of the `sqlite3_backup_remaining` function.
|
||||
public let remainingPageCount: Int
|
||||
|
||||
/// Total page count is defined by the `sqlite3_backup_pagecount` function
|
||||
|
||||
/// The number of pages in the source database.
|
||||
///
|
||||
/// It is the result of the `sqlite3_backup_pagecount` function.
|
||||
public let totalPageCount: Int
|
||||
|
||||
/// Completed page count is defined as `sqlite3_backup_pagecount() - sqlite3_backup_remaining()`
|
||||
|
||||
/// The number of of backed up pages.
|
||||
///
|
||||
/// It is equal to `totalPageCount - remainingPageCount`.
|
||||
public var completedPageCount: Int {
|
||||
totalPageCount - remainingPageCount
|
||||
}
|
||||
|
||||
/// This property is true if and only if `sqlite3_backup_step()` returns
|
||||
/// `SQLITE_DONE`
|
||||
|
||||
/// A boolean value indicating whether the backup is complete.
|
||||
///
|
||||
/// It is true if and only if the last call the `sqlite3_backup_step` has
|
||||
/// returned `SQLITE_DONE`.
|
||||
public let isCompleted: Bool
|
||||
}
|
||||
@@ -1,21 +1,44 @@
|
||||
import Foundation
|
||||
|
||||
/// A Collation is a string comparison function used by SQLite.
|
||||
/// `DatabaseCollation` is a custom string comparison function used by SQLite.
|
||||
///
|
||||
/// See also ``Database/CollationName``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html#collating_sequences>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a Custom Collation
|
||||
///
|
||||
/// - ``init(_:function:)``
|
||||
/// - ``name``
|
||||
///
|
||||
/// ### Built-in Collations
|
||||
///
|
||||
/// - ``caseInsensitiveCompare``
|
||||
/// - ``localizedCaseInsensitiveCompare``
|
||||
/// - ``localizedCompare``
|
||||
/// - ``localizedStandardCompare``
|
||||
/// - ``unicodeCompare``
|
||||
public final class DatabaseCollation {
|
||||
/// The name of the collation
|
||||
/// The name of the collation.
|
||||
public let name: String
|
||||
let function: (Int32, UnsafeRawPointer?, Int32, UnsafeRawPointer?) -> ComparisonResult
|
||||
let function: (CInt, UnsafeRawPointer?, CInt, UnsafeRawPointer?) -> ComparisonResult
|
||||
|
||||
/// Creates a collation.
|
||||
///
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard")
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
|
||||
/// return (string1 as NSString).localizedStandardCompare(string2)
|
||||
/// }
|
||||
/// db.add(collation: collation)
|
||||
/// try db.execute(sql: "CREATE TABLE file (name TEXT COLLATE localized_standard")
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
/// - name: The collation name.
|
||||
/// - function: A function that compares two strings.
|
||||
public init(_ name: String, function: @escaping (String, String) -> ComparisonResult) {
|
||||
self.name = name
|
||||
@@ -43,13 +66,11 @@ extension DatabaseCollation: Hashable {
|
||||
// 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.
|
||||
/// :nodoc:
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(0)
|
||||
}
|
||||
|
||||
/// Two collations are equal if they share the same name (case insensitive)
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseCollation, rhs: DatabaseCollation) -> Bool {
|
||||
// See <https://www.sqlite.org/c3ref/create_collation.html>
|
||||
return sqlite3_stricmp(lhs.name, rhs.name) == 0
|
||||
|
||||
+156
-66
@@ -2,9 +2,9 @@ import Foundation
|
||||
|
||||
/// An SQLite result code.
|
||||
///
|
||||
/// See <https://www.sqlite.org/rescode.html>
|
||||
public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
/// The raw SQLite result code
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
public struct ResultCode: RawRepresentable, Equatable {
|
||||
/// The raw SQLite result code.
|
||||
public let rawValue: CInt
|
||||
|
||||
/// Creates a `ResultCode` from a raw SQLite result code.
|
||||
@@ -12,11 +12,14 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// A result code limited to the least significant 8 bits of the receiver.
|
||||
/// See <https://www.sqlite.org/rescode.html> for more information.
|
||||
/// A primary result code limited to the least significant 8 bits.
|
||||
///
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let resultCode = .SQLITE_CONSTRAINT_FOREIGNKEY
|
||||
/// resultCode.primaryResultCode == .SQLITE_CONSTRAINT // true
|
||||
/// ```
|
||||
public var primaryResultCode: ResultCode {
|
||||
ResultCode(rawValue: rawValue & 0xFF)
|
||||
}
|
||||
@@ -28,11 +31,15 @@ public struct ResultCode: RawRepresentable, Equatable, CustomStringConvertible {
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
/// while extended result codes match only themselves:
|
||||
///
|
||||
/// switch error.extendedResultCode {
|
||||
/// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
|
||||
/// case .SQLITE_CONSTRAINT: // any other constraint error
|
||||
/// default: // any other database error
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// switch error.extendedResultCode {
|
||||
/// case .SQLITE_CONSTRAINT_FOREIGNKEY: // foreign key constraint error
|
||||
/// case .SQLITE_CONSTRAINT: // any other constraint error
|
||||
/// default: // any other database error
|
||||
/// }
|
||||
/// ```
|
||||
public static func ~= (pattern: ResultCode, code: ResultCode) -> Bool {
|
||||
if pattern.isPrimary {
|
||||
return pattern == code.primaryResultCode
|
||||
@@ -166,28 +173,30 @@ extension ResultCode {
|
||||
/// Primary result codes match themselves and their extended result codes,
|
||||
/// while extended result codes match only themselves.
|
||||
///
|
||||
/// do {
|
||||
/// try ...
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // foreign key constraint error
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT {
|
||||
/// // any other constraint error
|
||||
/// } catch {
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try ...
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // foreign key constraint error
|
||||
/// } catch ResultCode.SQLITE_CONSTRAINT {
|
||||
/// // any other constraint error
|
||||
/// } catch {
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// ```
|
||||
public static func ~= (lhs: Self, rhs: Error) -> Bool {
|
||||
guard let error = rhs as? DatabaseError else { return false }
|
||||
return lhs ~= error.extendedResultCode
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension ResultCode {
|
||||
extension ResultCode: CustomStringConvertible {
|
||||
var errorString: String? {
|
||||
String(cString: sqlite3_errstr(rawValue))
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
if let errorString = errorString {
|
||||
return "\(rawValue) (\(errorString))"
|
||||
@@ -197,63 +206,145 @@ extension ResultCode {
|
||||
}
|
||||
}
|
||||
|
||||
extension ResultCode: GRDBSendable { }
|
||||
extension ResultCode: Sendable { }
|
||||
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
|
||||
/// The SQLite error code (see
|
||||
/// <https://www.sqlite.org/rescode.html#primary_result_code_list>).
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// A `DatabaseError` describes an SQLite error.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try player.insert(db)
|
||||
/// } catch let error as DatabaseError {
|
||||
/// switch error.resultCode {
|
||||
/// case ResultCode.SQLITE_CONSTRAINT_FOREIGNKEY:
|
||||
/// // foreign key constraint error
|
||||
/// case ResultCode.SQLITE_CONSTRAINT:
|
||||
/// // any other constraint error
|
||||
/// default:
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The above example can also be written in a shorter way:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// try player.insert(db)
|
||||
/// } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // foreign key constraint error
|
||||
/// } catch DatabaseError.SQLITE_CONSTRAINT {
|
||||
/// // any other constraint error
|
||||
/// } catch {
|
||||
/// // any other database error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating DatabaseError
|
||||
///
|
||||
/// - ``init(resultCode:message:sql:arguments:publicStatementArguments:)``
|
||||
/// - ``ResultCode``
|
||||
///
|
||||
/// ### Error Information
|
||||
///
|
||||
/// - ``arguments``
|
||||
/// - ``extendedResultCode``
|
||||
/// - ``isInterruptionError``
|
||||
/// - ``message``
|
||||
/// - ``resultCode``
|
||||
/// - ``sql``
|
||||
///
|
||||
/// ### Converting DatabaseError to String
|
||||
///
|
||||
/// - ``description``
|
||||
/// - ``expandedDescription``
|
||||
public struct DatabaseError: Error {
|
||||
/// The SQLite primary result code.
|
||||
///
|
||||
/// This property returns a "primary result code", that is to say the least
|
||||
/// significant 8 bits of any SQLite result code. See
|
||||
/// <https://www.sqlite.org/rescode.html> for more information.
|
||||
/// significant 8 bits of any SQLite result code.
|
||||
///
|
||||
/// See also `extendedResultCode`.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.resultCode == .SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The above example can also be written in a shorter way:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch DatabaseError.SQL_CONSTRAINT {
|
||||
/// // A constraint error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See also ``extendedResultCode``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
public var resultCode: ResultCode {
|
||||
extendedResultCode.primaryResultCode
|
||||
}
|
||||
|
||||
/// The SQLite extended error code (see
|
||||
/// <https://www.sqlite.org/rescode.html#extended_result_code_list>).
|
||||
/// The SQLite extended error code.
|
||||
///
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // A foreign key constraint error
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// See also `resultCode`.
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch let error as DatabaseError where error.extendedResultCode == .SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // A foreign key constraint error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The above example can also be written in a shorter way:
|
||||
///
|
||||
/// ```swift
|
||||
/// do {
|
||||
/// ...
|
||||
/// } catch DatabaseError.SQLITE_CONSTRAINT_FOREIGNKEY {
|
||||
/// // A foreign key constraint error
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See also ``resultCode``.
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/rescode.html>
|
||||
public let extendedResultCode: ResultCode
|
||||
|
||||
/// The SQLite error message.
|
||||
public let message: String?
|
||||
|
||||
/// The SQL query that yielded the error (if relevant).
|
||||
/// The SQL query that yielded the error.
|
||||
public let sql: String?
|
||||
|
||||
/// The query arguments that yielded the error (if relevant).
|
||||
/// The query arguments that yielded the error.
|
||||
public let arguments: StatementArguments?
|
||||
|
||||
/// See Configuration.publicStatementArguments
|
||||
var publicStatementArguments: Bool
|
||||
|
||||
/// Creates a DatabaseError.
|
||||
/// Creates a `DatabaseError`.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - resultCode: A ResultCode (defaults to .SQLITE_ERROR).
|
||||
/// - message: An eventual error message. If nil, the error message is
|
||||
/// derived from the result code.
|
||||
/// - sql: An eventual SQL string.
|
||||
/// - arguments: Eventual Statement arguments.
|
||||
/// - arguments: Eventual statement arguments.
|
||||
/// - publicStatementArguments: If false (the default), statement
|
||||
/// arguments are not visible in the error's `description` property.
|
||||
/// arguments are not visible in the error's ``description`` property.
|
||||
public init(
|
||||
resultCode: ResultCode = .SQLITE_ERROR,
|
||||
message: String? = nil,
|
||||
@@ -422,13 +513,14 @@ extension DatabaseError {
|
||||
}
|
||||
|
||||
extension DatabaseError {
|
||||
/// Returns true if the error has code `SQLITE_ABORT` or `SQLITE_INTERRUPT`.
|
||||
/// A boolean value indicating if the error has code
|
||||
/// `SQLITE_ABORT` or `SQLITE_INTERRUPT`.
|
||||
///
|
||||
/// Such an error can be thrown when a database has been interrupted, or
|
||||
/// when the database is suspended.
|
||||
///
|
||||
/// See `DatabaseReader.interrupt()` and `DatabaseReader.suspend()` for
|
||||
/// more information.
|
||||
/// See ``DatabaseReader/interrupt()`` and ``Database/suspendNotification``
|
||||
/// for more information.
|
||||
public var isInterruptionError: Bool {
|
||||
switch resultCode {
|
||||
case .SQLITE_ABORT, .SQLITE_INTERRUPT:
|
||||
@@ -439,8 +531,7 @@ extension DatabaseError {
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseError {
|
||||
extension DatabaseError: CustomStringConvertible {
|
||||
/// The error description.
|
||||
///
|
||||
/// For example:
|
||||
@@ -493,19 +584,18 @@ extension DatabaseError {
|
||||
}
|
||||
}
|
||||
|
||||
// CustomNSError
|
||||
extension DatabaseError {
|
||||
|
||||
/// NSError bridging: the domain of the error.
|
||||
/// :nodoc:
|
||||
extension DatabaseError: CustomNSError {
|
||||
/// Part of the `CustomNSError` conformance.
|
||||
///
|
||||
/// Returns `GRDB.DatabaseError`.
|
||||
public static var errorDomain: String { "GRDB.DatabaseError" }
|
||||
|
||||
/// NSError bridging: the error code within the given domain.
|
||||
/// :nodoc:
|
||||
/// Part of the `CustomNSError` conformance.
|
||||
///
|
||||
/// Returns the ``extendedResultCode``.
|
||||
public var errorCode: Int { Int(extendedResultCode.rawValue) }
|
||||
|
||||
/// NSError bridging: the user-info dictionary.
|
||||
/// :nodoc:
|
||||
/// Part of the `CustomNSError` conformance.
|
||||
public var errorUserInfo: [String: Any] {
|
||||
var userInfo = [NSLocalizedDescriptionKey: description]
|
||||
if let message = message {
|
||||
|
||||
@@ -1,9 +1,30 @@
|
||||
/// An SQL function or aggregate.
|
||||
/// A custom SQL function or aggregate.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a Custom SQL Function or Aggregate
|
||||
///
|
||||
/// - ``init(_:argumentCount:pure:function:)``
|
||||
/// - ``init(_:argumentCount:pure:aggregate:)``
|
||||
/// - ``DatabaseAggregate``
|
||||
///
|
||||
/// ### Calling an SQL Function or Aggregate
|
||||
///
|
||||
/// - ``callAsFunction(_:)``
|
||||
///
|
||||
/// ### Built-in Functions
|
||||
///
|
||||
/// - ``capitalize``
|
||||
/// - ``localizedCapitalize``
|
||||
/// - ``localizedLowercase``
|
||||
/// - ``localizedUppercase``
|
||||
/// - ``lowercase``
|
||||
/// - ``uppercase``
|
||||
public final class DatabaseFunction: Hashable {
|
||||
// SQLite identifies functions by (name + argument count)
|
||||
private struct Identity: Hashable {
|
||||
let name: String
|
||||
let nArg: Int32 // -1 for variadic functions
|
||||
let nArg: CInt // -1 for variadic functions
|
||||
}
|
||||
|
||||
/// The name of the SQL function
|
||||
@@ -11,20 +32,29 @@ public final class DatabaseFunction: Hashable {
|
||||
private let identity: Identity
|
||||
let pure: Bool
|
||||
private let kind: Kind
|
||||
private var eTextRep: Int32 { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
private var eTextRep: CInt { (SQLITE_UTF8 | (pure ? SQLITE_DETERMINISTIC : 0)) }
|
||||
|
||||
/// Creates an SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int + 1
|
||||
/// ```swift
|
||||
/// let succ = DatabaseFunction("succ", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// db.add(function: fn)
|
||||
/// return int + 1
|
||||
/// }
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// try dbQueue.read { db in
|
||||
/// db.add(function: succ)
|
||||
/// try Int.fetchOne(db, sql: "SELECT succ(1)")! // 2
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Related APIs
|
||||
///
|
||||
/// - ``Database/add(function:)``
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
@@ -34,18 +64,18 @@ public final class DatabaseFunction: Hashable {
|
||||
/// only depends on its inputs. When a function is pure, SQLite has
|
||||
/// the opportunity to perform additional optimizations. Default value
|
||||
/// is false.
|
||||
/// - function: A function that takes an array of DatabaseValue
|
||||
/// arguments, and returns an optional DatabaseValueConvertible such
|
||||
/// as Int, String, NSDate, etc. The array is guaranteed to have
|
||||
/// exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// - function: A function that takes an array of ``DatabaseValue``
|
||||
/// arguments, and returns an optional ``DatabaseValueConvertible``
|
||||
/// such as `Int`, `String`, `Date`, etc. The array is guaranteed to
|
||||
/// have exactly `argumentCount` elements, provided `argumentCount` is
|
||||
/// not nil.
|
||||
public init(
|
||||
_ name: String,
|
||||
argumentCount: Int32? = nil,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
function: @escaping ([DatabaseValue]) throws -> DatabaseValueConvertible?)
|
||||
function: @escaping ([DatabaseValue]) throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.identity = Identity(name: name, nArg: argumentCount ?? -1)
|
||||
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.pure = pure
|
||||
self.kind = .function{ (argc, argv) in
|
||||
let arguments = (0..<Int(argc)).map { index in
|
||||
@@ -59,29 +89,35 @@ public final class DatabaseFunction: Hashable {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct MySum: DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
/// ```swift
|
||||
/// struct MySum: DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
///
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> DatabaseValueConvertible? {
|
||||
/// return sum
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: fn)
|
||||
/// try db.execute(sql: "CREATE TABLE test(i)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// func finalize() -> (any DatabaseValueConvertible)? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// let mySum = DatabaseFunction("mySum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: mySum)
|
||||
/// try db.execute(sql: "CREATE TABLE test(i)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, sql: "SELECT mySum(i) FROM test")! // 3
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Related APIs
|
||||
///
|
||||
/// - ``Database/add(function:)``
|
||||
///
|
||||
/// - parameters:
|
||||
/// - name: The function name.
|
||||
@@ -91,26 +127,49 @@ public final class DatabaseFunction: Hashable {
|
||||
/// results only depends on its inputs. When an aggregate is pure,
|
||||
/// SQLite has the opportunity to perform additional optimizations.
|
||||
/// Default value is false.
|
||||
/// - aggregate: A type that implements the DatabaseAggregate protocol.
|
||||
/// For each step of the aggregation, its `step` method is called with
|
||||
/// an array of DatabaseValue arguments. The array is guaranteed to
|
||||
/// have exactly *argumentCount* elements, provided *argumentCount* is
|
||||
/// - aggregate: A type that implements the ``DatabaseAggregate``
|
||||
/// protocol. For each step of the aggregation, its
|
||||
/// ``DatabaseAggregate/step(_:)`` method is called with an array of
|
||||
/// ``DatabaseValue`` arguments. The array is guaranteed to have
|
||||
/// exactly `argumentCount` elements, provided `argumentCount` is
|
||||
/// not nil.
|
||||
public init<Aggregate: DatabaseAggregate>(
|
||||
_ name: String,
|
||||
argumentCount: Int32? = nil,
|
||||
argumentCount: Int? = nil,
|
||||
pure: Bool = false,
|
||||
aggregate: Aggregate.Type)
|
||||
{
|
||||
self.identity = Identity(name: name, nArg: argumentCount ?? -1)
|
||||
self.identity = Identity(name: name, nArg: argumentCount.map(CInt.init) ?? -1)
|
||||
self.pure = pure
|
||||
self.kind = .aggregate { Aggregate() }
|
||||
}
|
||||
|
||||
/// Returns an SQL expression that applies the function.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/#sql-functions>
|
||||
public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression {
|
||||
/// You can use a `DatabaseFunction` as a regular Swift function. It returns
|
||||
/// an SQL expression that you can use in the query interface.
|
||||
///
|
||||
/// In the example below, `square(Column("score"))` generates the
|
||||
/// `square(score)` SQL expression:
|
||||
///
|
||||
/// ```swift
|
||||
/// let square = DatabaseFunction("square", argumentCount: 1) { dbValues in
|
||||
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
|
||||
/// return nil
|
||||
/// }
|
||||
/// return int * int
|
||||
/// }
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// try dbQueue.read { db in
|
||||
/// db.add(function: square)
|
||||
///
|
||||
/// // SELECT square(score) FROM player
|
||||
/// let squaredScores = let Player
|
||||
/// .select(square(Column("score")), as: Int.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression {
|
||||
switch kind {
|
||||
case .aggregate:
|
||||
return .function(name, arguments.map(\.sqlExpression))
|
||||
@@ -166,8 +225,10 @@ public final class DatabaseFunction: Hashable {
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class FunctionDefinition {
|
||||
let compute: (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?
|
||||
init(compute: @escaping (Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?) {
|
||||
let compute: (CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?
|
||||
init(compute: @escaping (CInt, UnsafeMutablePointer<OpaquePointer?>?)
|
||||
throws -> (any DatabaseValueConvertible)?)
|
||||
{
|
||||
self.compute = compute
|
||||
}
|
||||
}
|
||||
@@ -176,17 +237,17 @@ public final class DatabaseFunction: Hashable {
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private class AggregateDefinition {
|
||||
let makeAggregate: () -> DatabaseAggregate
|
||||
init(makeAggregate: @escaping () -> DatabaseAggregate) {
|
||||
let makeAggregate: () -> any DatabaseAggregate
|
||||
init(makeAggregate: @escaping () -> any DatabaseAggregate) {
|
||||
self.makeAggregate = makeAggregate
|
||||
}
|
||||
}
|
||||
|
||||
/// The current state of an aggregate, storable in SQLite
|
||||
private class AggregateContext {
|
||||
var aggregate: DatabaseAggregate
|
||||
var aggregate: any DatabaseAggregate
|
||||
var hasErrored = false
|
||||
init(aggregate: DatabaseAggregate) {
|
||||
init(aggregate: some DatabaseAggregate) {
|
||||
self.aggregate = aggregate
|
||||
}
|
||||
}
|
||||
@@ -195,10 +256,10 @@ public final class DatabaseFunction: Hashable {
|
||||
/// See <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
private enum Kind {
|
||||
/// A regular function: SELECT f(1)
|
||||
case function((Int32, UnsafeMutablePointer<OpaquePointer?>?) throws -> DatabaseValueConvertible?)
|
||||
case function((CInt, UnsafeMutablePointer<OpaquePointer?>?) throws -> (any DatabaseValueConvertible)?)
|
||||
|
||||
/// An aggregate: SELECT f(foo) FROM bar GROUP BY baz
|
||||
case aggregate(() -> DatabaseAggregate)
|
||||
case aggregate(() -> any DatabaseAggregate)
|
||||
|
||||
/// Feeds the `pApp` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
@@ -213,7 +274,7 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
/// Feeds the `xFunc` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var xFunc: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
var xFunc: (@convention(c) (OpaquePointer?, CInt, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .function = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
let definition = Unmanaged<FunctionDefinition>
|
||||
@@ -231,7 +292,7 @@ public final class DatabaseFunction: Hashable {
|
||||
|
||||
/// Feeds the `xStep` parameter of sqlite3_create_function_v2
|
||||
/// <http://sqlite.org/capi3ref.html#sqlite3_create_function>
|
||||
var xStep: (@convention(c) (OpaquePointer?, Int32, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
var xStep: (@convention(c) (OpaquePointer?, CInt, UnsafeMutablePointer<OpaquePointer?>?) -> Void)? {
|
||||
guard case .aggregate = self else { return nil }
|
||||
return { (sqliteContext, argc, argv) in
|
||||
let aggregateContextU = DatabaseFunction.unmanagedAggregateContext(sqliteContext)
|
||||
@@ -288,7 +349,7 @@ public final class DatabaseFunction: Hashable {
|
||||
// > the same aggregate function instance, the same buffer is returned.
|
||||
let stride = MemoryLayout<Unmanaged<AggregateContext>>.stride
|
||||
let aggregateContextBufferP = UnsafeMutableRawBufferPointer(
|
||||
start: sqlite3_aggregate_context(sqliteContext, Int32(stride))!,
|
||||
start: sqlite3_aggregate_context(sqliteContext, CInt(stride))!,
|
||||
count: stride)
|
||||
|
||||
if aggregateContextBufferP.contains(where: { $0 != 0 }) {
|
||||
@@ -314,7 +375,7 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
}
|
||||
|
||||
private static func report(result: DatabaseValueConvertible?, in sqliteContext: OpaquePointer?) {
|
||||
private static func report(result: (any DatabaseValueConvertible)?, in sqliteContext: OpaquePointer?) {
|
||||
switch result?.databaseValue.storage ?? .null {
|
||||
case .null:
|
||||
sqlite3_result_null(sqliteContext)
|
||||
@@ -326,7 +387,7 @@ public final class DatabaseFunction: Hashable {
|
||||
sqlite3_result_text(sqliteContext, string, -1, SQLITE_TRANSIENT)
|
||||
case .blob(let data):
|
||||
data.withUnsafeBytes {
|
||||
sqlite3_result_blob(sqliteContext, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
|
||||
sqlite3_result_blob(sqliteContext, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -344,13 +405,11 @@ public final class DatabaseFunction: Hashable {
|
||||
}
|
||||
|
||||
extension DatabaseFunction {
|
||||
/// :nodoc:
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(identity)
|
||||
}
|
||||
|
||||
/// Two functions are equal if they share the same name and arity.
|
||||
/// :nodoc:
|
||||
public static func == (lhs: DatabaseFunction, rhs: DatabaseFunction) -> Bool {
|
||||
lhs.identity == rhs.identity
|
||||
}
|
||||
@@ -360,47 +419,53 @@ extension DatabaseFunction {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// struct MySum : DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
/// ```swift
|
||||
/// struct MySum : DatabaseAggregate {
|
||||
/// var sum: Int = 0
|
||||
///
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> DatabaseValueConvertible? {
|
||||
/// return sum
|
||||
/// mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
/// if let int = Int.fromDatabaseValue(dbValues[0]) {
|
||||
/// sum += int
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: fn)
|
||||
/// try db.execute(sql: "CREATE TABLE test(i)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// func finalize() -> (any DatabaseValueConvertible)? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// let mySum = DatabaseFunction("mySum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: mySum)
|
||||
/// try db.execute(sql: "CREATE TABLE test(i)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (1)")
|
||||
/// try db.execute(sql: "INSERT INTO test(i) VALUES (2)")
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
/// ```
|
||||
public protocol DatabaseAggregate {
|
||||
/// Creates an aggregate.
|
||||
///
|
||||
/// A new instance is created for each aggregation.
|
||||
init()
|
||||
|
||||
/// This method is called at each step of the aggregation.
|
||||
/// Updates the aggregated value for one step of the aggregation.
|
||||
///
|
||||
/// The dbValues argument contains as many values as given to the SQL
|
||||
/// aggregate function.
|
||||
/// This method is called once for each step of the aggregation.
|
||||
///
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM player
|
||||
/// The `dbValues` argument contains as many values as given to the SQL
|
||||
/// aggregate function:
|
||||
///
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM player
|
||||
/// ```sql
|
||||
/// -- One value
|
||||
/// SELECT maxLength(name) FROM player
|
||||
///
|
||||
/// This method is never called after the finalize() method has been called.
|
||||
/// -- Two values
|
||||
/// SELECT maxFullNameLength(firstName, lastName) FROM player
|
||||
/// ```
|
||||
mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
|
||||
/// Returns the final result
|
||||
func finalize() throws -> DatabaseValueConvertible?
|
||||
/// Returns the aggregated value.
|
||||
func finalize() throws -> (any DatabaseValueConvertible)?
|
||||
}
|
||||
+204
-172
@@ -4,8 +4,42 @@ import Foundation
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// A DatabasePool grants concurrent accesses to an SQLite database.
|
||||
public final class DatabasePool: DatabaseWriter {
|
||||
/// A database connection that allows concurrent accesses to an SQLite database.
|
||||
///
|
||||
/// Unless ``Configuration/readonly``, a database pool opens an SQLite database
|
||||
/// in the [WAL mode](https://sqlite.org/wal.html).
|
||||
///
|
||||
/// It creates one writer SQLite connection, and a pool of up to
|
||||
/// ``Configuration/maximumReaderCount`` read-only SQLite connections. All
|
||||
/// write accesses are executed in a serial **writer dispatch queue**. All
|
||||
/// read accesses are executed in **reader dispatch queues** (one per read-only
|
||||
/// SQLite connection).
|
||||
///
|
||||
/// A database pool inherits most of its database access methods from the
|
||||
/// ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few
|
||||
/// specific database access methods as well.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabasePool
|
||||
///
|
||||
/// - ``init(path:configuration:)``
|
||||
///
|
||||
/// ### Creating a DatabaseSnapshot
|
||||
///
|
||||
/// - ``makeSnapshot()``
|
||||
///
|
||||
/// ### Accessing the Database
|
||||
///
|
||||
/// - ``asyncConcurrentRead(_:)``
|
||||
/// - ``writeInTransaction(_:_:)``
|
||||
///
|
||||
/// ### Managing SQLite Connections
|
||||
///
|
||||
/// - ``invalidateReadOnlyConnections()``
|
||||
/// - ``releaseMemory()``
|
||||
/// - ``releaseMemoryEventually()``
|
||||
public final class DatabasePool {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
/// The pool of reader connections.
|
||||
@@ -16,7 +50,6 @@ public final class DatabasePool: DatabaseWriter {
|
||||
|
||||
// MARK: - Database Information
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
writer.configuration
|
||||
}
|
||||
@@ -28,16 +61,21 @@ public final class DatabasePool: DatabaseWriter {
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
/// Opens the SQLite database at path *path*.
|
||||
/// Opens or creates an SQLite database.
|
||||
///
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// For example:
|
||||
///
|
||||
/// Database connections get closed when the database pool gets deallocated.
|
||||
/// ```swift
|
||||
/// let dbPool = try DatabasePool(path: "/path/to/database.sqlite")
|
||||
/// ```
|
||||
///
|
||||
/// The SQLite connections are closed when the database pool
|
||||
/// gets deallocated.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - path: The path to the database file.
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
GRDBPrecondition(configuration.maximumReaderCount > 0, "configuration.maximumReaderCount must be at least 1")
|
||||
|
||||
@@ -158,10 +196,8 @@ public final class DatabasePool: DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked because of databaseSnapshotCount and readerPool
|
||||
extension DatabasePool: @unchecked Sendable { }
|
||||
#endif
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
@@ -216,20 +252,15 @@ extension DatabasePool {
|
||||
/// as much memory as possible.
|
||||
private func setupMemoryManagement() {
|
||||
let center = NotificationCenter.default
|
||||
|
||||
// Use raw notification names because of
|
||||
// FB9801372 (UIApplication.didReceiveMemoryWarningNotification should not be declared @MainActor)
|
||||
// TODO: Reuse UIApplication.didReceiveMemoryWarningNotification when possible.
|
||||
// TODO: Reuse UIApplication.didEnterBackgroundNotification when possible.
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.applicationDidReceiveMemoryWarning(_:)),
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"),
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabasePool.applicationDidEnterBackground(_:)),
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidEnterBackgroundNotification"),
|
||||
name: UIApplication.didEnterBackgroundNotification,
|
||||
object: nil)
|
||||
}
|
||||
|
||||
@@ -350,7 +381,7 @@ extension DatabasePool: DatabaseReader {
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool = readerPool else {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
return try readerPool.get { reader in
|
||||
@@ -364,7 +395,7 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool = self.readerPool else {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
return
|
||||
}
|
||||
@@ -396,7 +427,7 @@ extension DatabasePool: DatabaseReader {
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool = readerPool else {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
return try readerPool.get { reader in
|
||||
@@ -408,7 +439,7 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
public func asyncUnsafeRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool = self.readerPool else {
|
||||
guard let readerPool else {
|
||||
value(.failure(DatabaseError(resultCode: .SQLITE_MISUSE, message: "Connection is closed")))
|
||||
return
|
||||
}
|
||||
@@ -439,7 +470,7 @@ extension DatabasePool: DatabaseReader {
|
||||
if let reader = currentReader {
|
||||
return try reader.reentrantSync(value)
|
||||
} else {
|
||||
guard let readerPool = readerPool else {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
return try readerPool.get { reader in
|
||||
@@ -469,48 +500,46 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// Performs the same job as asyncConcurrentRead.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
asyncConcurrentRead(value)
|
||||
}
|
||||
|
||||
/// Asynchronously executes a read-only function in a protected
|
||||
/// dispatch queue.
|
||||
/// Performs an asynchronous read access.
|
||||
///
|
||||
/// This method must be called from a writing dispatch queue, outside of any
|
||||
/// transaction. You'll get a fatal error otherwise.
|
||||
/// This method must be called from the writer dispatch queue, outside of
|
||||
/// any transaction. You'll get a fatal error otherwise.
|
||||
///
|
||||
/// The `value` function is guaranteed to see the database in the last
|
||||
/// committed state at the moment this method is called. Eventual
|
||||
/// concurrent database updates are not visible from the function.
|
||||
///
|
||||
/// This method returns as soon as the isolation guarantees described above
|
||||
/// are established.
|
||||
/// This method returns as soon as the isolation guarantee described above
|
||||
/// has been established.
|
||||
///
|
||||
/// In the example below, the number of players is fetched concurrently with
|
||||
/// the player insertion. Yet the future is guaranteed to return zero:
|
||||
/// the player insertion. Yet it is guaranteed to be zero:
|
||||
///
|
||||
/// try writer.asyncWriteWithoutTransaction { db in
|
||||
/// // Delete all players
|
||||
/// try Player.deleteAll()
|
||||
/// ```swift
|
||||
/// try writer.asyncWriteWithoutTransaction { db in
|
||||
/// // Delete all players
|
||||
/// try Player.deleteAll()
|
||||
///
|
||||
/// // Count players concurrently
|
||||
/// writer.asyncConcurrentRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Guaranteed to be zero
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// // Count players concurrently
|
||||
/// writer.asyncConcurrentRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Guaranteed to be zero
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
///
|
||||
/// // Insert a player
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
///
|
||||
/// // Insert a player
|
||||
/// try Player(...).insert(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
public func asyncConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
// Check that we're on the writer queue...
|
||||
@@ -529,7 +558,7 @@ extension DatabasePool: DatabaseReader {
|
||||
let isolationSemaphore = DispatchSemaphore(value: 0)
|
||||
|
||||
do {
|
||||
guard let readerPool = readerPool else {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
@@ -622,7 +651,7 @@ extension DatabasePool: DatabaseReader {
|
||||
/// Returns a reader that can be used from the current dispatch queue,
|
||||
/// if any.
|
||||
private var currentReader: SerializedDatabase? {
|
||||
guard let readerPool = readerPool else {
|
||||
guard let readerPool else {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -645,89 +674,13 @@ extension DatabasePool: DatabaseReader {
|
||||
return readers.first { $0.onValidQueue }
|
||||
}
|
||||
|
||||
// MARK: - Writing in Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
// TODO: throw instead of crashing when the database is closed
|
||||
try readerPool!.barrier {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
// TODO: throw instead of crashing when the database is closed
|
||||
readerPool!.asyncBarrier {
|
||||
self.writer.sync(updates)
|
||||
}
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result.
|
||||
///
|
||||
/// If the updates throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the updates return .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the transaction
|
||||
/// has completed.
|
||||
///
|
||||
/// Eventual concurrent reads are guaranteed to not see any partial updates
|
||||
/// of the database until the transaction has completed.
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
/// wrapping transaction.
|
||||
public func writeInTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
throws
|
||||
{
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try updates(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction.
|
||||
///
|
||||
/// Eventual concurrent reads may see partial updates unless you wrap them
|
||||
/// in a transaction.
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
@@ -758,7 +711,7 @@ extension DatabasePool: DatabaseReader {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
assert(!observation.requiresWriteAccess, "Use _addWriteOnly(observation:) instead")
|
||||
@@ -773,68 +726,147 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool: DatabaseWriter {
|
||||
// MARK: - Writing in Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func writeWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
return try readerPool.barrier {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
guard let readerPool else {
|
||||
updates(.failure(DatabaseError.connectionIsClosed()))
|
||||
return
|
||||
}
|
||||
readerPool.asyncBarrier {
|
||||
self.writer.sync { updates(.success($0)) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps database operations inside a database transaction.
|
||||
///
|
||||
/// The `updates` function runs in the writer dispatch queue, serialized
|
||||
/// with all database updates.
|
||||
///
|
||||
/// If `updates` throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If it returns
|
||||
/// ``Database/TransactionCompletion/rollback``, the transaction is also
|
||||
/// rollbacked, but no error is thrown.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// try Player(name: "Barbara").insert(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - 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``.
|
||||
/// - updates: A function that updates the database.
|
||||
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
|
||||
public func writeInTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
throws
|
||||
{
|
||||
try writer.sync { db in
|
||||
try db.inTransaction(kind) {
|
||||
try updates(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func unsafeReentrantWrite<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.reentrantSync(updates)
|
||||
}
|
||||
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabasePool {
|
||||
|
||||
// MARK: - Snapshots
|
||||
|
||||
/// Creates a database snapshot.
|
||||
///
|
||||
/// The snapshot sees an unchanging database content, as it existed at the
|
||||
/// moment it was created.
|
||||
/// The returned snapshot sees an unchanging database content, as it existed
|
||||
/// at the moment it was created.
|
||||
///
|
||||
/// When you want to control the latest committed changes seen by a
|
||||
/// snapshot, create it from the pool's writer protected dispatch queue:
|
||||
/// snapshot, create it from the pool's writer dispatch queue. Compare:
|
||||
///
|
||||
/// let snapshot1 = try dbPool.write { db -> DatabaseSnapshot in
|
||||
/// ```swift
|
||||
/// let snapshot1 = try dbPool.writeWithoutTransaction { db -> DatabaseSnapshot in
|
||||
/// try Player.deleteAll()
|
||||
/// return try dbPool.makeSnapshot()
|
||||
/// }
|
||||
/// // <- Other threads may modify the database here
|
||||
/// let snapshot2 = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// try snapshot1.read { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// try snapshot2.read { db in
|
||||
/// // Could be anything
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// It is forbidden to create a snapshot from the writer dispatch queue when
|
||||
/// a transaction is opened, because it is likely a programmer error:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbPool.writeInTransaction { db in
|
||||
/// try Player.deleteAll()
|
||||
/// // fatal error: makeSnapshot() must not be called from inside a transaction
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// return .commit
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// To avoid this fatal error, create the snapshot *before* or *after*
|
||||
/// the transaction:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbPool.writeWithoutTransaction { db in
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// return try dbPool.makeSnapshot()
|
||||
/// }
|
||||
/// // <- Other threads may modify the database here
|
||||
/// let snapshot2 = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// try snapshot1.read { db in
|
||||
/// // Guaranteed to be zero
|
||||
/// try Player.fetchCount(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// try snapshot2.read { db in
|
||||
/// // Could be anything
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// It is forbidden to create a snapshot from the writer protected dispatch
|
||||
/// queue when a transaction is opened, though, because it is likely a
|
||||
/// programmer error:
|
||||
///
|
||||
/// try dbPool.write { db in
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// // fatal error: makeSnapshot() must not be called from inside a transaction
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// return .commit
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// To avoid this fatal error, create the snapshot *before* or *after* the
|
||||
/// transaction:
|
||||
///
|
||||
/// try dbPool.writeWithoutTransaction { db in
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// try Player.deleteAll()
|
||||
/// return .commit
|
||||
/// }
|
||||
///
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// }
|
||||
/// // OK
|
||||
/// let snapshot = try dbPool.makeSnapshot()
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can create as many snapshots as you need, regardless of the maximum
|
||||
/// number of reader connections in the pool.
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html>
|
||||
/// Related SQLite documentation: <https://sqlite.org/isolation.html>
|
||||
public func makeSnapshot() throws -> DatabaseSnapshot {
|
||||
// Sanity check
|
||||
if writer.onValidQueue {
|
||||
|
||||
+125
-84
@@ -4,34 +4,63 @@ import Foundation
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// A DatabaseQueue serializes access to an SQLite database.
|
||||
public final class DatabaseQueue: DatabaseWriter {
|
||||
/// A database connection that serializes accesses to an SQLite database.
|
||||
///
|
||||
/// A database queue creates one single SQLite connection. All database accesses
|
||||
/// are executed in a serial **writer dispatch queue**.
|
||||
///
|
||||
/// A database queue inherits most of its database access methods from the
|
||||
/// ``DatabaseReader`` and ``DatabaseWriter`` protocols. It defines a few
|
||||
/// specific database access methods as well.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabaseQueue
|
||||
///
|
||||
/// - ``init(configuration:)``
|
||||
/// - ``init(path:configuration:)``
|
||||
///
|
||||
/// ### Accessing the Database
|
||||
///
|
||||
/// - ``inDatabase(_:)``
|
||||
/// - ``inTransaction(_:_:)``
|
||||
///
|
||||
/// ### Managing the SQLite Connection
|
||||
///
|
||||
/// - ``releaseMemory()``
|
||||
public final class DatabaseQueue {
|
||||
private let writer: SerializedDatabase
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The database configuration
|
||||
public var configuration: Configuration {
|
||||
writer.configuration
|
||||
}
|
||||
|
||||
/// The path to the database file; it is ":memory:" for in-memory databases.
|
||||
/// The path to the database file.
|
||||
///
|
||||
/// The path is `:memory:` for in-memory databases.
|
||||
public var path: String {
|
||||
writer.path
|
||||
}
|
||||
|
||||
// MARK: - Initializers
|
||||
|
||||
/// Opens the SQLite database at path *path*.
|
||||
/// Opens or creates an SQLite database.
|
||||
///
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
/// For example:
|
||||
///
|
||||
/// Database connections get closed when the database queue gets deallocated.
|
||||
/// ```swift
|
||||
/// let dbQueue = try DatabaseQueue(path: "/path/to/database.sqlite")
|
||||
/// ```
|
||||
///
|
||||
/// The SQLite connection is closed when the database queue
|
||||
/// gets deallocated.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - path: The path to the database file.
|
||||
/// - configuration: A configuration.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
public init(path: String, configuration: Configuration = Configuration()) throws {
|
||||
writer = try SerializedDatabase(
|
||||
path: path,
|
||||
@@ -51,14 +80,12 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
|
||||
/// Opens an in-memory SQLite database.
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
///
|
||||
/// Database memory is released when the database queue gets deallocated.
|
||||
/// The database memory is released when the database queue
|
||||
/// gets deallocated.
|
||||
///
|
||||
/// - parameter configuration: A configuration.
|
||||
public init(configuration: Configuration = Configuration()) {
|
||||
// Assume SQLite always succeeds creating an in-memory database
|
||||
writer = try! SerializedDatabase(
|
||||
public init(configuration: Configuration = Configuration()) throws {
|
||||
writer = try SerializedDatabase(
|
||||
path: ":memory:",
|
||||
configuration: configuration,
|
||||
defaultLabel: "GRDB.DatabaseQueue")
|
||||
@@ -71,10 +98,6 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
// Explicit unregistration is required before OS X 10.11.
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
public func close() throws {
|
||||
try writer.sync { try $0.close() }
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
@@ -94,20 +117,15 @@ extension DatabaseQueue {
|
||||
/// as much memory as possible.
|
||||
private func setupMemoryManagement() {
|
||||
let center = NotificationCenter.default
|
||||
|
||||
// Use raw notification names because of
|
||||
// FB9801372 (UIApplication.didReceiveMemoryWarningNotification should not be declared @MainActor)
|
||||
// TODO: Reuse UIApplication.didReceiveMemoryWarningNotification when possible.
|
||||
// TODO: Reuse UIApplication.didEnterBackgroundNotification when possible.
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabaseQueue.applicationDidReceiveMemoryWarning(_:)),
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidReceiveMemoryWarningNotification"),
|
||||
name: UIApplication.didReceiveMemoryWarningNotification,
|
||||
object: nil)
|
||||
center.addObserver(
|
||||
self,
|
||||
selector: #selector(DatabaseQueue.applicationDidEnterBackground(_:)),
|
||||
name: NSNotification.Name(rawValue: "UIApplicationDidEnterBackgroundNotification"),
|
||||
name: UIApplication.didEnterBackgroundNotification,
|
||||
object: nil)
|
||||
}
|
||||
|
||||
@@ -139,7 +157,10 @@ extension DatabaseQueue {
|
||||
#endif
|
||||
}
|
||||
|
||||
extension DatabaseQueue {
|
||||
extension DatabaseQueue: DatabaseReader {
|
||||
public func close() throws {
|
||||
try writer.sync { try $0.close() }
|
||||
}
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
@@ -239,9 +260,6 @@ extension DatabaseQueue {
|
||||
})
|
||||
}
|
||||
|
||||
/// Performs the same job as asyncConcurrentRead.
|
||||
///
|
||||
/// :nodoc:
|
||||
public func spawnConcurrentRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
// Check that we're on the writer queue...
|
||||
writer.execute { db in
|
||||
@@ -264,33 +282,59 @@ extension DatabaseQueue {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
} else {
|
||||
// Observe from the writer database connection.
|
||||
return _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseQueue: DatabaseWriter {
|
||||
// MARK: - Writing in Database
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction, and returns the result.
|
||||
/// Wraps database operations inside a database transaction.
|
||||
///
|
||||
/// If the updates throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If the updates return .rollback, the transaction is
|
||||
/// also rollbacked, but no error is thrown.
|
||||
/// The `updates` function runs in the writer dispatch queue, serialized
|
||||
/// with all database updates.
|
||||
///
|
||||
/// If `updates` throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown. If it returns
|
||||
/// ``Database/TransactionCompletion/rollback``, the transaction is also
|
||||
/// rollbacked, but no error is thrown.
|
||||
///
|
||||
/// Eventual concurrent database accesses are postponed until the
|
||||
/// transaction has completed.
|
||||
/// For example:
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
///
|
||||
/// try dbQueue.writeInTransaction { db in
|
||||
/// db.execute(...)
|
||||
/// return .commit
|
||||
/// }
|
||||
/// ```swift
|
||||
/// try dbQueue.inTransaction { db in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// try Player(name: "Barbara").insert(db)
|
||||
/// return .commit
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil). If nil, the transaction
|
||||
/// type is configuration.defaultTransactionKind, which itself
|
||||
/// defaults to .deferred. See <https://www.sqlite.org/lang_transaction.html>
|
||||
/// for more information.
|
||||
/// - updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates, or by the
|
||||
/// wrapping transaction.
|
||||
/// type is the ``Configuration/defaultTransactionKind`` of the
|
||||
/// the ``configuration``.
|
||||
/// - updates: A function that updates the database.
|
||||
/// - throws: The error thrown by `updates`, or by the wrapping transaction.
|
||||
public func inTransaction(
|
||||
_ kind: Database.TransactionKind? = nil,
|
||||
_ updates: (Database) throws -> Database.TransactionCompletion)
|
||||
@@ -309,27 +353,48 @@ extension DatabaseQueue {
|
||||
}
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
public func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
writer.async { updates(.success($0)) }
|
||||
}
|
||||
|
||||
/// Synchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
///
|
||||
/// Eventual concurrent database updates are postponed until the updates
|
||||
/// are completed.
|
||||
/// This method is identical to
|
||||
/// ``DatabaseWriter/writeWithoutTransaction(_:)-4qh1w``
|
||||
///
|
||||
/// Eventual concurrent reads may see partial updates unless you wrap them
|
||||
/// in a transaction.
|
||||
/// For example:
|
||||
///
|
||||
/// This method is *not* reentrant.
|
||||
/// ```swift
|
||||
/// let newPlayerCount = try dbQueue.inDatabase { db in
|
||||
/// try Player(name: "Arthur").insert(db)
|
||||
/// return try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
/// 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`.
|
||||
public func inDatabase<T>(_ updates: (Database) throws -> T) rethrows -> T {
|
||||
try writer.sync(updates)
|
||||
}
|
||||
@@ -341,28 +406,4 @@ extension DatabaseQueue {
|
||||
public func asyncWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
writer.async(updates)
|
||||
}
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
return _addReadOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
} else {
|
||||
// Observe from the writer database connection.
|
||||
return _addWriteOnly(
|
||||
observation: observation,
|
||||
scheduling: scheduler,
|
||||
onChange: onChange)
|
||||
}
|
||||
}
|
||||
}
|
||||
+308
-297
@@ -3,273 +3,302 @@ import Combine
|
||||
#endif
|
||||
import Dispatch
|
||||
|
||||
/// `DatabaseReader` is the protocol for all types that can fetch values from
|
||||
/// an SQLite database.
|
||||
/// The protocol for types that read from an SQLite database.
|
||||
///
|
||||
/// It is adopted by `DatabaseQueue`, `DatabasePool`, and `DatabaseSnapshot`.
|
||||
/// Do not declare new conformances to `DatabaseReader`. Only the
|
||||
/// ``DatabaseQueue``, ``DatabasePool``, and ``DatabaseSnapshot`` types are
|
||||
/// valid conforming types.
|
||||
///
|
||||
/// The protocol comes with isolation guarantees that describe the behavior of
|
||||
/// adopting types in a multithreaded application.
|
||||
///
|
||||
/// Types that adopt the protocol can provide in practice stronger guarantees.
|
||||
/// For example, `DatabaseQueue` provides a stronger isolation level
|
||||
/// than `DatabasePool`.
|
||||
/// ## Topics
|
||||
///
|
||||
/// **Warning**: Isolation guarantees stand as long as there is no external
|
||||
/// connection to the database. Should you have to cope with external
|
||||
/// connections, protect yourself with transactions, and be ready to setup a
|
||||
/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html).
|
||||
public protocol DatabaseReader: AnyObject, GRDBSendable {
|
||||
/// ### Database Information
|
||||
///
|
||||
/// - ``configuration``
|
||||
///
|
||||
/// ### Reading from the Database
|
||||
///
|
||||
/// - ``asyncRead(_:)``
|
||||
/// - ``read(_:)-3806d``
|
||||
/// - ``read(_:)-4w6gy``
|
||||
/// - ``readPublisher(receiveOn:value:)``
|
||||
///
|
||||
/// ### Unsafe Methods
|
||||
///
|
||||
/// - ``asyncUnsafeRead(_:)``
|
||||
/// - ``unsafeRead(_:)-5i7tf``
|
||||
/// - ``unsafeRead(_:)-11mk0``
|
||||
/// - ``unsafeReentrantRead(_:)``
|
||||
///
|
||||
/// ### Other Database Operations
|
||||
///
|
||||
/// - ``backup(to:pagesPerStep:progress:)``
|
||||
/// - ``close()``
|
||||
/// - ``interrupt()``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyDatabaseReader``
|
||||
public protocol DatabaseReader: AnyObject, Sendable {
|
||||
|
||||
/// The database configuration
|
||||
/// The database configuration.
|
||||
var configuration: Configuration { get }
|
||||
|
||||
/// Closes the database connection with the `sqlite3_close()` function.
|
||||
/// Closes the database connection.
|
||||
///
|
||||
/// **Note**: You DO NOT HAVE to call this method, and you SHOULD NOT call
|
||||
/// it unless the correct execution of your program depends on precise
|
||||
/// database closing. Database connections are automatically closed when
|
||||
/// they are deinitialized, and this is sufficient for most applications.
|
||||
/// - note: You do not have to call this method, and you should not call
|
||||
/// it unless the correct execution of your program depends on precise
|
||||
/// database closing. Database connections are automatically closed when
|
||||
/// they are deinitialized, and this is sufficient for most applications.
|
||||
///
|
||||
/// If this method does not throw, then the database is properly closed, and
|
||||
/// every future database access will throw a `DatabaseError` of
|
||||
/// every future database access will throw a ``DatabaseError`` of
|
||||
/// code `SQLITE_MISUSE`.
|
||||
///
|
||||
/// Otherwise, there exists concurrent database accesses or living prepared
|
||||
/// statements that prevent the database from closing, and this method
|
||||
/// throws a `DatabaseError` of code `SQLITE_BUSY`.
|
||||
/// throws a ``DatabaseError`` of code `SQLITE_BUSY`.
|
||||
/// See <https://www.sqlite.org/c3ref/close.html> for more information.
|
||||
///
|
||||
/// After an error has been thrown, the database may still be opened, and
|
||||
/// you can keep on accessing it. It may also remain in a "zombie" state,
|
||||
/// in which case it will throw `SQLITE_MISUSE` for all future
|
||||
/// database accesses.
|
||||
///
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
func close() throws
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
/// This method causes any pending database operation to abort and return at
|
||||
/// its earliest opportunity.
|
||||
/// Causes any pending database operation to abort and return at its
|
||||
/// earliest opportunity.
|
||||
///
|
||||
/// It can be called from any thread.
|
||||
/// This method can be called from any thread.
|
||||
///
|
||||
/// A call to `interrupt()` that occurs when there are no running SQL
|
||||
/// statements is a no-op and has no effect on SQL statements that are
|
||||
/// started after `interrupt()` returns.
|
||||
///
|
||||
/// A database operation that is interrupted will throw a DatabaseError with
|
||||
/// code SQLITE_INTERRUPT. If the interrupted SQL operation is an INSERT,
|
||||
/// UPDATE, or DELETE that is inside an explicit transaction, then the
|
||||
/// entire transaction will be rolled back automatically. If the rolled back
|
||||
/// transaction was started by a transaction-wrapping method such as
|
||||
/// `DatabaseWriter.write` or `Database.inTransaction`, then all database
|
||||
/// accesses will throw a DatabaseError with code SQLITE_ABORT until the
|
||||
/// wrapping method returns.
|
||||
/// A database operation that is interrupted will throw a ``DatabaseError``
|
||||
/// with code `SQLITE_INTERRUPT`. If the interrupted SQL operation is an
|
||||
/// `INSERT`, `UPDATE`, or `DELETE` that is inside an explicit transaction,
|
||||
/// then the entire transaction will be rolled back automatically. If the
|
||||
/// rolled back transaction was started by a transaction-wrapping method
|
||||
/// such as ``DatabaseWriter/write(_:)-76inz`` or
|
||||
/// ``Database/inTransaction(_:_:)``, then all database accesses will throw
|
||||
/// a ``DatabaseError`` with code `SQLITE_ABORT` until the wrapping
|
||||
/// method returns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// // not executed:
|
||||
/// try Player(...).insert(db)
|
||||
/// } // throws SQLITE_INTERRUPT
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// // not executed:
|
||||
/// try Player(...).insert(db)
|
||||
/// } // throws SQLITE_INTERRUPT
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// try Player(...).insert(db) // throws SQLITE_ABORT
|
||||
/// } // throws SQLITE_ABORT
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// try Player(...).insert(db) // throws SQLITE_ABORT
|
||||
/// } // throws SQLITE_ABORT
|
||||
/// try dbQueue.write { db in
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// } // throws SQLITE_ABORT
|
||||
/// ```
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// } // throws SQLITE_ABORT
|
||||
/// Beware: when an application opens a transaction without a
|
||||
/// transaction-wrapping method, no `SQLITE_ABORT` error warns of
|
||||
/// aborted transactions:
|
||||
///
|
||||
/// When an application creates transaction without a transaction-wrapping
|
||||
/// method, no SQLITE_ABORT error warns of aborted transactions:
|
||||
/// ```swift
|
||||
/// try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
|
||||
/// try db.beginTransaction()
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// try Player(...).insert(db) // success
|
||||
/// try db.commit() // throws SQLITE_ERROR "cannot commit - no transaction is active"
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
|
||||
/// try db.beginTransaction()
|
||||
/// do {
|
||||
/// // interrupted:
|
||||
/// try Player(...).insert(db) // throws SQLITE_INTERRUPT
|
||||
/// } catch { }
|
||||
/// try Player(...).insert(db) // success
|
||||
/// try db.commit() // throws SQLITE_ERROR "cannot commit - no transaction is active"
|
||||
/// }
|
||||
///
|
||||
/// Both SQLITE_ABORT and SQLITE_INTERRUPT errors can be checked with the
|
||||
/// `DatabaseError.isInterruptionError` property.
|
||||
/// Both `SQLITE_ABORT` and `SQLITE_INTERRUPT` errors can be checked with the
|
||||
/// ``DatabaseError/isInterruptionError`` property.
|
||||
func interrupt()
|
||||
|
||||
// MARK: - Read From Database
|
||||
|
||||
/// Synchronously executes a read-only function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
/// Executes read-only database operations, and returns their result after
|
||||
/// they have finished executing.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let count = try reader.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let count = try reader.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `value` function runs in an isolated fashion: eventual concurrent
|
||||
/// database updates are not visible from the function:
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `player` table is modified, between the two requests, by
|
||||
/// // some other database connection or some other thread.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
/// ``DatabaseError`` with resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Now this value may be different:
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// Attempts to write in the database 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.
|
||||
///
|
||||
/// It is a programmer error to call this method from another database
|
||||
/// access method:
|
||||
/// access method. Doing so raises a "Database methods are not reentrant"
|
||||
/// fatal error at runtime.
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Raises a fatal error
|
||||
/// try reader.read { ... )
|
||||
/// }
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
/// - 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.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func read<T>(_ value: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Asynchronously executes a read-only function that accepts a
|
||||
/// database connection.
|
||||
/// Schedules read-only database operations for execution, and
|
||||
/// returns immediately.
|
||||
///
|
||||
/// The `value` function runs in an isolated fashion: eventual concurrent
|
||||
/// database updates are not visible from the function:
|
||||
/// For example:
|
||||
///
|
||||
/// reader.asyncRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `player` table is modified, between the two requests, by
|
||||
/// // some other database connection or some other thread.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // handle error
|
||||
/// }
|
||||
/// ```swift
|
||||
/// try reader.asyncRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // Handle error
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Attempts to write in the database throw a DatabaseError with
|
||||
/// resultCode `SQLITE_READONLY`.
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// - parameter value: A function that accesses the database. Its argument
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
/// ``DatabaseError`` with resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - 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<Database, Error>) -> Void)
|
||||
|
||||
/// Synchronously executes a function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
/// 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.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let count = try reader.unsafeRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let count = try reader.unsafeRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The guarantees of the `read` method are lifted:
|
||||
///
|
||||
/// the `value` function is not isolated: eventual concurrent database
|
||||
/// updates are visible from the function:
|
||||
///
|
||||
/// try reader.unsafeRead { db in
|
||||
/// // Those two values can be different, because some other
|
||||
/// // database connection or some other thread may modify the
|
||||
/// // database between the two requests.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// The `value` function is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `unsafeRead`).
|
||||
/// 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.
|
||||
///
|
||||
/// It is a programmer error to call this method from another database
|
||||
/// access method:
|
||||
/// access method. Doing so raises a "Database methods are not reentrant"
|
||||
/// fatal error at runtime.
|
||||
///
|
||||
/// try reader.read { db in
|
||||
/// // Raises a fatal error
|
||||
/// try reader.unsafeRead { ... )
|
||||
/// }
|
||||
/// - 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 `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
/// - 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.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func unsafeRead<T>(_ value: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Asynchronously executes a function that accepts a database connection.
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
///
|
||||
/// The guarantees of the `asyncRead` method are lifted:
|
||||
/// 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.
|
||||
///
|
||||
/// the `value` function is not isolated: eventual concurrent database
|
||||
/// updates are visible from the function:
|
||||
/// For example:
|
||||
///
|
||||
/// reader.asyncUnsafeRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// // Those two values can be different, because some other
|
||||
/// // database connection or some other thread may modify the
|
||||
/// // database between the two requests.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // handle error
|
||||
/// }
|
||||
/// ```swift
|
||||
/// reader.asyncUnsafeRead { dbResult in
|
||||
/// do {
|
||||
/// let db = try dbResult.get()
|
||||
/// let count = try Player.fetchCount(db)
|
||||
/// } catch {
|
||||
/// // handle error
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `value` function is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `asyncUnsafeRead`).
|
||||
/// - 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 `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
///
|
||||
/// - parameter value: A function that accesses the database. Its argument
|
||||
/// - 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<Database, Error>) -> Void)
|
||||
|
||||
/// Synchronously executes a function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
///
|
||||
/// The guarantees of the safe `read` method are lifted:
|
||||
/// 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.
|
||||
///
|
||||
/// the `value` function is not isolated: eventual concurrent database
|
||||
/// updates are visible from the function:
|
||||
/// This method can be called from other database access methods. Reentrant
|
||||
/// database accesses are discouraged, though, because they muddle
|
||||
/// transaction boundaries.
|
||||
///
|
||||
/// try reader.unsafeReentrantRead { db in
|
||||
/// // Those two values can be different, because some other
|
||||
/// // database connection or some other thread may modify the
|
||||
/// // database between the two requests.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// The `value` function is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `unsafeRead`).
|
||||
/// ```swift
|
||||
/// let count = try reader.unsafeReentrantRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This method is reentrant. It should be avoided because it fosters
|
||||
/// dangerous concurrency practices.
|
||||
/// 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 function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
/// - 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 `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.
|
||||
func unsafeReentrantRead<T>(_ value: (Database) throws -> T) throws -> T
|
||||
|
||||
|
||||
@@ -277,18 +306,16 @@ public protocol DatabaseReader: AnyObject, GRDBSendable {
|
||||
|
||||
/// Starts a value observation.
|
||||
///
|
||||
/// You should use the `ValueObservation.start(in:onError:onChange:)`
|
||||
/// Use the ``ValueObservation/start(in:scheduling:onError:onChange:)``
|
||||
/// method instead.
|
||||
///
|
||||
/// - parameter observation: the stared observation
|
||||
/// - returns: a TransactionObserver
|
||||
///
|
||||
/// :nodoc:
|
||||
/// - parameter observation: a ValueObservation.
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
}
|
||||
|
||||
extension DatabaseReader {
|
||||
@@ -306,31 +333,32 @@ extension DatabaseReader {
|
||||
///
|
||||
/// Usage:
|
||||
///
|
||||
/// let source: DatabaseQueue = ...
|
||||
/// let destination: DatabaseQueue = ...
|
||||
/// try source.backup(to: destination)
|
||||
/// ```swift
|
||||
/// let source: DatabaseQueue = ...
|
||||
/// let destination: DatabaseQueue = ...
|
||||
/// try source.backup(to: destination)
|
||||
/// ```
|
||||
///
|
||||
/// When you're after progress reporting during backup, you'll want to
|
||||
/// perform the backup in several steps. Each step copies the number of
|
||||
/// _database pages_ you specify. See <https://www.sqlite.org/c3ref/backup_finish.html>
|
||||
/// for more information:
|
||||
///
|
||||
/// // Backup with progress reporting
|
||||
/// try source.backup(
|
||||
/// to: destination,
|
||||
/// pagesPerStep: ...)
|
||||
/// { backupProgress in
|
||||
/// print("Database backup progress:", backupProgress)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// // Backup with progress reporting
|
||||
/// try source.backup(to: destination, pagesPerStep: ...) { progress in
|
||||
/// print("Database backup progress:", progress)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `progress` callback will be called at least once—when
|
||||
/// `backupProgress.isCompleted == true`. If the callback throws
|
||||
/// when `backupProgress.isCompleted == false`, the backup is aborted
|
||||
/// and the error is rethrown. If the callback throws when
|
||||
/// and the error is rethrown. If the callback throws when
|
||||
/// `backupProgress.isCompleted == true`, backup completion is
|
||||
/// unaffected and the error is silently ignored.
|
||||
///
|
||||
/// See also `Database.backup()`.
|
||||
/// See also ``Database/backup(to:pagesPerStep:progress:)``
|
||||
///
|
||||
/// - parameters:
|
||||
/// - writer: The destination database.
|
||||
@@ -338,11 +366,11 @@ extension DatabaseReader {
|
||||
/// step. By default, all pages are copied in one single step.
|
||||
/// - progress: An optional function that is notified of the backup
|
||||
/// progress.
|
||||
/// - throws: The error thrown by `progress` if the backup is abandoned, or
|
||||
/// any `DatabaseError` that would happen while performing the backup.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or the
|
||||
/// error thrown by `progress`.
|
||||
public func backup(
|
||||
to writer: DatabaseWriter,
|
||||
pagesPerStep: Int32 = -1,
|
||||
to writer: some DatabaseWriter,
|
||||
pagesPerStep: CInt = -1,
|
||||
progress: ((DatabaseBackupProgress) throws -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
@@ -356,7 +384,7 @@ extension DatabaseReader {
|
||||
|
||||
func backup(
|
||||
to destDb: Database,
|
||||
pagesPerStep: Int32 = -1,
|
||||
pagesPerStep: CInt = -1,
|
||||
afterBackupInit: (() -> Void)? = nil,
|
||||
afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil)
|
||||
throws
|
||||
@@ -371,44 +399,36 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
extension DatabaseReader {
|
||||
// MARK: - Asynchronous Database Access
|
||||
|
||||
// TODO: remove @escaping as soon as it is possible
|
||||
/// Asynchronously executes a read-only function that accepts a database
|
||||
/// connection, and returns its result.
|
||||
/// Executes read-only database operations, and returns their result after
|
||||
/// they have finished executing.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let count = try await reader.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let count = try await reader.read { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `value` function runs in an isolated fashion: eventual concurrent
|
||||
/// database updates are not visible from the function:
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// try await reader.read { db in
|
||||
/// // Those two values are guaranteed to be equal, even if the
|
||||
/// // `player` table is modified, between the two requests, by
|
||||
/// // some other database connection or some other thread.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
/// The database connection is read-only: attempts to write throw a
|
||||
/// ``DatabaseError`` with resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// try await reader.read { db in
|
||||
/// // Now this value may be different:
|
||||
/// let count = 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.
|
||||
///
|
||||
/// Attempts to write in the database throw a DatabaseError with
|
||||
/// resultCode `SQLITE_READONLY`.
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
/// - 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(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func read<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
@@ -422,36 +442,37 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: remove @escaping as soon as it is possible
|
||||
/// Asynchronously executes a function that accepts a database connection.
|
||||
/// Executes database operations, and returns their result after they have
|
||||
/// finished executing.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
/// - 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.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let count = try await reader.unsafeRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// let count = try await reader.unsafeRead { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The guarantees of the `read` method are lifted:
|
||||
/// 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.
|
||||
///
|
||||
/// the `value` function is not isolated: eventual concurrent database
|
||||
/// updates are visible from the function:
|
||||
/// - 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 `value`
|
||||
/// closure may not return the same value.
|
||||
/// - warning: Attempts to write in the database may succeed.
|
||||
///
|
||||
/// try await reader.asyncRead { db in
|
||||
/// // Those two values can be different, because some other
|
||||
/// // database connection or some other thread may modify the
|
||||
/// // database between the two requests.
|
||||
/// let count1 = try Player.fetchCount(db)
|
||||
/// let count2 = try Player.fetchCount(db)
|
||||
/// }
|
||||
///
|
||||
/// The `value` function is not prevented from writing (DatabaseQueue, in
|
||||
/// particular, will accept database modifications in `asyncUnsafeRead`).
|
||||
///
|
||||
/// - parameter value: A function that accesses the database.
|
||||
/// - throws: The error thrown by `value`, or any `DatabaseError` that would
|
||||
/// happen while establishing the read access to the database.
|
||||
/// - 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(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func unsafeRead<T>(_ value: @Sendable @escaping (Database) throws -> T) async throws -> T {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
@@ -465,47 +486,43 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if canImport(Combine)
|
||||
extension DatabaseReader {
|
||||
// MARK: - Publishing Database Values
|
||||
|
||||
/// Returns a Publisher that asynchronously completes with a fetched value.
|
||||
/// Returns a publisher that publishes one value and completes.
|
||||
///
|
||||
/// // DatabasePublishers.Read<[Player]>
|
||||
/// let players = dbQueue.readPublisher { db in
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
/// The database is not accessed until subscription. Value and completion
|
||||
/// are published on `scheduler` (the main dispatch queue by default).
|
||||
///
|
||||
/// Its value and completion are emitted on the main dispatch queue.
|
||||
/// For example:
|
||||
///
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func readPublisher<Output>(
|
||||
value: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Read<Output>
|
||||
{
|
||||
readPublisher(receiveOn: DispatchQueue.main, value: value)
|
||||
}
|
||||
|
||||
/// Returns a Publisher that asynchronously completes with a fetched value.
|
||||
/// ```swift
|
||||
/// // DatabasePublishers.Read<Int>
|
||||
/// let countPublisher = reader.readPublisher { db in
|
||||
/// try Player.fetchCount(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// // DatabasePublishers.Read<[Player]>
|
||||
/// let players = dbQueue.readPublisher(
|
||||
/// receiveOn: DispatchQueue.global(),
|
||||
/// value: { db in try Player.fetchAll(db) })
|
||||
/// Database operations are isolated in a transaction: they do not see
|
||||
/// changes performed by eventual concurrent writes (even writes performed
|
||||
/// by other processes).
|
||||
///
|
||||
/// Its value and completion are emitted on `scheduler`.
|
||||
/// 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 scheduler: A Combine Scheduler.
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func readPublisher<S, Output>(
|
||||
receiveOn scheduler: S,
|
||||
public func readPublisher<Output>(
|
||||
receiveOn scheduler: some Combine.Scheduler = DispatchQueue.main,
|
||||
value: @escaping (Database) throws -> Output)
|
||||
-> DatabasePublishers.Read<Output>
|
||||
where S: Scheduler
|
||||
{
|
||||
Deferred {
|
||||
Future { fulfill in
|
||||
@@ -521,13 +538,11 @@ extension DatabaseReader {
|
||||
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that reads a value from the database. It publishes exactly
|
||||
/// one element, or an error.
|
||||
/// A publisher that reads from the database.
|
||||
///
|
||||
/// See:
|
||||
/// `Read` publishes exactly one element, or an error.
|
||||
///
|
||||
/// - `DatabaseReader.readPublisher(receiveOn:value:)`.
|
||||
/// - `DatabaseReader.readPublisher(value:)`.
|
||||
/// You build such a publisher from ``DatabaseReader``.
|
||||
public struct Read<Output>: Publisher {
|
||||
public typealias Output = Output
|
||||
public typealias Failure = Error
|
||||
@@ -557,7 +572,7 @@ extension DatabaseReader {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
@@ -565,7 +580,7 @@ extension DatabaseReader {
|
||||
// started from a database access.
|
||||
let value = try unsafeReentrantRead { db in
|
||||
try db.isolated(readOnly: true) {
|
||||
try observation.fetchValue(db)
|
||||
try observation.fetchInitialValue(db)
|
||||
}
|
||||
}
|
||||
onChange(value)
|
||||
@@ -579,7 +594,7 @@ extension DatabaseReader {
|
||||
guard !isCancelled else { return }
|
||||
|
||||
let result = dbResult.flatMap { db in
|
||||
Result { try observation.fetchValue(db) }
|
||||
Result { try observation.fetchInitialValue(db) }
|
||||
}
|
||||
|
||||
scheduler.schedule {
|
||||
@@ -596,18 +611,21 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type-erased DatabaseReader
|
||||
/// A type-erased database reader.
|
||||
///
|
||||
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
|
||||
/// underlying database reader.
|
||||
public final class AnyDatabaseReader: DatabaseReader {
|
||||
private let base: DatabaseReader
|
||||
/// An instance of `AnyDatabaseReader` forwards its operations to an underlying
|
||||
/// base database reader.
|
||||
public final class AnyDatabaseReader {
|
||||
private let base: any DatabaseReader
|
||||
|
||||
/// Creates a database reader that wraps a base database reader.
|
||||
public init(_ base: DatabaseReader) {
|
||||
/// Creates a new database reader that wraps and forwards operations
|
||||
/// to `base`.
|
||||
public init(_ base: some DatabaseReader) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension AnyDatabaseReader: DatabaseReader {
|
||||
public var configuration: Configuration {
|
||||
base.configuration
|
||||
}
|
||||
@@ -616,14 +634,10 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
try base.close()
|
||||
}
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
public func interrupt() {
|
||||
base.interrupt()
|
||||
}
|
||||
|
||||
// MARK: - Reading from Database
|
||||
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
public func read<T>(_ value: (Database) throws -> T) throws -> T {
|
||||
try base.read(value)
|
||||
@@ -646,14 +660,11 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
try base.unsafeReentrantRead(value)
|
||||
}
|
||||
|
||||
// MARK: - Value Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
observation: observation,
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/// DatabaseRegion defines a region in the database. DatabaseRegion is dedicated
|
||||
/// to help transaction observers recognize impactful database changes in their
|
||||
/// `observes(eventsOfKind:)` and `databaseDidChange(with:)` methods.
|
||||
/// An observable region of the database.
|
||||
///
|
||||
/// A database region is the union of any number of "table regions", which can
|
||||
/// cover a full table, or the combination of columns and rows:
|
||||
/// A `DatabaseRegion` is the union of any number of "table regions", which can
|
||||
/// cover a full table, or the combination of columns and rows identified by
|
||||
/// their rowids:
|
||||
///
|
||||
/// |Table1 | |Table2 | |Table3 | |Table4 | |Table5 |
|
||||
/// |-------| |-------| |-------| |-------| |-------|
|
||||
@@ -12,24 +11,36 @@
|
||||
/// |x|x|x|x| |x| | | | | | | | | |x|x| |x| | | | | |
|
||||
/// |x|x|x|x| |x| | | | | | | | | | | | | | | | | | |
|
||||
///
|
||||
/// To create a database region, you use one of those methods:
|
||||
/// It is dedicated to help ``TransactionObserver`` types detect impactful
|
||||
/// database changes.
|
||||
///
|
||||
/// - `DatabaseRegion.fullDatabase`: the region that covers all database tables.
|
||||
/// You get `DatabaseRegion` instances from a ``DatabaseRegionConvertible``
|
||||
/// value, a prepared ``Statement``, or from the initializers described below.
|
||||
///
|
||||
/// - `DatabaseRegion()`: the empty region.
|
||||
/// ## Topics
|
||||
///
|
||||
/// - `DatabaseRegion(table:)`: the region that covers one database table.
|
||||
/// ### Creating Regions
|
||||
///
|
||||
/// - `Statement.databaseRegion`:
|
||||
/// - ``fullDatabase-3ir3p``
|
||||
/// - ``init()``
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name, score FROM player")
|
||||
/// let region = statement.databaseRegion
|
||||
/// ### Instance Properties
|
||||
///
|
||||
/// - `FetchRequest.databaseRegion(_:)`
|
||||
/// - ``isEmpty``
|
||||
/// - ``isFullDatabase``
|
||||
///
|
||||
/// let request = Player.filter(key: 1)
|
||||
/// let region = try request.databaseRegion(db)
|
||||
public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
/// ### Combining Regions
|
||||
///
|
||||
/// - ``formUnion(_:)``
|
||||
/// - ``union(_:)``
|
||||
///
|
||||
/// ### Detecting Database Changes
|
||||
///
|
||||
/// Use those methods from ``TransactionObserver`` methods.
|
||||
///
|
||||
/// - ``isModified(byEventsOfKind:)``
|
||||
/// - ``isModified(by:)``
|
||||
public struct DatabaseRegion {
|
||||
private let tableRegions: [CaseInsensitiveIdentifier: TableRegion]?
|
||||
|
||||
private init(tableRegions: [CaseInsensitiveIdentifier: TableRegion]?) {
|
||||
@@ -38,32 +49,22 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
|
||||
/// Returns whether the region is empty.
|
||||
public var isEmpty: Bool {
|
||||
guard let tableRegions = tableRegions else {
|
||||
guard let tableRegions else {
|
||||
// full database
|
||||
return false
|
||||
}
|
||||
return tableRegions.isEmpty
|
||||
}
|
||||
|
||||
/// Returns whether the region covers the full database: all columns and all
|
||||
/// rows from all tables.
|
||||
/// Returns whether the region covers the full database.
|
||||
public var isFullDatabase: Bool {
|
||||
tableRegions == nil
|
||||
}
|
||||
|
||||
/// The region that covers the full database: all columns and all rows
|
||||
/// from all tables.
|
||||
/// The region that covers the full database.
|
||||
public static let fullDatabase = DatabaseRegion(tableRegions: nil)
|
||||
|
||||
// TODO: rename to init(table:) when this initializer is no longer public
|
||||
/// The region that covers a full database table: all columns and all rows
|
||||
/// from this table.
|
||||
static func fullTable(_ table: String) -> DatabaseRegion {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
return DatabaseRegion(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Creates an empty database region.
|
||||
/// The empty database region.
|
||||
public init() {
|
||||
self.init(tableRegions: [:])
|
||||
}
|
||||
@@ -71,9 +72,9 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
/// Creates a region that spans all rows and columns of a database table.
|
||||
///
|
||||
/// - parameter table: A table name.
|
||||
@available(*, deprecated, message: "In order to specify a table region, prefer `Table(tableName)`")
|
||||
public init(table: String) {
|
||||
self = .fullTable(table)
|
||||
init(table: String) {
|
||||
let table = CaseInsensitiveIdentifier(rawValue: table)
|
||||
self.init(tableRegions: [table: TableRegion(columns: nil, rowIds: nil)])
|
||||
}
|
||||
|
||||
/// Full columns in a table: (some columns in a table) × (all rows)
|
||||
@@ -95,7 +96,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
/// this intersection. It is currently only used as support for
|
||||
/// the isModified(byEventsOfKind:) method.
|
||||
func intersection(_ other: DatabaseRegion) -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return other }
|
||||
guard let tableRegions else { return other }
|
||||
guard let otherTableRegions = other.tableRegions else { return self }
|
||||
|
||||
var tableRegionsIntersection: [CaseInsensitiveIdentifier: TableRegion] = [:]
|
||||
@@ -113,7 +114,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
|
||||
/// Only keeps those rowIds in the given table
|
||||
func tableIntersection(_ table: String, rowIds: Set<Int64>) -> DatabaseRegion {
|
||||
guard var tableRegions = tableRegions else {
|
||||
guard var tableRegions else {
|
||||
return DatabaseRegion(table: table, rowIds: rowIds)
|
||||
}
|
||||
|
||||
@@ -133,7 +134,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
|
||||
/// Returns the union of this region and the given one.
|
||||
public func union(_ other: DatabaseRegion) -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
guard let tableRegions else { return .fullDatabase }
|
||||
guard let otherTableRegions = other.tableRegions else { return .fullDatabase }
|
||||
|
||||
var tableRegionsUnion: [CaseInsensitiveIdentifier: TableRegion] = [:]
|
||||
@@ -178,7 +179,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
/// This method removes views (assuming no table exists with the same name
|
||||
/// as a view).
|
||||
private func canonicalTables(_ db: Database) throws -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
guard let tableRegions else { return .fullDatabase }
|
||||
var region = DatabaseRegion()
|
||||
for (table, tableRegion) in tableRegions {
|
||||
if let canonicalTableName = try db.canonicalTableName(table.rawValue) {
|
||||
@@ -191,7 +192,7 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
|
||||
/// Returns a region which doesn't contain any SQLite internal table.
|
||||
private func ignoringInternalSQLiteTables() -> DatabaseRegion {
|
||||
guard let tableRegions = tableRegions else { return .fullDatabase }
|
||||
guard let tableRegions else { return .fullDatabase }
|
||||
let filteredRegions = tableRegions.filter {
|
||||
!Database.isSQLiteInternalTable($0.key.rawValue)
|
||||
}
|
||||
@@ -215,7 +216,7 @@ extension DatabaseRegion {
|
||||
/// in the TransactionObserver.observes(eventsOfKind:) method, by calling
|
||||
/// region.isModified(byEventsOfKind:)
|
||||
public func isModified(by event: DatabaseEvent) -> Bool {
|
||||
guard let tableRegions = tableRegions else {
|
||||
guard let tableRegions else {
|
||||
// Full database: all changes are impactful
|
||||
return true
|
||||
}
|
||||
@@ -234,9 +235,7 @@ extension DatabaseRegion {
|
||||
}
|
||||
}
|
||||
|
||||
// Equatable
|
||||
extension DatabaseRegion {
|
||||
/// :nodoc:
|
||||
extension DatabaseRegion: Equatable {
|
||||
public static func == (lhs: DatabaseRegion, rhs: DatabaseRegion) -> Bool {
|
||||
switch (lhs.tableRegions, rhs.tableRegions) {
|
||||
case (nil, nil):
|
||||
@@ -257,11 +256,9 @@ extension DatabaseRegion {
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseRegion {
|
||||
/// :nodoc:
|
||||
extension DatabaseRegion: CustomStringConvertible {
|
||||
public var description: String {
|
||||
guard let tableRegions = tableRegions else {
|
||||
guard let tableRegions else {
|
||||
return "full database"
|
||||
}
|
||||
if tableRegions.isEmpty {
|
||||
@@ -336,7 +333,7 @@ private struct TableRegion: Equatable {
|
||||
}
|
||||
|
||||
func contains(rowID: Int64) -> Bool {
|
||||
guard let rowIds = rowIds else {
|
||||
guard let rowIds else {
|
||||
return true
|
||||
}
|
||||
return rowIds.contains(rowID)
|
||||
@@ -345,10 +342,13 @@ private struct TableRegion: Equatable {
|
||||
|
||||
// MARK: - DatabaseRegionConvertible
|
||||
|
||||
/// `DatabaseRegionConvertible` is the protocol for values that can be turned
|
||||
/// into a `DatabaseRegion`.
|
||||
/// A type that operates on a specific ``DatabaseRegion``.
|
||||
///
|
||||
/// Such values specify the region obserbed by `DatabaseRegionObservation`.
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyDatabaseRegionConvertible``
|
||||
public protocol DatabaseRegionConvertible {
|
||||
/// Returns a database region.
|
||||
///
|
||||
@@ -356,16 +356,13 @@ public protocol DatabaseRegionConvertible {
|
||||
func databaseRegion(_ db: Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
#if compiler(>=5.5)
|
||||
extension DatabaseRegionConvertible where Self == DatabaseRegion {
|
||||
/// The region that covers the full database: all columns and all rows
|
||||
/// from all tables.
|
||||
public static var fullDatabase: Self { DatabaseRegion.fullDatabase }
|
||||
}
|
||||
#endif
|
||||
|
||||
extension DatabaseRegion: DatabaseRegionConvertible {
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
self
|
||||
}
|
||||
@@ -379,11 +376,10 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
|
||||
_region = region
|
||||
}
|
||||
|
||||
public init(_ region: DatabaseRegionConvertible) {
|
||||
_region = { try region.databaseRegion($0) }
|
||||
public init(_ region: some DatabaseRegionConvertible) {
|
||||
_region = region.databaseRegion
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func databaseRegion(_ db: Database) throws -> DatabaseRegion {
|
||||
try _region(db)
|
||||
}
|
||||
@@ -398,7 +394,7 @@ extension DatabaseRegion {
|
||||
}
|
||||
}
|
||||
|
||||
static func union(_ regions: [DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion {
|
||||
static func union(_ regions: [any DatabaseRegionConvertible]) -> (Database) throws -> DatabaseRegion {
|
||||
return { db in
|
||||
try regions.reduce(into: DatabaseRegion()) { union, region in
|
||||
try union.formUnion(region.databaseRegion(db))
|
||||
|
||||
@@ -3,98 +3,153 @@ import Combine
|
||||
#endif
|
||||
import Foundation
|
||||
|
||||
/// DatabaseRegionObservation tracks changes in the results of database
|
||||
/// requests, and notifies each database transaction whenever the
|
||||
/// database changes.
|
||||
/// `DatabaseRegionObservation` tracks transactions that modify a
|
||||
/// database region.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all)
|
||||
/// let observer = try observation.start(in: dbQueue) { db: Database in
|
||||
/// print("Players have changed.")
|
||||
/// }
|
||||
/// ```swift
|
||||
/// // Track the player table
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
///
|
||||
/// let cancellable = try observation.start(in: dbQueue) { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (db: Database) in
|
||||
/// print("A modification of the player table has just been committed.")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating DatabaseRegionObservation
|
||||
///
|
||||
/// - ``init(tracking:)-5ldbe``
|
||||
/// - ``init(tracking:)-2nqjd``
|
||||
///
|
||||
/// ### Observing Database Transactions
|
||||
///
|
||||
/// - ``publisher(in:)``
|
||||
/// - ``start(in:onError:onChange:)``
|
||||
public struct DatabaseRegionObservation {
|
||||
/// The extent of the database observation. The default is
|
||||
/// `.observerLifetime`: the observation lasts until the
|
||||
/// observer returned by the `start(in:onChange:)` method
|
||||
/// is deallocated.
|
||||
public var extent: Database.TransactionObservationExtent
|
||||
|
||||
/// A closure that is evaluated when the observation starts, and returns
|
||||
/// the observed database region.
|
||||
var observedRegion: (Database) throws -> DatabaseRegion
|
||||
}
|
||||
|
||||
extension DatabaseRegionObservation {
|
||||
/// Creates a DatabaseRegionObservation which observes *regions*, and
|
||||
/// notifies whenever one of the observed regions is modified by a
|
||||
/// database transaction.
|
||||
/// Creates a `DatabaseRegionObservation` that notifies all transactions
|
||||
/// that modify one of the provided regions.
|
||||
///
|
||||
/// For example, this sample code counts the number of a times the player
|
||||
/// table is modified:
|
||||
/// For example:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
///
|
||||
/// var count = 0
|
||||
/// let observer = observation.start(in: dbQueue) { _ in
|
||||
/// count += 1
|
||||
/// print("Players have been modified \(count) times.")
|
||||
/// }
|
||||
///
|
||||
/// The observation lasts until the observer returned by `start` is
|
||||
/// deallocated. See the `extent` property for more information.
|
||||
/// ```swift
|
||||
/// // An observation that tracks the 'player' table
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
/// ```
|
||||
///
|
||||
/// - parameter regions: A list of observed regions.
|
||||
public init(tracking regions: DatabaseRegionConvertible...) {
|
||||
public init(tracking regions: any DatabaseRegionConvertible...) {
|
||||
self.init(tracking: regions)
|
||||
}
|
||||
|
||||
/// Creates a DatabaseRegionObservation which observes *regions*, and
|
||||
/// notifies whenever one of the observed regions is modified by a
|
||||
/// database transaction.
|
||||
/// Creates a `DatabaseRegionObservation` that notifies all transactions
|
||||
/// that modify one of the provided regions.
|
||||
///
|
||||
/// For example, this sample code counts the number of a times the player
|
||||
/// table is modified:
|
||||
/// For example:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: [Player.all()])
|
||||
/// ```swift
|
||||
/// // An observation that tracks the 'player' table
|
||||
/// let observation = DatabaseRegionObservation(tracking: [Player.all()])
|
||||
/// ```
|
||||
///
|
||||
/// var count = 0
|
||||
/// let observer = observation.start(in: dbQueue) { _ in
|
||||
/// count += 1
|
||||
/// print("Players have been modified \(count) times.")
|
||||
/// }
|
||||
///
|
||||
/// The observation lasts until the observer returned by `start` is
|
||||
/// deallocated. See the `extent` property for more information.
|
||||
///
|
||||
/// - parameter regions: A list of observed regions.
|
||||
public init(tracking regions: [DatabaseRegionConvertible]) {
|
||||
self.init(
|
||||
extent: .observerLifetime,
|
||||
observedRegion: DatabaseRegion.union(regions))
|
||||
/// - parameter regions: An array of observed regions.
|
||||
public init(tracking regions: [any DatabaseRegionConvertible]) {
|
||||
self.init(observedRegion: DatabaseRegion.union(regions))
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseRegionObservation {
|
||||
/// Starts the observation in the provided database writer (such as
|
||||
/// a database queue or database pool), and returns a transaction observer.
|
||||
/// The state of a started DatabaseRegionObservation
|
||||
private enum ObservationState {
|
||||
case cancelled
|
||||
case pending
|
||||
case started(DatabaseRegionObserver)
|
||||
}
|
||||
|
||||
/// Starts observing the database.
|
||||
///
|
||||
/// - parameter reader: A DatabaseWriter.
|
||||
/// - parameter onChange: A closure that is provided a database connection
|
||||
/// with write access each time the observed region has been modified.
|
||||
/// - returns: a TransactionObserver
|
||||
/// The observation lasts until the returned cancellable is cancelled
|
||||
/// or deallocated.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all())
|
||||
///
|
||||
/// let cancellable = try observation.start(in: dbQueue) { error in
|
||||
/// // handle error
|
||||
/// } onChange: { (db: Database) in
|
||||
/// print("A modification of the player table has just been committed.")
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// If this method is called from the writer dispatch queue of `writer` (see
|
||||
/// ``DatabaseWriter``), the observation starts immediately. Otherwise, it
|
||||
/// blocks the current thread until a write access can be established.
|
||||
///
|
||||
/// Both `onError` and `onChange` closures are executed in the writer
|
||||
/// dispatch queue, serialized with all database updates performed
|
||||
/// by `writer`.
|
||||
///
|
||||
/// The ``Database`` argument to `onChange` is valid only during the
|
||||
/// execution of the closure. Do not store or return the database connection
|
||||
/// for later use.
|
||||
///
|
||||
/// - parameter writer: A DatabaseWriter.
|
||||
/// - parameter onError: The closure to execute when the observation fails.
|
||||
/// - parameter onChange: The closure to execute when a transaction has
|
||||
/// modified the observed region.
|
||||
/// - returns: A DatabaseCancellable that can stop the observation.
|
||||
public func start(
|
||||
in dbWriter: DatabaseWriter,
|
||||
in writer: some DatabaseWriter,
|
||||
onError: @escaping (Error) -> Void,
|
||||
onChange: @escaping (Database) -> Void)
|
||||
throws -> TransactionObserver
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
@LockedBox var state = ObservationState.pending
|
||||
|
||||
// Use unsafeReentrantWrite so that observation can start from any
|
||||
// dispatch queue.
|
||||
return try dbWriter.unsafeReentrantWrite { db -> TransactionObserver in
|
||||
let region = try observedRegion(db).observableRegion(db)
|
||||
let observer = DatabaseRegionObserver(region: region, onChange: onChange)
|
||||
db.add(transactionObserver: observer, extent: extent)
|
||||
return observer
|
||||
writer.unsafeReentrantWrite { db in
|
||||
do {
|
||||
let region = try observedRegion(db).observableRegion(db)
|
||||
$state.update {
|
||||
let observer = DatabaseRegionObserver(region: region, onChange: {
|
||||
if case .cancelled = state {
|
||||
return
|
||||
}
|
||||
onChange($0)
|
||||
})
|
||||
|
||||
// Use the `.observerLifetime` extent so that we can cancel
|
||||
// the observation by deallocating the observer. This is
|
||||
// a simpler way to cancel the observation than waiting for
|
||||
// *another* write access in order to explicitly remove
|
||||
// the observer.
|
||||
db.add(transactionObserver: observer, extent: .observerLifetime)
|
||||
|
||||
$0 = .started(observer)
|
||||
}
|
||||
} catch {
|
||||
onError(error)
|
||||
}
|
||||
}
|
||||
|
||||
return AnyDatabaseCancellable {
|
||||
// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -104,14 +159,16 @@ extension DatabaseRegionObservation {
|
||||
extension DatabaseRegionObservation {
|
||||
// MARK: - Publishing Impactful Transactions
|
||||
|
||||
/// Returns a publisher that tracks changes in a database region.
|
||||
/// Returns a publisher that observes the database.
|
||||
///
|
||||
/// It emits database connections on a protected dispatch queue.
|
||||
/// The publisher publishes ``Database`` connections on the writer dispatch
|
||||
/// queue of `writer` (see ``DatabaseWriter``). Those connections are valid
|
||||
/// only when published. Do not store or return them for later use.
|
||||
///
|
||||
/// Error completion, if any, is only emitted, synchronously,
|
||||
/// on subscription.
|
||||
/// Do not reschedule the publisher with `receive(on:options:)` or any
|
||||
/// `Publisher` method that schedules publisher elements.
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
public func publisher(in writer: DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
|
||||
public func publisher(in writer: some DatabaseWriter) -> DatabasePublishers.DatabaseRegion {
|
||||
DatabasePublishers.DatabaseRegion(self, in: writer)
|
||||
}
|
||||
}
|
||||
@@ -153,22 +210,21 @@ private class DatabaseRegionObserver: TransactionObserver {
|
||||
#if canImport(Combine)
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension DatabasePublishers {
|
||||
/// A publisher that tracks changes in a database region.
|
||||
/// A publisher that tracks transactions that modify a database region.
|
||||
///
|
||||
/// See `DatabaseRegionObservation.publisher(in:)`.
|
||||
/// You build such a publisher from ``DatabaseRegionObservation``.
|
||||
public struct DatabaseRegion: Publisher {
|
||||
public typealias Output = Database
|
||||
public typealias Failure = Error
|
||||
|
||||
let writer: DatabaseWriter
|
||||
let writer: any DatabaseWriter
|
||||
let observation: DatabaseRegionObservation
|
||||
|
||||
init(_ observation: DatabaseRegionObservation, in writer: DatabaseWriter) {
|
||||
init(_ observation: DatabaseRegionObservation, in writer: some DatabaseWriter) {
|
||||
self.writer = writer
|
||||
self.observation = observation
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = DatabaseRegionSubscription(
|
||||
writer: writer,
|
||||
@@ -183,13 +239,13 @@ extension DatabasePublishers {
|
||||
{
|
||||
private struct WaitingForDemand {
|
||||
let downstream: Downstream
|
||||
let writer: DatabaseWriter
|
||||
let writer: any DatabaseWriter
|
||||
let observation: DatabaseRegionObservation
|
||||
}
|
||||
|
||||
private struct Observing {
|
||||
let downstream: Downstream
|
||||
let writer: DatabaseWriter // Retain writer until subscription is finished
|
||||
let writer: any DatabaseWriter // Retain writer until subscription is finished
|
||||
var remainingDemand: Subscribers.Demand
|
||||
}
|
||||
|
||||
@@ -204,14 +260,14 @@ extension DatabasePublishers {
|
||||
case finished
|
||||
}
|
||||
|
||||
// Observer is not stored in self.state because we must enter the
|
||||
// cancellable is not stored in self.state because we must enter the
|
||||
// .observing state *before* the observation starts.
|
||||
private var observer: TransactionObserver?
|
||||
private var cancellable: AnyDatabaseCancellable?
|
||||
private var state: State
|
||||
private var lock = NSRecursiveLock() // Allow re-entrancy
|
||||
|
||||
init(
|
||||
writer: DatabaseWriter,
|
||||
writer: some DatabaseWriter,
|
||||
observation: DatabaseRegionObservation,
|
||||
downstream: Downstream)
|
||||
{
|
||||
@@ -228,18 +284,14 @@ extension DatabasePublishers {
|
||||
guard demand > 0 else {
|
||||
return
|
||||
}
|
||||
do {
|
||||
state = .observing(Observing(
|
||||
downstream: info.downstream,
|
||||
writer: info.writer,
|
||||
remainingDemand: demand))
|
||||
observer = try info.observation.start(
|
||||
in: info.writer,
|
||||
onChange: { [weak self] in self?.receive($0) })
|
||||
} catch {
|
||||
state = .finished
|
||||
info.downstream.receive(completion: .failure(error))
|
||||
}
|
||||
state = .observing(Observing(
|
||||
downstream: info.downstream,
|
||||
writer: info.writer,
|
||||
remainingDemand: demand))
|
||||
cancellable = info.observation.start(
|
||||
in: info.writer,
|
||||
onError: { [weak self] in self?.receive(failure: $0) },
|
||||
onChange: { [weak self] in self?.receive($0) })
|
||||
|
||||
case var .observing(info):
|
||||
info.remainingDemand += demand
|
||||
@@ -253,7 +305,7 @@ extension DatabasePublishers {
|
||||
|
||||
func cancel() {
|
||||
lock.synchronized {
|
||||
observer = nil
|
||||
cancellable = nil
|
||||
state = .finished
|
||||
}
|
||||
}
|
||||
@@ -272,6 +324,15 @@ extension DatabasePublishers {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func receive(failure error: Error) {
|
||||
lock.synchronized {
|
||||
if case let .observing(info) = state {
|
||||
state = .finished
|
||||
info.downstream.receive(completion: .failure(error))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -21,12 +21,14 @@ struct DatabaseSchemaCache {
|
||||
}
|
||||
|
||||
var schemaInfo: SchemaInfo?
|
||||
private var tables: [String: Presence<TableInfo>] = [:]
|
||||
private var primaryKeys: [String: Presence<PrimaryKeyInfo>] = [:]
|
||||
private var columns: [String: Presence<[ColumnInfo]>] = [:]
|
||||
private var indexes: [String: Presence<[IndexInfo]>] = [:]
|
||||
private var foreignKeys: [String: Presence<[ForeignKeyInfo]>] = [:]
|
||||
|
||||
mutating func clear() {
|
||||
tables = [:]
|
||||
primaryKeys = [:]
|
||||
columns = [:]
|
||||
indexes = [:]
|
||||
@@ -34,6 +36,14 @@ struct DatabaseSchemaCache {
|
||||
schemaInfo = nil
|
||||
}
|
||||
|
||||
func table(_ table: String) -> Presence<TableInfo>? {
|
||||
tables[table]
|
||||
}
|
||||
|
||||
mutating func set(tableInfo: Presence<TableInfo>, forTable table: String) {
|
||||
tables[table] = tableInfo
|
||||
}
|
||||
|
||||
func primaryKey(_ table: String) -> Presence<PrimaryKeyInfo>? {
|
||||
primaryKeys[table]
|
||||
}
|
||||
|
||||
@@ -1,12 +1,19 @@
|
||||
import Dispatch
|
||||
|
||||
/// A DatabaseSnapshot sees an unchanging database content, as it existed at the
|
||||
/// moment it was created.
|
||||
/// A database connection that sees an unchanging database content, as it
|
||||
/// existed at the moment it was created.
|
||||
///
|
||||
/// See DatabasePool.makeSnapshot()
|
||||
/// You create instances of `DatabaseSnapshot` from a ``DatabasePool``, with
|
||||
/// ``DatabasePool/makeSnapshot()``.
|
||||
///
|
||||
/// For more information, read about "snapshot isolation" at <https://sqlite.org/isolation.html>
|
||||
public final class DatabaseSnapshot: DatabaseReader {
|
||||
/// A database snapshot creates one single SQLite connection. All database
|
||||
/// accesses are executed in a serial dispatch queue.
|
||||
///
|
||||
/// A database snapshot inherits all of its database access methods from the
|
||||
/// ``DatabaseReader`` protocol.
|
||||
///
|
||||
/// Related SQLite documentation: <https://sqlite.org/isolation.html>
|
||||
public final class DatabaseSnapshot {
|
||||
private let serializedDatabase: SerializedDatabase
|
||||
|
||||
/// The database configuration
|
||||
@@ -16,7 +23,7 @@ public final class DatabaseSnapshot: DatabaseReader {
|
||||
|
||||
init(path: String, configuration: Configuration = Configuration(), defaultLabel: String, purpose: String) throws {
|
||||
var configuration = DatabasePool.readerConfiguration(configuration)
|
||||
configuration.allowsUnsafeTransactions = true // Snaphost keeps a long-lived transaction
|
||||
configuration.allowsUnsafeTransactions = true // Snapshot keeps a long-lived transaction
|
||||
|
||||
serializedDatabase = try SerializedDatabase(
|
||||
path: path,
|
||||
@@ -45,14 +52,12 @@ public final class DatabaseSnapshot: DatabaseReader {
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension DatabaseSnapshot: DatabaseReader {
|
||||
public func close() throws {
|
||||
try serializedDatabase.sync { try $0.close() }
|
||||
}
|
||||
}
|
||||
|
||||
// DatabaseReader
|
||||
extension DatabaseSnapshot {
|
||||
|
||||
// MARK: - Interrupting Database Operations
|
||||
|
||||
@@ -84,12 +89,11 @@ extension DatabaseSnapshot {
|
||||
|
||||
// MARK: - Database Observation
|
||||
|
||||
/// :nodoc:
|
||||
public func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
_addReadOnly(
|
||||
observation: observation,
|
||||
|
||||
+117
-66
@@ -1,20 +1,69 @@
|
||||
import Foundation
|
||||
|
||||
// MARK: - DatabaseValue
|
||||
|
||||
/// DatabaseValue is the intermediate type between SQLite and your values.
|
||||
/// A value stored in a database table.
|
||||
///
|
||||
/// See <https://www.sqlite.org/datatype3.html>
|
||||
public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueConvertible, SQLSpecificExpressible {
|
||||
/// The SQLite storage
|
||||
/// To get `DatabaseValue` instances, you can:
|
||||
///
|
||||
/// - Fetch `DatabaseValue` from a ``Database`` instace:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// let dbValue = try DatabaseValue.fetchOne(db, sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Extract `DatabaseValue` from a database ``Row``:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read { db in
|
||||
/// if let row = try Row.fetchOne(db, sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// {
|
||||
/// let dbValue = row[0] as DatabaseValue
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - Use the ``DatabaseValueConvertible/databaseValue-1ob9k`` property on a
|
||||
/// ``DatabaseValueConvertible`` value:
|
||||
///
|
||||
/// ```swift
|
||||
/// let dbValue = DatabaseValue.null
|
||||
/// let dbValue = 1.databaseValue
|
||||
/// let dbValue = "Arthur".databaseValue
|
||||
/// let dbValue = Date().databaseValue
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html>
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating a DatabaseValue
|
||||
///
|
||||
/// - ``init(value:)``
|
||||
/// - ``null``
|
||||
///
|
||||
/// ### Accessing the SQLite storage
|
||||
///
|
||||
/// - ``isNull``
|
||||
/// - ``storage-swift.property``
|
||||
/// - ``Storage-swift.enum``
|
||||
public struct DatabaseValue: Hashable {
|
||||
/// The SQLite storage.
|
||||
public let storage: Storage
|
||||
|
||||
/// The NULL DatabaseValue.
|
||||
public static let null = DatabaseValue(storage: .null)
|
||||
|
||||
/// An SQLite storage (NULL, INTEGER, REAL, TEXT, BLOB).
|
||||
/// A value stored in a database table, with its exact SQLite storage
|
||||
/// (NULL, INTEGER, REAL, TEXT, BLOB).
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/datatype3.html#storage_classes_and_datatypes>
|
||||
@frozen
|
||||
public enum Storage: Equatable {
|
||||
public enum Storage {
|
||||
/// The NULL storage class.
|
||||
case null
|
||||
|
||||
@@ -30,8 +79,8 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
/// The BLOB storage class, wrapping Data.
|
||||
case blob(Data)
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil.
|
||||
public var value: DatabaseValueConvertible? {
|
||||
/// Returns `Int64`, `Double`, `String`, `Data` or nil.
|
||||
public var value: (any DatabaseValueConvertible)? {
|
||||
switch self {
|
||||
case .null:
|
||||
return nil
|
||||
@@ -45,29 +94,13 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
return data
|
||||
}
|
||||
}
|
||||
|
||||
/// Return true if the storages are identical.
|
||||
///
|
||||
/// Unlike DatabaseValue equality that considers the integer 1 to be
|
||||
/// equal to the 1.0 double (as SQLite does), int64 and double storages
|
||||
/// are never equal.
|
||||
public static func == (_ lhs: Storage, _ rhs: Storage) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.null, .null): return true
|
||||
case let (.int64(lhs), .int64(rhs)): return lhs == rhs
|
||||
case let (.double(lhs), .double(rhs)): return lhs == rhs
|
||||
case let (.string(lhs), .string(rhs)): return lhs == rhs
|
||||
case let (.blob(lhs), .blob(rhs)): return lhs == rhs
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a DatabaseValue from Any.
|
||||
/// Creates a `DatabaseValue` from any value.
|
||||
///
|
||||
/// The result is nil unless object adopts DatabaseValueConvertible.
|
||||
/// The result is nil unless `value` adopts ``DatabaseValueConvertible``.
|
||||
public init?(value: Any) {
|
||||
guard let convertible = value as? DatabaseValueConvertible else {
|
||||
guard let convertible = value as? any DatabaseValueConvertible else {
|
||||
return nil
|
||||
}
|
||||
self = convertible.databaseValue
|
||||
@@ -75,7 +108,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
|
||||
// MARK: - Extracting Value
|
||||
|
||||
/// Returns true if databaseValue is NULL.
|
||||
/// A boolean value indicating is the database value is `NULL`.
|
||||
public var isNull: Bool {
|
||||
switch storage {
|
||||
case .null:
|
||||
@@ -115,8 +148,8 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
/// Creates a `DatabaseValue` initialized from a raw SQLite statement pointer.
|
||||
init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
storage = .null
|
||||
@@ -157,51 +190,55 @@ extension DatabaseValue: StatementBinding {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue: GRDBSendable { }
|
||||
extension DatabaseValue: Sendable { }
|
||||
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked due to Foundation.Data not conforming to Sendable
|
||||
// TODO: Remove @unchecked when Foundation has been upgraded
|
||||
// @unchecked Sendable because Data is not Sendable in all target OS
|
||||
extension DatabaseValue.Storage: @unchecked Sendable { }
|
||||
#endif
|
||||
|
||||
// MARK: - Hashable & Equatable
|
||||
|
||||
// Hashable
|
||||
extension DatabaseValue {
|
||||
|
||||
/// :nodoc:
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
switch storage {
|
||||
case .null:
|
||||
hasher.combine(0)
|
||||
case .int64(let int64):
|
||||
// 1 == 1.0, hence 1 and 1.0 must have the same hash:
|
||||
hasher.combine(Double(int64))
|
||||
case .double(let double):
|
||||
hasher.combine(double)
|
||||
case .string(let string):
|
||||
hasher.combine(string)
|
||||
case .blob(let data):
|
||||
hasher.combine(data)
|
||||
extension DatabaseValue.Storage: Equatable {
|
||||
/// Return true if the storages are identical.
|
||||
///
|
||||
/// Unlike ``DatabaseValue`` equality that considers the integer 1 as
|
||||
/// equal to the 1.0 double (as SQLite does), int64 and double storages
|
||||
/// are never equal.
|
||||
public static func == (_ lhs: Self, _ rhs: Self) -> Bool {
|
||||
switch (lhs, rhs) {
|
||||
case (.null, .null): return true
|
||||
case let (.int64(lhs), .int64(rhs)): return lhs == rhs
|
||||
case let (.double(lhs), .double(rhs)): return lhs == rhs
|
||||
case let (.string(lhs), .string(rhs)): return lhs == rhs
|
||||
case let (.blob(lhs), .blob(rhs)): return lhs == rhs
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether two DatabaseValues are equal.
|
||||
}
|
||||
|
||||
extension DatabaseValue: Equatable {
|
||||
/// Returns whether two ``DatabaseValue`` are equal.
|
||||
///
|
||||
/// 1.databaseValue == "foo".databaseValue // false
|
||||
/// 1.databaseValue == 1.databaseValue // true
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// 1.databaseValue == "foo".databaseValue // false
|
||||
/// 1.databaseValue == 1.databaseValue // true
|
||||
/// ```
|
||||
///
|
||||
/// When comparing integers and doubles, the result is true if and only
|
||||
/// values are equal, and if converting one type to the other does
|
||||
/// not lose information:
|
||||
///
|
||||
/// 1.databaseValue == 1.0.databaseValue // true
|
||||
/// ```swift
|
||||
/// 1.databaseValue == 1.0.databaseValue // true
|
||||
/// ```
|
||||
///
|
||||
/// For a comparison that distinguishes integer and doubles, compare
|
||||
/// storages instead:
|
||||
///
|
||||
/// 1.databaseValue.storage == 1.0.databaseValue.storage // false
|
||||
/// ```swift
|
||||
/// 1.databaseValue.storage == 1.0.databaseValue.storage // false
|
||||
/// ```
|
||||
public static func == (lhs: DatabaseValue, rhs: DatabaseValue) -> Bool {
|
||||
switch (lhs.storage, rhs.storage) {
|
||||
case (.null, .null):
|
||||
@@ -224,8 +261,25 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
// DatabaseValueConvertible
|
||||
extension DatabaseValue {
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
switch storage {
|
||||
case .null:
|
||||
hasher.combine(0)
|
||||
case .int64(let int64):
|
||||
// 1 == 1.0, hence 1 and 1.0 must have the same hash:
|
||||
hasher.combine(Double(int64))
|
||||
case .double(let double):
|
||||
hasher.combine(double)
|
||||
case .string(let string):
|
||||
hasher.combine(string)
|
||||
case .blob(let data):
|
||||
hasher.combine(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue: DatabaseValueConvertible {
|
||||
/// Returns self
|
||||
public var databaseValue: DatabaseValue {
|
||||
self
|
||||
@@ -237,16 +291,13 @@ extension DatabaseValue {
|
||||
}
|
||||
}
|
||||
|
||||
// SQLExpressible
|
||||
extension DatabaseValue {
|
||||
extension DatabaseValue: SQLSpecificExpressible {
|
||||
public var sqlExpression: SQLExpression {
|
||||
.databaseValue(self)
|
||||
}
|
||||
}
|
||||
|
||||
// CustomStringConvertible
|
||||
extension DatabaseValue {
|
||||
/// :nodoc:
|
||||
extension DatabaseValue: CustomStringConvertible {
|
||||
public var description: String {
|
||||
switch storage {
|
||||
case .null:
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+577
-340
File diff suppressed because it is too large.
Load diff
+113
-47
@@ -1,37 +1,82 @@
|
||||
// MARK: - FetchRequest
|
||||
|
||||
/// The protocol for all requests that fetch database rows, and tell how those
|
||||
/// rows should be interpreted.
|
||||
/// A type that fetches and decodes database rows.
|
||||
///
|
||||
/// struct Player: FetchableRecord { ... }
|
||||
/// let request: ... // Some FetchRequest that fetches Player
|
||||
/// try request.fetchCursor(db) // Cursor of Player
|
||||
/// try request.fetchAll(db) // [Player]
|
||||
/// try request.fetchSet(db) // Set<Player>
|
||||
/// try request.fetchOne(db) // Player?
|
||||
/// try request.fetchCount(db) // Int
|
||||
public protocol FetchRequest: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Counting the Results
|
||||
///
|
||||
/// - ``fetchCount(_:)``
|
||||
///
|
||||
/// ### Fetching Database Rows
|
||||
///
|
||||
/// - ``fetchCursor(_:)-9283d``
|
||||
/// - ``fetchAll(_:)-7p809``
|
||||
/// - ``fetchOne(_:)-9fafl``
|
||||
/// - ``fetchSet(_:)-6bdrd``
|
||||
///
|
||||
/// ### Fetching Database Values
|
||||
///
|
||||
/// - ``fetchCursor(_:)-19f5g``
|
||||
/// - ``fetchCursor(_:)-66xoi``
|
||||
/// - ``fetchAll(_:)-1loau``
|
||||
/// - ``fetchAll(_:)-28pne``
|
||||
/// - ``fetchOne(_:)-44mvv``
|
||||
/// - ``fetchOne(_:)-5hlkf``
|
||||
/// - ``fetchSet(_:)-4hhtm``
|
||||
/// - ``fetchSet(_:)-9wshm``
|
||||
///
|
||||
/// ### Fetching Records
|
||||
///
|
||||
/// - ``fetchCursor(_:)-2ah3q``
|
||||
/// - ``fetchAll(_:)-vdos``
|
||||
/// - ``fetchOne(_:)-2bq0k``
|
||||
/// - ``fetchSet(_:)-4jdrq``
|
||||
///
|
||||
/// ### Preparing Database Requests
|
||||
///
|
||||
/// - ``makePreparedRequest(_:forSingleResult:)``
|
||||
/// - ``PreparedRequest``
|
||||
///
|
||||
/// ### Database Observation Support
|
||||
///
|
||||
/// - ``databaseRegion(_:)``
|
||||
///
|
||||
/// ### Adapting the Fetched Rows
|
||||
///
|
||||
/// - ``adapted(_:)``
|
||||
/// - ``AdaptedFetchRequest``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``AnyFetchRequest``
|
||||
public protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
/// Returns a PreparedRequest that is ready to be executed.
|
||||
/// Returns a ``PreparedRequest``.
|
||||
///
|
||||
/// The `singleResult` argument is a hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use it to optimize the
|
||||
/// prepared statement, for example by adding a `LIMIT 1` SQL clause:
|
||||
///
|
||||
/// ```swift
|
||||
/// // Calls makePreparedRequest(db, forSingleResult: true)
|
||||
/// try request.fetchOne(db)
|
||||
///
|
||||
/// // Calls makePreparedRequest(db, forSingleResult: false)
|
||||
/// try request.fetchAll(db)
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter singleResult: A hint that a single result row will be
|
||||
/// consumed. Implementations can optionally use it to optimize the
|
||||
/// prepared statement, for example by adding a `LIMIT 1` SQL clause.
|
||||
///
|
||||
/// // Calls makePreparedRequest(db, forSingleResult: true)
|
||||
/// try request.fetchOne(db)
|
||||
///
|
||||
/// // Calls makePreparedRequest(db, forSingleResult: false)
|
||||
/// try request.fetchAll(db)
|
||||
/// - returns: A prepared request.
|
||||
/// consumed.
|
||||
func makePreparedRequest(_ db: Database, forSingleResult singleResult: Bool) throws -> PreparedRequest
|
||||
|
||||
/// Returns the number of rows fetched by the request.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
func fetchCount(_ db: Database) throws -> Int
|
||||
}
|
||||
|
||||
@@ -46,20 +91,20 @@ extension FetchRequest {
|
||||
|
||||
// MARK: - PreparedRequest
|
||||
|
||||
/// A PreparedRequest is a request that is ready to be executed.
|
||||
/// A `PreparedRequest` is a request that is ready to be executed.
|
||||
public struct PreparedRequest {
|
||||
/// A prepared statement
|
||||
/// A prepared statement with bound parameters.
|
||||
public var statement: Statement
|
||||
|
||||
/// An eventual adapter for rows fetched by the select statement
|
||||
public var adapter: RowAdapter?
|
||||
/// An eventual adapter for rows fetched by the select statement.
|
||||
public var adapter: (any RowAdapter)?
|
||||
|
||||
/// Support for eager loading of hasMany associations.
|
||||
var supplementaryFetch: ((Database, [Row]) throws -> Void)?
|
||||
|
||||
init(
|
||||
statement: Statement,
|
||||
adapter: RowAdapter?,
|
||||
adapter: (any RowAdapter)?,
|
||||
supplementaryFetch: ((Database, [Row]) throws -> Void)? = nil)
|
||||
{
|
||||
self.statement = statement
|
||||
@@ -74,28 +119,40 @@ extension PreparedRequest: Refinable { }
|
||||
|
||||
extension FetchRequest {
|
||||
/// Returns an adapted request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
///
|
||||
/// The returned request performs an identical database query, but adapts
|
||||
/// the fetched rows. See ``RowAdapter``.
|
||||
///
|
||||
/// - parameter adapter: A closure that accepts a database connection and
|
||||
/// returns a row adapter.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
AdaptedFetchRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
|
||||
/// An adapted request.
|
||||
public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
///
|
||||
/// See ``FetchRequest/adapted(_:)``.
|
||||
public struct AdaptedFetchRequest<Base: FetchRequest> {
|
||||
let base: Base
|
||||
let adapter: (Database) throws -> RowAdapter
|
||||
let adapter: (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 -> RowAdapter) {
|
||||
init(_ base: Base, _ adapter: @escaping (Database) throws -> any RowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension AdaptedFetchRequest: SQLSubqueryable {
|
||||
public var sqlSubquery: SQLSubquery {
|
||||
base.sqlSubquery
|
||||
}
|
||||
}
|
||||
|
||||
extension AdaptedFetchRequest: FetchRequest {
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try base.fetchCount(db)
|
||||
@@ -124,21 +181,39 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
///
|
||||
/// An `AnyFetchRequest` forwards its operations to an underlying request,
|
||||
/// hiding its specifics.
|
||||
public struct AnyFetchRequest<RowDecoder>: FetchRequest {
|
||||
public struct AnyFetchRequest<RowDecoder> {
|
||||
private let request: FetchRequestEraser
|
||||
|
||||
/// Creates a request bound to type RowDecoder.
|
||||
/// Returns a request that performs an identical database query, but decodes
|
||||
/// database rows with `type`.
|
||||
///
|
||||
/// - parameter type: The fetched type RowDecoder
|
||||
/// - returns: A request bound to type RowDecoder.
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // AnyFetchRequest<Player>
|
||||
/// let playerRequest = AnyFetchRequest(Player.all())
|
||||
///
|
||||
/// // AnyFetchRequest<Row>
|
||||
/// let rowRequest = playerRequest.asRequest(of: Row.self)
|
||||
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> AnyFetchRequest<RowDecoder> {
|
||||
AnyFetchRequest<RowDecoder>(request: request)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension AnyFetchRequest {
|
||||
/// Creates a request that wraps and forwards operations to `request`.
|
||||
public init(_ request: some FetchRequest<RowDecoder>) {
|
||||
self.init(request: ConcreteFetchRequestEraser(request: request))
|
||||
}
|
||||
}
|
||||
|
||||
extension AnyFetchRequest: SQLSubqueryable {
|
||||
public var sqlSubquery: SQLSubquery {
|
||||
request.sqlSubquery
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extension AnyFetchRequest: FetchRequest {
|
||||
public func fetchCount(_ db: Database) throws -> Int {
|
||||
try request.fetchCount(db)
|
||||
}
|
||||
@@ -152,15 +227,6 @@ public struct AnyFetchRequest<RowDecoder>: FetchRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension AnyFetchRequest {
|
||||
/// Creates a request that wraps and forwards operations to `request`.
|
||||
public init<Request: FetchRequest>(_ request: Request)
|
||||
where Request.RowDecoder == RowDecoder
|
||||
{
|
||||
self.init(request: ConcreteFetchRequestEraser(request: request))
|
||||
}
|
||||
}
|
||||
|
||||
// Class-based type erasure, so that we preserve full type information.
|
||||
private class FetchRequestEraser: FetchRequest {
|
||||
typealias RowDecoder = Void
|
||||
|
||||
+1075
-877
File diff suppressed because it is too large.
Load diff
+75
-96
@@ -5,20 +5,22 @@ import Foundation
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let sql = "SELECT 1, 2,3,4, 5,6, 7,8"
|
||||
/// // <.><. . .><. .><. .>
|
||||
/// let adapters = splittingRowAdapters([1, 3, 2])
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "a": adapters[0],
|
||||
/// "b": adapters[1],
|
||||
/// "c": adapters[2],
|
||||
/// "d": adapters[3]])
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// row.scopes["a"] // [1]
|
||||
/// row.scopes["b"] // [2, 3, 4]
|
||||
/// row.scopes["c"] // [5, 6]
|
||||
/// row.scopes["d"] // [7, 8]
|
||||
public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] {
|
||||
/// ```swift
|
||||
/// let sql = "SELECT 1, 2,3,4, 5,6, 7,8"
|
||||
/// // <.><. . .><. .><. .>
|
||||
/// let adapters = splittingRowAdapters([1, 3, 2])
|
||||
/// let adapter = ScopeAdapter([
|
||||
/// "a": adapters[0],
|
||||
/// "b": adapters[1],
|
||||
/// "c": adapters[2],
|
||||
/// "d": adapters[3]])
|
||||
/// let row = try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// row.scopes["a"] // [1]
|
||||
/// row.scopes["b"] // [2, 3, 4]
|
||||
/// row.scopes["c"] // [5, 6]
|
||||
/// row.scopes["d"] // [7, 8]
|
||||
/// ```
|
||||
public func splittingRowAdapters(columnCounts: [Int]) -> [any RowAdapter] {
|
||||
guard !columnCounts.isEmpty else {
|
||||
// Identity adapter
|
||||
return [SuffixRowAdapter(fromIndex: 0)]
|
||||
@@ -41,8 +43,6 @@ public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] {
|
||||
}
|
||||
|
||||
/// _LayoutedColumnMapping is a type that supports the RowAdapter protocol.
|
||||
///
|
||||
/// :nodoc:
|
||||
public struct _LayoutedColumnMapping {
|
||||
/// An array of (baseIndex, mappedName) pairs, where baseIndex is the index
|
||||
/// of a column in a base row, and mappedName the mapped name of
|
||||
@@ -66,14 +66,16 @@ public struct _LayoutedColumnMapping {
|
||||
/// Use it in your custom RowAdapter type:
|
||||
///
|
||||
/// struct FooBarAdapter : RowAdapter {
|
||||
/// func layoutAdapter(layout: _RowLayout) throws -> _LayoutedRowAdapter {
|
||||
/// func layoutAdapter(layout: _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
/// return _LayoutedColumnMapping(layoutColumns: [(1, "foo"), (2, "bar")])
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // [foo:"foo" bar: "bar"]
|
||||
/// try Row.fetchOne(db, sql: "SELECT NULL, 'foo', 'bar'", adapter: FooBarAdapter())
|
||||
init<S: Sequence>(layoutColumns: S) where S.Iterator.Element == (Int, String) {
|
||||
init<S>(layoutColumns: S)
|
||||
where S: Sequence, S.Element == (Int, String)
|
||||
{
|
||||
self._layoutColumns = Array(layoutColumns)
|
||||
self.lowercaseColumnIndexes = Dictionary(
|
||||
layoutColumns
|
||||
@@ -91,16 +93,14 @@ public struct _LayoutedColumnMapping {
|
||||
}
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
extension _LayoutedColumnMapping: _LayoutedRowAdapter {
|
||||
/// Returns self.
|
||||
public var _mapping: _LayoutedColumnMapping { self }
|
||||
|
||||
/// Returns the empty dictionary.
|
||||
public var _scopes: [String: _LayoutedRowAdapter] { [:] }
|
||||
public var _scopes: [String: any _LayoutedRowAdapter] { [:] }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
extension _LayoutedColumnMapping: _RowLayout {
|
||||
/// Returns the index of the leftmost column named `name`, in a
|
||||
/// case-insensitive way.
|
||||
@@ -116,21 +116,17 @@ extension _LayoutedColumnMapping: _RowLayout {
|
||||
///
|
||||
/// GRBD ships with a ready-made type that adopts this protocol:
|
||||
/// `_LayoutedColumnMapping`.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _LayoutedRowAdapter {
|
||||
/// A LayoutedColumnMapping that defines how to map a column name to a
|
||||
/// column in a base row.
|
||||
var _mapping: _LayoutedColumnMapping { get }
|
||||
|
||||
/// The layouted row adapters for each scope.
|
||||
var _scopes: [String: _LayoutedRowAdapter] { get }
|
||||
var _scopes: [String: any _LayoutedRowAdapter] { get }
|
||||
}
|
||||
|
||||
/// `_RowLayout` is a protocol that supports the `RowAdapter` protocol. It
|
||||
/// describes the layout of a base row.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _RowLayout {
|
||||
/// An array of (baseIndex, name) pairs, where baseIndex is the index
|
||||
/// of a column in a base row, and name the name of that column.
|
||||
@@ -142,21 +138,45 @@ public protocol _RowLayout {
|
||||
}
|
||||
|
||||
extension Statement: _RowLayout {
|
||||
/// :nodoc:
|
||||
public var _layoutColumns: [(Int, String)] {
|
||||
Array(columnNames.enumerated())
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutIndex(ofColumn name: String) -> Int? {
|
||||
index(ofColumn: name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Implementation details of `RowAdapter`.
|
||||
/// A type that helps two incompatible row interfaces working together.
|
||||
///
|
||||
/// :nodoc:
|
||||
public protocol _RowAdapter {
|
||||
/// You provide row adapters to methods that fetch. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// try dbQueue.read {
|
||||
/// // An adapter that ignores the first two columns
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
///
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Splitting a Row
|
||||
///
|
||||
/// - ``splittingRowAdapters(columnCounts:)``
|
||||
///
|
||||
/// ### Built-in Adapters
|
||||
///
|
||||
/// - ``ColumnMapping``
|
||||
/// - ``EmptyRowAdapter``
|
||||
/// - ``RangeRowAdapter``
|
||||
/// - ``RenameColumnAdapter``
|
||||
/// - ``ScopeAdapter``
|
||||
/// - ``SuffixRowAdapter``
|
||||
public protocol RowAdapter {
|
||||
/// You never call this method directly. It is called for you whenever an
|
||||
/// adapter has to be applied.
|
||||
///
|
||||
@@ -169,37 +189,16 @@ public protocol _RowAdapter {
|
||||
/// // column named "foo" whose value is the leftmost value of the
|
||||
/// // base row.
|
||||
/// struct FirstColumnAdapter : RowAdapter {
|
||||
/// func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter {
|
||||
/// func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
/// return _LayoutedColumnMapping(layoutColumns: [(0, "foo")])
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // [foo:1]
|
||||
/// try Row.fetchOne(db, sql: "SELECT 1, 2, 3", adapter: FirstColumnAdapter())
|
||||
func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter
|
||||
func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter
|
||||
}
|
||||
|
||||
/// `RowAdapter` is a protocol that helps two incompatible row interfaces
|
||||
/// working together.
|
||||
///
|
||||
/// GRDB ships with four concrete types that adopt the RowAdapter protocol:
|
||||
///
|
||||
/// - `ColumnMapping`: renames row columns
|
||||
/// - `EmptyRowAdapter`: hides all columns
|
||||
/// - `RangeRowAdapter`: exposes a range of columns
|
||||
/// - `RenameColumnAdapter`: transforms column names with a function
|
||||
/// - `ScopeAdapter`: defines row scopes
|
||||
/// - `SuffixRowAdapter`: hides the first columns of a row
|
||||
///
|
||||
/// To use a row adapter, provide it to any method that fetches:
|
||||
///
|
||||
/// let adapter = SuffixRowAdapter(fromIndex: 2)
|
||||
/// let sql = "SELECT 1 AS foo, 2 AS bar, 3 AS baz"
|
||||
///
|
||||
/// // [baz:3]
|
||||
/// try Row.fetchOne(db, sql: sql, adapter: adapter)
|
||||
public protocol RowAdapter: _RowAdapter { }
|
||||
|
||||
extension RowAdapter {
|
||||
/// Returns an adapter based on self, with added scopes.
|
||||
///
|
||||
@@ -208,7 +207,7 @@ extension RowAdapter {
|
||||
///
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public func addingScopes(_ scopes: [String: RowAdapter]) -> RowAdapter {
|
||||
public func addingScopes(_ scopes: [String: any RowAdapter]) -> any RowAdapter {
|
||||
if scopes.isEmpty {
|
||||
return self
|
||||
} else {
|
||||
@@ -218,7 +217,7 @@ extension RowAdapter {
|
||||
}
|
||||
|
||||
extension RowAdapter {
|
||||
func baseColumnIndex(atIndex index: Int, layout: _RowLayout) throws -> Int {
|
||||
func baseColumnIndex(atIndex index: Int, layout: some _RowLayout) throws -> Int {
|
||||
try _layoutedAdapter(from: layout)._mapping.baseColumnIndex(atMappingIndex: index)
|
||||
}
|
||||
}
|
||||
@@ -228,8 +227,7 @@ public struct EmptyRowAdapter: RowAdapter {
|
||||
/// Creates an EmptyRowAdapter
|
||||
public init() { }
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter {
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
_LayoutedColumnMapping(layoutColumns: [])
|
||||
}
|
||||
}
|
||||
@@ -251,8 +249,7 @@ public struct ColumnMapping: RowAdapter {
|
||||
self.mapping = mapping
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter {
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
let layoutColumns = try mapping
|
||||
.map { (mappedColumn, baseColumn) -> (Int, String) in
|
||||
guard let index = layout._layoutIndex(ofColumn: baseColumn) else {
|
||||
@@ -292,8 +289,7 @@ public struct SuffixRowAdapter: RowAdapter {
|
||||
self.index = index
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter {
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
_LayoutedColumnMapping(layoutColumns: layout._layoutColumns.suffix(from: index))
|
||||
}
|
||||
}
|
||||
@@ -321,8 +317,7 @@ public struct RangeRowAdapter: RowAdapter {
|
||||
self.range = range.lowerBound..<(range.upperBound + 1)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter {
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
_LayoutedColumnMapping(layoutColumns: layout._layoutColumns[range])
|
||||
}
|
||||
}
|
||||
@@ -352,10 +347,10 @@ public struct RangeRowAdapter: RowAdapter {
|
||||
public struct ScopeAdapter: RowAdapter {
|
||||
|
||||
/// The base adapter
|
||||
let base: RowAdapter
|
||||
let base: any RowAdapter
|
||||
|
||||
/// The scope adapters
|
||||
let scopes: [String: RowAdapter]
|
||||
let scopes: [String: any RowAdapter]
|
||||
|
||||
/// Creates an adapter that preserves row contents and add scoped rows.
|
||||
///
|
||||
@@ -392,13 +387,12 @@ public struct ScopeAdapter: RowAdapter {
|
||||
/// row adapters.
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(base: RowAdapter, scopes: [String: RowAdapter]) {
|
||||
public init(base: some RowAdapter, scopes: [String: any RowAdapter]) {
|
||||
self.base = base
|
||||
self.scopes = scopes
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter {
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
let layoutedAdapter = try base._layoutedAdapter(from: layout)
|
||||
var layoutedScopes = layoutedAdapter._scopes
|
||||
for (name, adapter) in scopes {
|
||||
@@ -413,14 +407,14 @@ public struct ScopeAdapter: RowAdapter {
|
||||
/// The `_LayoutedRowAdapter` for `ScopeAdapter`
|
||||
struct LayoutedScopeAdapter: _LayoutedRowAdapter {
|
||||
let _mapping: _LayoutedColumnMapping
|
||||
let _scopes: [String: _LayoutedRowAdapter]
|
||||
let _scopes: [String: any _LayoutedRowAdapter]
|
||||
}
|
||||
|
||||
struct ChainedAdapter: RowAdapter {
|
||||
let first: RowAdapter
|
||||
let second: RowAdapter
|
||||
let first: any RowAdapter
|
||||
let second: any RowAdapter
|
||||
|
||||
func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter {
|
||||
func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
try second._layoutedAdapter(from: first._layoutedAdapter(from: layout)._mapping)
|
||||
}
|
||||
}
|
||||
@@ -443,8 +437,7 @@ public struct RenameColumnAdapter: RowAdapter {
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter {
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
let layoutColumns = layout._layoutColumns.map { (index, column) in (index, transform(column)) }
|
||||
return _LayoutedColumnMapping(layoutColumns: layoutColumns)
|
||||
}
|
||||
@@ -452,13 +445,13 @@ public struct RenameColumnAdapter: RowAdapter {
|
||||
|
||||
extension Row {
|
||||
/// Creates a row from a base row and a statement adapter
|
||||
convenience init(base: Row, adapter: _LayoutedRowAdapter) {
|
||||
convenience init(base: Row, adapter: some _LayoutedRowAdapter) {
|
||||
self.init(impl: AdaptedRowImpl(base: base, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns self if adapter is nil
|
||||
func adapted(with adapter: RowAdapter?, layout: _RowLayout) throws -> Row {
|
||||
guard let adapter = adapter else {
|
||||
func adapted(with adapter: (any RowAdapter)?, layout: some _RowLayout) throws -> Row {
|
||||
guard let adapter else {
|
||||
return self
|
||||
}
|
||||
return try Row(base: self, adapter: adapter._layoutedAdapter(from: layout))
|
||||
@@ -467,10 +460,10 @@ extension Row {
|
||||
|
||||
struct AdaptedRowImpl: RowImpl {
|
||||
let base: Row
|
||||
let adapter: _LayoutedRowAdapter
|
||||
let adapter: any _LayoutedRowAdapter
|
||||
let mapping: _LayoutedColumnMapping
|
||||
|
||||
init(base: Row, adapter: _LayoutedRowAdapter) {
|
||||
init(base: Row, adapter: some _LayoutedRowAdapter) {
|
||||
self.base = base
|
||||
self.adapter = adapter
|
||||
self.mapping = adapter._mapping
|
||||
@@ -503,23 +496,9 @@ struct AdaptedRowImpl: RowImpl {
|
||||
return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
func withUnsafeData<T>(atUncheckedIndex index: Int, _ body: (Data?) throws -> T) throws -> T {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return try Value.fastDecodeIfPresent(fromRow: base, atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return try base.impl.fastDecodeDataNoCopy(atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
|
||||
let mappedIndex = mapping.baseColumnIndex(atMappingIndex: index)
|
||||
return try base.impl.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: mappedIndex)
|
||||
return try base.impl.withUnsafeData(atUncheckedIndex: mappedIndex, body)
|
||||
}
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/// A key that is used to decode a value in a row
|
||||
@usableFromInline
|
||||
enum RowKey: Hashable, GRDBSendable {
|
||||
enum RowKey: Hashable, Sendable {
|
||||
/// A column name
|
||||
case columnName(String)
|
||||
|
||||
@@ -18,7 +18,7 @@ enum RowKey: Hashable, GRDBSendable {
|
||||
@usableFromInline
|
||||
enum RowDecodingError: Error {
|
||||
@usableFromInline
|
||||
struct Context: CustomDebugStringConvertible, GRDBSendable {
|
||||
struct Context: CustomDebugStringConvertible, Sendable {
|
||||
/// A description of what went wrong, for debugging purposes.
|
||||
@usableFromInline
|
||||
let debugDescription: String
|
||||
@@ -78,7 +78,7 @@ enum RowDecodingError: Error {
|
||||
static func valueMismatch(
|
||||
_ type: Any.Type,
|
||||
sqliteStatement: SQLiteStatement,
|
||||
index: Int32,
|
||||
index: CInt,
|
||||
context: RowDecodingContext)
|
||||
-> Self
|
||||
{
|
||||
@@ -99,7 +99,7 @@ enum RowDecodingError: Error {
|
||||
valueMismatch(
|
||||
type,
|
||||
context: RowDecodingContext(statement: statement, index: index),
|
||||
databaseValue: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: Int32(index)))
|
||||
databaseValue: DatabaseValue(sqliteStatement: statement.sqliteStatement, index: CInt(index)))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the `column not found: <column>`
|
||||
@@ -137,7 +137,7 @@ struct RowDecodingContext {
|
||||
} else if let sqliteStatement = row.sqliteStatement {
|
||||
self.key = key
|
||||
self.row = row.copy()
|
||||
self.sql = String(cString: sqlite3_sql(sqliteStatement)).trimmingCharacters(in: .sqlStatementSeparators)
|
||||
self.sql = String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
self.statementArguments = nil // Can't rebuild them
|
||||
} else {
|
||||
self.key = key
|
||||
|
||||
+190
-62
@@ -1,25 +1,81 @@
|
||||
/// `SQL` helps you build SQL literal with
|
||||
/// [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
/// An SQL literal.
|
||||
///
|
||||
/// For example:
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection. For example:
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// let name: String = ...
|
||||
/// let id: Int64 = ...
|
||||
/// let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
/// try db.execute(literal: query)
|
||||
/// }
|
||||
/// ```swift
|
||||
/// try dbQueue.write { db in
|
||||
/// let name: String = "O'Brien"
|
||||
/// let id: Int64 = 42
|
||||
/// let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
|
||||
///
|
||||
/// // UPDATE player SET name = 'O''Brien' WHERE id = 42
|
||||
/// try db.execute(literal: query)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating an SQL Literal from a Literal Value
|
||||
///
|
||||
/// - ``init(stringLiteral:)``
|
||||
/// - ``init(unicodeScalarLiteral:)-7p0al``
|
||||
/// - ``init(extendedGraphemeClusterLiteral:)-1oham``
|
||||
///
|
||||
/// ### Creating an SQL Literal from an Interpolation
|
||||
///
|
||||
/// - ``init(stringInterpolation:)``
|
||||
/// - ``SQLInterpolation``
|
||||
///
|
||||
/// ### Creating an SQL Literal from an SQL String
|
||||
///
|
||||
/// - ``init(sql:arguments:)``
|
||||
///
|
||||
/// ### Creating an SQL Literal from an SQL Expression
|
||||
///
|
||||
/// - ``init(_:)``
|
||||
///
|
||||
/// ### Concatenating SQL Literals
|
||||
///
|
||||
/// - ``append(literal:)``
|
||||
/// - ``append(sql:arguments:)``
|
||||
public struct SQL {
|
||||
/// `SQL` is an array of elements which can be qualified with table
|
||||
/// aliases. This is how `SQL` can blend well in the query interface.
|
||||
/// `SQL.Element` is a component of an `SQL` literal.
|
||||
///
|
||||
/// Elements can be qualified with table aliases, and this is how `SQL`
|
||||
/// blends well in the query interface. See below how the `createdAt` column
|
||||
/// is qualified with the `player` table in the generated SQL, in order to
|
||||
/// avoid any conflict with the `team.createdAt` column:
|
||||
///
|
||||
/// func date(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
/// // An SQL literal made of three elements:
|
||||
/// // - "DATE(" raw sql string
|
||||
/// // - expression
|
||||
/// // - ")" raw sql string
|
||||
/// SQL("DATE(\(value))").sqlExpression
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*, team.*
|
||||
/// // FROM player
|
||||
/// // JOIN team ON team.id = player.teamId
|
||||
/// // WHERE DATE(player.createdAt) = '2022-08-17'
|
||||
/// let request = Player
|
||||
/// .filter(date(Column("createdAt")) == "2022-08-17")
|
||||
/// .including(required: Player.team)
|
||||
enum Element {
|
||||
// Can't be qualified with a table alias
|
||||
/// A raw SQL literal with eventual arguments.
|
||||
case sql(String, StatementArguments = StatementArguments())
|
||||
// Does not need to be qualified with a table alias
|
||||
|
||||
/// A subquery.
|
||||
case subquery(SQLSubquery)
|
||||
// Cases below can be qualified with a table alias
|
||||
|
||||
/// An expression.
|
||||
case expression(SQLExpression)
|
||||
|
||||
/// A selection.
|
||||
case selection(SQLSelection)
|
||||
|
||||
/// An ordering.
|
||||
case ordering(SQLOrdering)
|
||||
|
||||
var isEmpty: Bool {
|
||||
@@ -27,6 +83,17 @@ public struct SQL {
|
||||
case let .sql(sql, _):
|
||||
return sql.isEmpty
|
||||
default:
|
||||
// Subqueries, expressions, selections and orderings are
|
||||
// assumed to be non-empty.
|
||||
//
|
||||
// Nothing prevents the user from creating an ill-formed empty
|
||||
// expression, but we don't care about such misuse:
|
||||
//
|
||||
// // An ill-formed empty expression
|
||||
// let expression = SQL("").sqlExpression
|
||||
//
|
||||
// let sql: SQL = "\(expression)"
|
||||
// sql.isEmpty // false, deal with it ¯\_(ツ)_/¯
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -54,7 +121,8 @@ public struct SQL {
|
||||
fileprivate func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .sql:
|
||||
// Can't qualify raw SQL string
|
||||
/// A raw SQL string can't be qualified with a table alias,
|
||||
/// because we can't parse it.
|
||||
return self
|
||||
case .subquery:
|
||||
// Subqueries don't need table alias
|
||||
@@ -80,9 +148,11 @@ public struct SQL {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let query = SQL(
|
||||
/// sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
/// arguments: [name, id])
|
||||
/// ```swift
|
||||
/// let query = SQL(
|
||||
/// sql: "UPDATE player SET name = ? WHERE id = ?",
|
||||
/// arguments: [name, id])
|
||||
/// ```
|
||||
public init(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self.init(elements: [.sql(sql, arguments)])
|
||||
}
|
||||
@@ -91,12 +161,14 @@ public struct SQL {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let columnLiteral = SQL(Column("username"))
|
||||
/// let suffixLiteral = SQL("@example.com".databaseValue)
|
||||
/// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ")
|
||||
/// let request = User.select(emailLiteral.sqlExpression)
|
||||
/// let emails = try String.fetchAll(db, request)
|
||||
public init(_ expression: SQLSpecificExpressible) {
|
||||
/// ```swift
|
||||
/// let columnLiteral = SQL(Column("username"))
|
||||
/// let suffixLiteral = SQL("@example.com".databaseValue)
|
||||
/// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ")
|
||||
/// let request = User.select(emailLiteral.sqlExpression)
|
||||
/// let emails = try String.fetchAll(db, request)
|
||||
/// ```
|
||||
public init(_ expression: some SQLSpecificExpressible) {
|
||||
self.init(elements: [.expression(expression.sqlExpression)])
|
||||
}
|
||||
|
||||
@@ -128,10 +200,14 @@ public struct SQL {
|
||||
extension SQL {
|
||||
/// Returns the `SQL` literal produced by the concatenation of two literals.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// let selection: SQL = "SELECT * FROM player "
|
||||
/// let condition: SQL = "WHERE name = \(name)"
|
||||
/// let query = selection + condition
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name = "O'Brien"
|
||||
/// let selection: SQL = "SELECT * FROM player "
|
||||
/// let condition: SQL = "WHERE name = \(name)"
|
||||
/// let query = selection + condition
|
||||
/// ```
|
||||
public static func + (lhs: SQL, rhs: SQL) -> SQL {
|
||||
var result = lhs
|
||||
result += rhs
|
||||
@@ -140,27 +216,39 @@ extension SQL {
|
||||
|
||||
/// Appends an `SQL` literal to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query += "WHERE name = \(name)"
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query += "WHERE name = \(name)"
|
||||
/// ```
|
||||
public static func += (lhs: inout SQL, rhs: SQL) {
|
||||
lhs.elements += rhs.elements
|
||||
}
|
||||
|
||||
/// Appends an `SQL` literal to the receiver.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query.append(literal: "WHERE name = \(name)")
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query.append(literal: "WHERE name = \(name)")
|
||||
/// ```
|
||||
public mutating func append(literal sqlLiteral: SQL) {
|
||||
self += sqlLiteral
|
||||
}
|
||||
|
||||
/// Appends a plain SQL string to the receiver, and eventual arguments.
|
||||
///
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query.append(sql: "WHERE name = ?", arguments: [name])
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let name = "O'Brien"
|
||||
/// var query: SQL = "SELECT * FROM player "
|
||||
/// query.append(sql: "WHERE name = ?", arguments: [name])
|
||||
/// ```
|
||||
public mutating func append(sql: String, arguments: StatementArguments = StatementArguments()) {
|
||||
self += SQL(sql: sql, arguments: arguments)
|
||||
}
|
||||
@@ -172,25 +260,56 @@ extension SQL: SQLSpecificExpressible {
|
||||
/// Use this property when you need an explicit `SQLExpression`.
|
||||
/// For example:
|
||||
///
|
||||
/// func date(_ value: SQLExpressible) -> SQLExpression {
|
||||
/// SQL("DATE(\(value))").sqlExpression
|
||||
/// }
|
||||
/// ```swift
|
||||
/// func date(_ value: some SQLExpressible) -> SQLExpression {
|
||||
/// SQL("DATE(\(value))").sqlExpression
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
/// let createdAt = Column("createdAt")
|
||||
/// let request = Player.filter(date(createdAt) == "2020-01-23")
|
||||
/// // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
/// let createdAt = Column("createdAt")
|
||||
/// let request = Player.filter(date(createdAt) == "2020-01-23")
|
||||
/// ```
|
||||
public var sqlExpression: SQLExpression {
|
||||
.literal(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQL: SQLSelectable {
|
||||
/// Creates a literal SQL result column.
|
||||
///
|
||||
/// Use this property when you need an explicit `SQLSelection`. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT firstName AS givenName, lastName AS familyName FROM player
|
||||
/// let selection = SQL("firstName AS givenName, lastName AS familyName").sqlSelection
|
||||
/// let request = Player.select(selection)
|
||||
/// ```
|
||||
public var sqlSelection: SQLSelection {
|
||||
.literal(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension SQL: SQLOrderingTerm {
|
||||
/// Creates a literal SQL ordering term.
|
||||
///
|
||||
/// Use this property when you need an explicit `SQLOrdering`. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT * FROM player ORDER BY name DESC
|
||||
/// let ordering = SQL("name DESC").sqlOrdering
|
||||
/// let request = Player.order(ordering)
|
||||
/// ```
|
||||
///
|
||||
/// An ordering term is only valid if it represent a single ordering terms.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Valid
|
||||
/// SQL("score DESC").sqlOrdering
|
||||
/// SQL("name").sqlOrdering
|
||||
///
|
||||
/// // Invalid
|
||||
/// SQL("score DESC, name").sqlOrdering
|
||||
/// ```
|
||||
public var sqlOrdering: SQLOrdering {
|
||||
.literal(self)
|
||||
}
|
||||
@@ -198,14 +317,20 @@ extension SQL: SQLOrderingTerm {
|
||||
|
||||
extension Sequence where Element == SQL {
|
||||
/// Returns the concatenated `SQL` literal of this sequence of literals,
|
||||
/// inserting the given separator between each element.
|
||||
/// inserting the given raw SQL separator between each element.
|
||||
///
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
/// For example:
|
||||
///
|
||||
/// ```
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
/// ```
|
||||
///
|
||||
/// - Note: The separator is a raw SQL string, not an ``SQL`` literal.
|
||||
public func joined(separator: String = "") -> SQL {
|
||||
if separator.isEmpty {
|
||||
return SQL(elements: flatMap(\.elements))
|
||||
@@ -217,14 +342,20 @@ extension Sequence where Element == SQL {
|
||||
|
||||
extension Collection where Element == SQL {
|
||||
/// Returns the concatenated `SQL` literal of this collection of literals,
|
||||
/// inserting the given SQL separator between each element.
|
||||
/// inserting the given raw SQL separator between each element.
|
||||
///
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
/// "SET name = \(name)",
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
/// ```
|
||||
///
|
||||
/// - Note: The separator is a raw SQL string, not an ``SQL`` literal.
|
||||
public func joined(separator: String = "") -> SQL {
|
||||
if separator.isEmpty {
|
||||
return SQL(elements: flatMap(\.elements))
|
||||
@@ -237,22 +368,19 @@ extension Collection where Element == SQL {
|
||||
// MARK: - ExpressibleByStringInterpolation
|
||||
|
||||
extension SQL: ExpressibleByStringInterpolation {
|
||||
/// :nodoc
|
||||
public init(unicodeScalarLiteral: String) {
|
||||
self.init(sql: unicodeScalarLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(extendedGraphemeClusterLiteral: String) {
|
||||
self.init(sql: extendedGraphemeClusterLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
|
||||
/// Creates an `SQL` literal from the given literal SQL string.
|
||||
public init(stringLiteral: String) {
|
||||
self.init(sql: stringLiteral, arguments: [])
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
self.init(elements: sqlInterpolation.elements)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
/// :nodoc:
|
||||
public struct SQLInterpolation: StringInterpolationProtocol {
|
||||
var elements: [SQL.Element]
|
||||
|
||||
|
||||
+85
-46
@@ -1,4 +1,44 @@
|
||||
/// A FetchRequest built from raw SQL.
|
||||
/// An SQL request that can decode database rows.
|
||||
///
|
||||
/// `SQLRequest` allows you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// ```swift
|
||||
/// extension Player {
|
||||
/// static func filter(name: String) -> SQLRequest<Player> {
|
||||
/// "SELECT * FROM player WHERE name = \(name)"
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let players = try Player.filter(name: "O'Brien").fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// An `SQLRequest` can be created from a string literal, as in the above
|
||||
/// example, or from one of the initializers documented below.
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ### Creating an SQL Request from a Literal Value
|
||||
///
|
||||
/// - ``init(stringLiteral:)``
|
||||
/// - ``init(unicodeScalarLiteral:)-84mq8``
|
||||
/// - ``init(extendedGraphemeClusterLiteral:)-1sf75``
|
||||
///
|
||||
/// ### Creating an SQL Request from an Interpolation
|
||||
///
|
||||
/// - ``init(stringInterpolation:)``
|
||||
///
|
||||
/// ### Creating an SQL Request from an SQL Literal
|
||||
///
|
||||
/// - ``init(literal:adapter:cached:)-4vuxn``
|
||||
/// - ``init(literal:adapter:cached:)-82f97``
|
||||
///
|
||||
/// ### Creating an SQL Request from an SQL String
|
||||
///
|
||||
/// - ``init(sql:arguments:adapter:cached:)-3qq8t``
|
||||
/// - ``init(sql:arguments:adapter:cached:)-5ecx2``
|
||||
public struct SQLRequest<RowDecoder> {
|
||||
/// There are two statement caches: one "public" for statements generated by
|
||||
/// the user, and one "internal" for the statements generated by GRDB. Those
|
||||
@@ -12,15 +52,15 @@ public struct SQLRequest<RowDecoder> {
|
||||
case `internal`
|
||||
}
|
||||
|
||||
/// The request adapter
|
||||
public var adapter: RowAdapter?
|
||||
/// The row adapter.
|
||||
public var adapter: (any RowAdapter)?
|
||||
|
||||
private(set) var sqlLiteral: SQL
|
||||
let cache: Cache?
|
||||
|
||||
private init(
|
||||
literal sqlLiteral: SQL,
|
||||
adapter: RowAdapter?,
|
||||
adapter: (any RowAdapter)?,
|
||||
fromCache cache: Cache?,
|
||||
type: RowDecoder.Type)
|
||||
{
|
||||
@@ -31,27 +71,27 @@ public struct SQLRequest<RowDecoder> {
|
||||
}
|
||||
|
||||
extension SQLRequest {
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
/// Creates a request from an SQL string.
|
||||
///
|
||||
/// let request = SQLRequest<String>(sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// let request = SQLRequest<Player>(sql: """
|
||||
/// SELECT * FROM player WHERE id = ?
|
||||
/// """, arguments: [1])
|
||||
/// ```swift
|
||||
/// let request = SQLRequest<String>(sql: """
|
||||
/// SELECT name FROM player
|
||||
/// """)
|
||||
/// let request = SQLRequest<Player>(sql: """
|
||||
/// SELECT * FROM player WHERE name = ?
|
||||
/// """, arguments: ["O'Brien"])
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil,
|
||||
adapter: (any RowAdapter)? = nil,
|
||||
cached: Bool = false)
|
||||
{
|
||||
self.init(
|
||||
@@ -61,23 +101,24 @@ extension SQLRequest {
|
||||
type: RowDecoder.self)
|
||||
}
|
||||
|
||||
/// Creates a request from an `SQL` literal, and optional row adapter.
|
||||
/// Creates a request from an ``SQL`` literal.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let name = "O'brien"
|
||||
/// let request = SQLRequest<Player>(literal: """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// let name = "O'Brien"
|
||||
/// let request = SQLRequest<Player>(literal: """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqlLiteral: An `SQL` literal.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(literal sqlLiteral: SQL, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
public init(literal sqlLiteral: SQL, adapter: (any RowAdapter)? = nil, cached: Bool = false) {
|
||||
self.init(
|
||||
literal: sqlLiteral,
|
||||
adapter: adapter,
|
||||
@@ -86,25 +127,25 @@ extension SQLRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRequest where RowDecoder == Row {
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
extension SQLRequest<Row> {
|
||||
/// Creates a request of database rows, from an SQL string.
|
||||
///
|
||||
/// let request = SQLRequest(sql: """
|
||||
/// SELECT * FROM player WHERE id = ?
|
||||
/// """, arguments: [1])
|
||||
/// ```swift
|
||||
/// let request = SQLRequest(sql: """
|
||||
/// SELECT * FROM player WHERE name = ?
|
||||
/// """, arguments: ["O'Brien"])
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - sql: An SQL string.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil,
|
||||
adapter: (any RowAdapter)? = nil,
|
||||
cached: Bool = false)
|
||||
{
|
||||
self.init(
|
||||
@@ -114,23 +155,24 @@ extension SQLRequest where RowDecoder == Row {
|
||||
type: Row.self)
|
||||
}
|
||||
|
||||
/// Creates a request from an `SQL` literal, and optional row adapter.
|
||||
/// Creates a request of database rows, from an ``SQL`` literal.
|
||||
///
|
||||
/// Literals allow you to safely embed raw values in your SQL, without any
|
||||
/// risk of syntax errors or SQL injection:
|
||||
/// ``SQL`` literals allow you to safely embed raw values in your SQL,
|
||||
/// without any risk of syntax errors or SQL injection:
|
||||
///
|
||||
/// let name = "O'brien"
|
||||
/// let request = SQLRequest(literal: """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// """)
|
||||
/// ```swift
|
||||
/// let name = "O'Brien"
|
||||
/// let request = SQLRequest(literal: """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// """)
|
||||
/// ```
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqlLiteral: An `SQL` literal.
|
||||
/// - adapter: Optional RowAdapter.
|
||||
/// - cached: Defaults to false. If true, the request reuses a cached
|
||||
/// prepared statement.
|
||||
/// - returns: A SQLRequest
|
||||
public init(literal sqlLiteral: SQL, adapter: RowAdapter? = nil, cached: Bool = false) {
|
||||
public init(literal sqlLiteral: SQL, adapter: (any RowAdapter)? = nil, cached: Bool = false) {
|
||||
self.init(
|
||||
literal: sqlLiteral,
|
||||
adapter: adapter,
|
||||
@@ -170,22 +212,19 @@ extension SQLRequest: FetchRequest {
|
||||
}
|
||||
|
||||
extension SQLRequest: ExpressibleByStringInterpolation {
|
||||
/// :nodoc
|
||||
public init(unicodeScalarLiteral: String) {
|
||||
self.init(sql: unicodeScalarLiteral)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(extendedGraphemeClusterLiteral: String) {
|
||||
self.init(sql: extendedGraphemeClusterLiteral)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
/// Creates an `SQLRequest` from the given literal SQL string.
|
||||
public init(stringLiteral: String) {
|
||||
self.init(sql: stringLiteral)
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public init(stringInterpolation sqlInterpolation: SQLInterpolation) {
|
||||
self.init(literal: SQL(stringInterpolation: sqlInterpolation))
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ final class SchedulingWatchdog {
|
||||
GRDBPrecondition(allows(db), message(), file: file, line: line)
|
||||
}
|
||||
|
||||
/// Returns true iff the database argument can be used in the current
|
||||
/// Returns whether the database argument can be used in the current
|
||||
/// dispatch queue.
|
||||
static func allows(_ db: Database) -> Bool {
|
||||
current?.allows(db) ?? false
|
||||
|
||||
@@ -249,9 +249,7 @@ final class SerializedDatabase {
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked because the wrapped `Database` itself is not Sendable.
|
||||
// It happens the job of SerializedDatabase is precisely to provide thread-safe
|
||||
// access to `Database`.
|
||||
extension SerializedDatabase: @unchecked Sendable { }
|
||||
#endif
|
||||
+470
-266
File diff suppressed because it is too large.
Load diff
@@ -2,14 +2,19 @@
|
||||
import Glibc
|
||||
#endif
|
||||
|
||||
/// A class that gathers information about one statement during its compilation.
|
||||
/// `StatementAuthorizer` provides information about compiled database
|
||||
/// statements, and prevents the truncate optimization when row deletions are
|
||||
/// observed by transaction observers.
|
||||
///
|
||||
/// <https://www.sqlite.org/c3ref/set_authorizer.html>
|
||||
/// <https://www.sqlite.org/lang_delete.html#the_truncate_optimization>
|
||||
final class StatementAuthorizer {
|
||||
private unowned var database: Database
|
||||
|
||||
/// What this statements reads
|
||||
/// What a statement reads.
|
||||
var selectedRegion = DatabaseRegion()
|
||||
|
||||
/// What this statements writes
|
||||
/// What a statement writes.
|
||||
var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// True if a statement alters the schema in a way that requires
|
||||
@@ -27,6 +32,20 @@ final class StatementAuthorizer {
|
||||
self.database = database
|
||||
}
|
||||
|
||||
/// Registers the authorizer with `sqlite3_set_authorizer`.
|
||||
func register() {
|
||||
let authorizerP = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_set_authorizer(
|
||||
database.sqliteConnection,
|
||||
{ (authorizerP, actionCode, cString1, cString2, cString3, cString4) in
|
||||
Unmanaged<StatementAuthorizer>
|
||||
.fromOpaque(authorizerP.unsafelyUnwrapped)
|
||||
.takeUnretainedValue()
|
||||
.authorize(actionCode, cString1, cString2, cString3, cString4)
|
||||
},
|
||||
authorizerP)
|
||||
}
|
||||
|
||||
/// Reset before compiling a new statement
|
||||
func reset() {
|
||||
selectedRegion = DatabaseRegion()
|
||||
@@ -36,13 +55,13 @@ final class StatementAuthorizer {
|
||||
isDropStatement = false
|
||||
}
|
||||
|
||||
func authorize(
|
||||
_ actionCode: Int32,
|
||||
private func authorize(
|
||||
_ actionCode: CInt,
|
||||
_ cString1: UnsafePointer<Int8>?,
|
||||
_ cString2: UnsafePointer<Int8>?,
|
||||
_ cString3: UnsafePointer<Int8>?,
|
||||
_ cString4: UnsafePointer<Int8>?)
|
||||
-> Int32
|
||||
-> CInt
|
||||
{
|
||||
// Uncomment when debugging
|
||||
// print("""
|
||||
@@ -74,7 +93,7 @@ final class StatementAuthorizer {
|
||||
guard let columnName = cString2.map(String.init) else { return SQLITE_OK }
|
||||
if columnName.isEmpty {
|
||||
// SELECT COUNT(*) FROM table
|
||||
selectedRegion.formUnion(DatabaseRegion.fullTable(tableName))
|
||||
selectedRegion.formUnion(DatabaseRegion(table: tableName))
|
||||
} else {
|
||||
// SELECT column FROM table
|
||||
selectedRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName]))
|
||||
@@ -91,18 +110,21 @@ final class StatementAuthorizer {
|
||||
guard let cString1 = cString1 else { return SQLITE_OK }
|
||||
|
||||
// Deletions from sqlite_master and sqlite_temp_master are not like
|
||||
// other deletions: the update hook does not notify them, and they
|
||||
// are prevented when the truncate optimization is disabled.
|
||||
// Let's authorize such deletions by returning SQLITE_OK:
|
||||
// other deletions: `sqlite3_update_hook` does not notify them, and
|
||||
// they are prevented when the truncate optimization is disabled.
|
||||
// Let's always authorize such deletions by returning SQLITE_OK:
|
||||
guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK }
|
||||
guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK }
|
||||
|
||||
let tableName = String(cString: cString1)
|
||||
databaseEventKinds.append(.delete(tableName: tableName))
|
||||
|
||||
// Now we prevent the truncate optimization so that transaction
|
||||
// observers are notified of individual row deletions.
|
||||
if database.observationBroker.observesDeletions(on: tableName) {
|
||||
if let observationBroker = database.observationBroker,
|
||||
observationBroker.observesDeletions(on: tableName)
|
||||
{
|
||||
// Prevent the truncate optimization so that
|
||||
// `sqlite3_update_hook` notifies individual row deletions to
|
||||
// transaction observers.
|
||||
return SQLITE_IGNORE
|
||||
} else {
|
||||
return SQLITE_OK
|
||||
@@ -138,33 +160,21 @@ final class StatementAuthorizer {
|
||||
return SQLITE_OK
|
||||
|
||||
case SQLITE_FUNCTION:
|
||||
guard let cString2 = cString2 else { return SQLITE_OK }
|
||||
|
||||
// SQLite does not report ALTER TABLE DROP COLUMN with the
|
||||
// SQLITE_ALTER_TABLE action code. So we need to find another way
|
||||
// to set the `invalidatesDatabaseSchemaCache` flag for such
|
||||
// SQLite 3.37.2 does not report ALTER TABLE DROP COLUMN with the
|
||||
// SQLITE_ALTER_TABLE action code. SQLite 3.38 does.
|
||||
//
|
||||
// Until SQLite 3.38, we need to find another way to set the
|
||||
// `invalidatesDatabaseSchemaCache` flag for such
|
||||
// statement, and it is SQLITE_FUNCTION sqlite_drop_column.
|
||||
//
|
||||
// See <https://github.com/groue/GRDB.swift/pull/1144#issuecomment-1015155717>
|
||||
// See <https://sqlite.org/forum/forumpost/bd47580ec2>
|
||||
//
|
||||
// TODO: remove when SQLite properly reports SQLITE_ALTER_TABLE
|
||||
if strcmp(cString2, "sqlite_drop_column") == 0 {
|
||||
if sqlite3_libversion_number() < 3038000,
|
||||
let cString2,
|
||||
strcmp(cString2, "sqlite_drop_column") == 0
|
||||
{
|
||||
invalidatesDatabaseSchemaCache = true
|
||||
}
|
||||
|
||||
// Starting SQLite 3.19.0, `SELECT COUNT(*) FROM table` triggers
|
||||
// an authorization callback for SQLITE_READ with an empty
|
||||
// column: http://www.sqlite.org/changes.html#version_3_19_0
|
||||
//
|
||||
// Before SQLite 3.19.0, `SELECT COUNT(*) FROM table` does not
|
||||
// trigger any authorization callback that tells about the
|
||||
// counted table: any use of the COUNT function makes the
|
||||
// region undetermined (the full database).
|
||||
guard sqlite3_libversion_number() < 3019000 else { return SQLITE_OK }
|
||||
if sqlite3_stricmp(cString2, "COUNT") == 0 {
|
||||
selectedRegion = .fullDatabase
|
||||
}
|
||||
return SQLITE_OK
|
||||
|
||||
default:
|
||||
@@ -172,7 +182,7 @@ final class StatementAuthorizer {
|
||||
}
|
||||
}
|
||||
|
||||
func insertUpdateEventKind(tableName: String, columnName: String) {
|
||||
private func insertUpdateEventKind(tableName: String, columnName: String) {
|
||||
for (index, eventKind) in databaseEventKinds.enumerated() {
|
||||
if case .update(let t, let columnNames) = eventKind, t == tableName {
|
||||
var columnNames = columnNames
|
||||
@@ -186,7 +196,7 @@ final class StatementAuthorizer {
|
||||
}
|
||||
|
||||
private struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible {
|
||||
let rawValue: Int32
|
||||
let rawValue: CInt
|
||||
|
||||
var description: String {
|
||||
switch rawValue {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -3,13 +3,11 @@ import CoreGraphics
|
||||
|
||||
/// CGFloat adopts DatabaseValueConvertible
|
||||
extension CGFloat: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns a REAL database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
Double(self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a CGFloat initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> CGFloat? {
|
||||
guard let double = Double.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
|
||||
@@ -2,7 +2,7 @@ import Foundation
|
||||
|
||||
/// Data is convertible to and from DatabaseValue.
|
||||
extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
if let bytes = sqlite3_column_blob(sqliteStatement, index) {
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
self.init(bytes: bytes, count: count) // copy bytes
|
||||
@@ -11,13 +11,19 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns a BLOB database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
DatabaseValue(storage: .blob(self))
|
||||
}
|
||||
|
||||
/// Returns a Data initialized from *dbValue*, if it contains
|
||||
/// a Blob.
|
||||
/// Returns a `Data` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a data blob, returns it.
|
||||
///
|
||||
/// If the database value contains a string, returns this string converted
|
||||
/// to UTF8 data.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Data? {
|
||||
switch dbValue.storage {
|
||||
case .blob(let data):
|
||||
@@ -33,7 +39,7 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
withUnsafeBytes {
|
||||
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, Int32($0.count), SQLITE_TRANSIENT)
|
||||
sqlite3_bind_blob(sqliteStatement, index, $0.baseAddress, CInt($0.count), SQLITE_TRANSIENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -43,67 +49,21 @@ extension Data: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
extension Data {
|
||||
static func fastDecodeNoCopy(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
atUncheckedIndex index: CInt,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Data
|
||||
{
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
|
||||
throw RowDecodingError.valueMismatch(
|
||||
Data.self,
|
||||
sqliteStatement: sqliteStatement,
|
||||
index: index,
|
||||
context: context())
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, index) else {
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, index))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
static func fastDecodeNoCopy(
|
||||
fromRow row: Row,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Data
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try fastDecodeNoCopy(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecodeDataNoCopy(atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
static func fastDecodeNoCopyIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
-> Data?
|
||||
{
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
return nil
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
static func fastDecodeNoCopyIfPresent(
|
||||
fromRow row: Row,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Data?
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return fastDecodeNoCopyIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecodeDataNoCopyIfPresent(atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import Foundation
|
||||
|
||||
/// DatabaseDateComponents reads and stores DateComponents in the database.
|
||||
public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnConvertible, Codable {
|
||||
/// A database value that holds date components.
|
||||
public struct DatabaseDateComponents {
|
||||
|
||||
/// The available formats for reading and storing date components.
|
||||
/// The SQLite formats for date components.
|
||||
public enum Format: String {
|
||||
|
||||
/// The format "yyyy-MM-dd".
|
||||
@@ -43,8 +43,6 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - NSDateComponents conversion
|
||||
|
||||
/// The date components
|
||||
public let dateComponents: DateComponents
|
||||
|
||||
@@ -61,9 +59,9 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
self.format = format
|
||||
self.dateComponents = dateComponents
|
||||
}
|
||||
|
||||
// MARK: - StatementColumnConvertible adoption
|
||||
|
||||
}
|
||||
|
||||
extension DatabaseDateComponents: StatementColumnConvertible {
|
||||
/// Returns a value initialized from a raw SQLite statement pointer.
|
||||
///
|
||||
/// - parameters:
|
||||
@@ -71,25 +69,25 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
guard let cString = sqlite3_column_text(sqliteStatement, index) else {
|
||||
return nil
|
||||
}
|
||||
let length = Int(sqlite3_column_bytes(sqliteStatement, index)) // avoid an strlen
|
||||
let optionalComponents = cString.withMemoryRebound(
|
||||
let components = cString.withMemoryRebound(
|
||||
to: Int8.self,
|
||||
capacity: length + 1 /* trailing \0 */) { cString in
|
||||
SQLiteDateParser().components(cString: cString, length: length)
|
||||
}
|
||||
guard let components = optionalComponents else {
|
||||
guard let components else {
|
||||
return nil
|
||||
}
|
||||
self.init(components.dateComponents, format: components.format)
|
||||
}
|
||||
|
||||
// MARK: - DatabaseValueConvertible adoption
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
}
|
||||
|
||||
extension DatabaseDateComponents: DatabaseValueConvertible {
|
||||
/// Returns a TEXT database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
let dateString: String?
|
||||
switch format {
|
||||
@@ -128,39 +126,32 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
return [dateString, timeString].compactMap { $0 }.joined(separator: " ").databaseValue
|
||||
}
|
||||
|
||||
/// Returns a DatabaseDateComponents if *dbValue* contains a
|
||||
/// valid date.
|
||||
/// Creates a `DatabaseDateComponents` from the specified database value.
|
||||
///
|
||||
/// The supported formats are:
|
||||
///
|
||||
/// - `YYYY-MM-DD`
|
||||
/// - `YYYY-MM-DD HH:MM`
|
||||
/// - `YYYY-MM-DD HH:MM:SS`
|
||||
/// - `YYYY-MM-DD HH:MM:SS.SSS`
|
||||
/// - `YYYY-MM-DDTHH:MM`
|
||||
/// - `YYYY-MM-DDTHH:MM:SS`
|
||||
/// - `YYYY-MM-DDTHH:MM:SS.SSS`
|
||||
/// - `HH:MM`
|
||||
/// - `HH:MM:SS`
|
||||
/// - `HH:MM:SS.SSS`
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_datefunc.html>
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> DatabaseDateComponents? {
|
||||
// https://www.sqlite.org/lang_datefunc.html
|
||||
//
|
||||
// Supported formats are:
|
||||
//
|
||||
// - YYYY-MM-DD
|
||||
// - YYYY-MM-DD HH:MM
|
||||
// - YYYY-MM-DD HH:MM:SS
|
||||
// - YYYY-MM-DD HH:MM:SS.SSS
|
||||
// - YYYY-MM-DDTHH:MM
|
||||
// - YYYY-MM-DDTHH:MM:SS
|
||||
// - YYYY-MM-DDTHH:MM:SS.SSS
|
||||
// - HH:MM
|
||||
// - HH:MM:SS
|
||||
// - HH:MM:SS.SSS
|
||||
|
||||
// We need a String
|
||||
guard let string = String.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
}
|
||||
|
||||
return SQLiteDateParser().components(from: string)
|
||||
}
|
||||
|
||||
// MARK: - Codable adoption
|
||||
|
||||
|
||||
/// Creates a new instance by decoding from the given decoder.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - decoder: The decoder to read data from.
|
||||
}
|
||||
|
||||
extension DatabaseDateComponents: Decodable {
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
let stringValue = try container.decode(String.self)
|
||||
@@ -170,11 +161,9 @@ public struct DatabaseDateComponents: DatabaseValueConvertible, StatementColumnC
|
||||
}
|
||||
self = decodedValue
|
||||
}
|
||||
|
||||
/// Encodes this value into the given encoder.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - encoder: The encoder to write data to.
|
||||
}
|
||||
|
||||
extension DatabaseDateComponents: Encodable {
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(String.fromDatabaseValue(databaseValue)!)
|
||||
|
||||
@@ -15,12 +15,10 @@ import Foundation
|
||||
/// extension Foo : DatabaseValueConvertible { /* empty */ }
|
||||
extension DatabaseValueConvertible where Self: ReferenceConvertible, Self.ReferenceType: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
public var databaseValue: DatabaseValue {
|
||||
(self as! ReferenceType).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a value initialized from *dbValue*, if possible.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
ReferenceType.fromDatabaseValue(dbValue).flatMap { cast($0) }
|
||||
}
|
||||
|
||||
@@ -4,22 +4,24 @@ import Foundation
|
||||
/// NSDate is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension NSDate: DatabaseValueConvertible {
|
||||
/// Returns a database value that contains the date encoded as
|
||||
/// Returns a TEXT database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
public var databaseValue: DatabaseValue {
|
||||
(self as Date).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a date initialized from dbValue, if possible.
|
||||
/// Creates an `NSDate` with the specified database value.
|
||||
///
|
||||
/// If database value contains a number, that number is interpreted as a
|
||||
/// If the database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
///
|
||||
/// If database value contains a string, that string is interpreted as a
|
||||
/// If the database value contains a string, that string is interpreted as a
|
||||
/// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time
|
||||
/// zone. Nil is returned if the date string does not contain at least the
|
||||
/// year, month and day components. Other components (minutes, etc.)
|
||||
/// are set to zero if missing.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let date = Date.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
@@ -32,22 +34,24 @@ extension NSDate: DatabaseValueConvertible {
|
||||
/// Date is stored in the database using the format
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
extension Date: DatabaseValueConvertible {
|
||||
/// Returns a database value that contains the date encoded as
|
||||
/// Returns a TEXT database value that contains the date encoded as
|
||||
/// "yyyy-MM-dd HH:mm:ss.SSS", in the UTC time zone.
|
||||
public var databaseValue: DatabaseValue {
|
||||
storageDateFormatter.string(from: self).databaseValue
|
||||
}
|
||||
|
||||
/// Returns a date initialized from dbValue, if possible.
|
||||
/// Creates an `Date` with the specified database value.
|
||||
///
|
||||
/// If database value contains a number, that number is interpreted as a
|
||||
/// If the database value contains a number, that number is interpreted as a
|
||||
/// timeinterval since 00:00:00 UTC on 1 January 1970.
|
||||
///
|
||||
/// If database value contains a string, that string is interpreted as a
|
||||
/// If the database value contains a string, that string is interpreted as a
|
||||
/// [SQLite date](https://sqlite.org/lang_datefunc.html) in the UTC time
|
||||
/// zone. Nil is returned if the date string does not contain at least the
|
||||
/// year, month and day components. Other components (minutes, etc.)
|
||||
/// are set to zero if missing.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Date? {
|
||||
if let databaseDateComponents = DatabaseDateComponents.fromDatabaseValue(dbValue) {
|
||||
return Date(databaseDateComponents: databaseDateComponents)
|
||||
@@ -120,7 +124,7 @@ extension Date: StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_INTEGER, SQLITE_FLOAT:
|
||||
self.init(timeIntervalSince1970: sqlite3_column_double(sqliteStatement, index))
|
||||
|
||||
@@ -3,12 +3,22 @@ import Foundation
|
||||
|
||||
/// Decimal adopts DatabaseValueConvertible
|
||||
extension Decimal: DatabaseValueConvertible {
|
||||
/// Returns a TEXT decimal value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
NSDecimalNumber(decimal: self)
|
||||
.description(withLocale: Locale(identifier: "en_US_POSIX"))
|
||||
.databaseValue
|
||||
}
|
||||
|
||||
/// Creates an `Decimal` with the specified database value.
|
||||
///
|
||||
/// If the database value contains a integer or a double, returns a
|
||||
/// `Decimal` initialized from this number.
|
||||
///
|
||||
/// If the database value contains a string, parses the string with the
|
||||
/// `en_US_POSIX` locale.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
switch dbValue.storage {
|
||||
case .int64(let int64):
|
||||
@@ -28,7 +38,7 @@ extension Decimal: DatabaseValueConvertible {
|
||||
extension Decimal: StatementColumnConvertible {
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_INTEGER:
|
||||
self.init(sqlite3_column_int64(sqliteStatement, index))
|
||||
|
||||
@@ -4,13 +4,19 @@ import Foundation
|
||||
/// NSData is convertible to and from DatabaseValue.
|
||||
extension NSData: DatabaseValueConvertible {
|
||||
|
||||
/// Returns a value that can be stored in the database.
|
||||
/// Returns a BLOB database value.
|
||||
public var databaseValue: DatabaseValue {
|
||||
(self as Data).databaseValue
|
||||
}
|
||||
|
||||
/// Returns an NSData initialized from *dbValue*, if it contains
|
||||
/// a Blob.
|
||||
/// Returns a `NSData` from the specified database value.
|
||||
///
|
||||
/// If the database value contains a data blob, returns it.
|
||||
///
|
||||
/// If the database value contains a string, returns this string converted
|
||||
/// to UTF8 data.
|
||||
///
|
||||
/// Otherwise, returns nil.
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
guard let data = Data.fromDatabaseValue(dbValue) else {
|
||||
return nil
|
||||
|
||||
@@ -3,7 +3,7 @@ import Foundation
|
||||
/// NSNull adopts DatabaseValueConvertible
|
||||
extension NSNull: DatabaseValueConvertible {
|
||||
|
||||
/// Returns DatabaseValue.null.
|
||||
/// Returns the NULL database value.
|
||||
public var databaseValue: DatabaseValue { .null }
|
||||
|
||||
/// Returns nil.
|
||||
|
||||
Loaded 100 of 373 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user