mirror of
https://github.com/groue/GRDB.swift
synced 2026-11-27 04:14:21 +00:00
Merge branch 'development'
This commit is contained in:
commit
6bf346ccf5
322 files changed
+13549
-9781
No files matched your search
@@ -5,6 +5,10 @@ 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.0.0` Betas - [6.0.0-beta](#600-beta)
|
||||
|
||||
#### 5.x Releases
|
||||
|
||||
- `5.26.x` Releases - [5.26.0](#5260)
|
||||
@@ -93,6 +97,61 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 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.0
|
||||
|
||||
Released July 9, 2022 • [diff](https://github.com/groue/GRDB.swift/compare/v5.25.0...v5.26.0)
|
||||
|
||||
@@ -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:
|
||||
|
||||
|
||||
@@ -506,7 +506,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).
|
||||
|
||||
|
||||
@@ -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 */
|
||||
|
||||
+1
-11
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -38,16 +38,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 */
|
||||
|
||||
+1
-11
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
@@ -38,16 +38,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:
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
56606D25235593AB00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* 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 */; };
|
||||
@@ -127,15 +127,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 */ = {
|
||||
@@ -366,7 +366,7 @@
|
||||
buildConfigurationList = 568E5FDE1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS" */;
|
||||
buildPhases = (
|
||||
568E5FBD1E926430002582E0 /* Resources */,
|
||||
568E5FDD1E926430002582E0 /* Embed App Extensions */,
|
||||
568E5FDD1E926430002582E0 /* Embed Foundation Extensions */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
@@ -425,7 +425,7 @@
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 1230;
|
||||
LastUpgradeCheck = 1200;
|
||||
LastUpgradeCheck = 1400;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
56185BEF25B80B8900B9C30F = {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1200"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -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](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/StatementArguments.html):
|
||||
|
||||
```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](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/StatementArguments.html):
|
||||
|
||||
```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,353 @@
|
||||
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](../README.md#persistence-callbacks) for the full list of callbacks).
|
||||
|
||||
For example, 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")
|
||||
}
|
||||
```
|
||||
@@ -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](http://groue.github.io/GRDB.swift/docs/6.0.0-beta/Structs/DatabaseMigrator.html) 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
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
@@ -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>
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
+6
-6
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '5.26.0'
|
||||
s.version = '6.0.0-beta'
|
||||
|
||||
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',
|
||||
|
||||
+139
-37
@@ -70,8 +70,8 @@
|
||||
560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */; };
|
||||
560D92421C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; };
|
||||
560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; };
|
||||
560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
|
||||
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
|
||||
560D92471C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */; };
|
||||
560D92481C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */; };
|
||||
560D924B1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
|
||||
560D924C1C672C4B00F4F92B /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
|
||||
5611620825757583007AAF99 /* JoinAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5611620725757583007AAF99 /* JoinAssociation.swift */; };
|
||||
@@ -84,6 +84,10 @@
|
||||
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; };
|
||||
5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; };
|
||||
5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; };
|
||||
56158780288D875E00A67323 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615877F288D875E00A67323 /* Optional.swift */; };
|
||||
56158781288D875E00A67323 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615877F288D875E00A67323 /* Optional.swift */; };
|
||||
56158782288D875E00A67323 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615877F288D875E00A67323 /* Optional.swift */; };
|
||||
56158783288D875E00A67323 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615877F288D875E00A67323 /* Optional.swift */; };
|
||||
5615B261222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B25A222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */; };
|
||||
5615B262222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B25A222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */; };
|
||||
5615B26A222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5615B269222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift */; };
|
||||
@@ -393,7 +397,7 @@
|
||||
565490D91D5AE252005622CB /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
|
||||
565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56300B6F1C53F592005A543B /* QueryInterfaceRequest.swift */; };
|
||||
565490DF1D5AE252005622CB /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
|
||||
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
|
||||
565490E11D5AE252005622CB /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */; };
|
||||
565490E21D5AE252005622CB /* Record.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238A11B9C753B0082EB20 /* Record.swift */; };
|
||||
565490E41D5AE252005622CB /* TableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92461C672C4B00F4F92B /* TableRecord.swift */; };
|
||||
56553C101C3E906C00522B5C /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
|
||||
@@ -490,6 +494,10 @@
|
||||
566BE71F2342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
|
||||
566BE7202342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
|
||||
566BE7212342542F00A8254B /* LockedBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566BE7172342542F00A8254B /* LockedBox.swift */; };
|
||||
566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.swift */; };
|
||||
566DDE0E288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.swift */; };
|
||||
566DDE0F288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.swift */; };
|
||||
566DDE10288D763C0000DCFB /* Fixits.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566DDE0C288D763C0000DCFB /* Fixits.swift */; };
|
||||
56703297212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
56703298212B5450007D270F /* DatabaseUUIDEncodingStrategyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */; };
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */; };
|
||||
@@ -549,9 +557,6 @@
|
||||
567DAF221EAB61ED00FC0928 /* grdb_config.h in Headers */ = {isa = PBXBuildFile; fileRef = 567DAF141EAB61ED00FC0928 /* grdb_config.h */; settings = {ATTRIBUTES = (Private, ); }; };
|
||||
567DAF351EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
|
||||
567DAF391EAB789800FC0928 /* DatabaseLogErrorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */; };
|
||||
567ECE4F2222E431009245CA /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; };
|
||||
567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; };
|
||||
567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; };
|
||||
567F45A81F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
|
||||
567F45AC1F888B2600030B59 /* TruncateOptimizationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */; };
|
||||
568068311EBBA26100EFB8AA /* SQLRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 568068301EBBA26100EFB8AA /* SQLRequestTests.swift */; };
|
||||
@@ -684,7 +689,6 @@
|
||||
56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */; };
|
||||
56A2385A1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382B1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift */; };
|
||||
56A2385C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */; };
|
||||
56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; };
|
||||
56A238621B9C74A90082EB20 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; };
|
||||
56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; };
|
||||
56A2386A1B9C74A90082EB20 /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; };
|
||||
@@ -787,6 +791,38 @@
|
||||
56CEB5531EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; };
|
||||
56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; };
|
||||
56CEB5591EAA359A00BFAF62 /* SQLExpression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */; };
|
||||
56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */; };
|
||||
56D110C028AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */; };
|
||||
56D110C128AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */; };
|
||||
56D110C228AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */; };
|
||||
56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */; };
|
||||
56D110C528AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */; };
|
||||
56D110C628AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */; };
|
||||
56D110C728AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */; };
|
||||
56D110C928AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */; };
|
||||
56D110CA28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */; };
|
||||
56D110CB28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */; };
|
||||
56D110CC28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */; };
|
||||
56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */; };
|
||||
56D110CF28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */; };
|
||||
56D110D028AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */; };
|
||||
56D110D128AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */; };
|
||||
56D110D328AFC81400E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D228AFC81400E64463 /* PersistableRecord.swift */; };
|
||||
56D110D428AFC81400E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D228AFC81400E64463 /* PersistableRecord.swift */; };
|
||||
56D110D528AFC81400E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D228AFC81400E64463 /* PersistableRecord.swift */; };
|
||||
56D110D628AFC81400E64463 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D228AFC81400E64463 /* PersistableRecord.swift */; };
|
||||
56D110D828AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; };
|
||||
56D110D928AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; };
|
||||
56D110DA28AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; };
|
||||
56D110DB28AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */; };
|
||||
56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; };
|
||||
56D110DE28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; };
|
||||
56D110DF28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; };
|
||||
56D110E028AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */; };
|
||||
56D110FA28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; };
|
||||
56D110FB28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; };
|
||||
56D110FC28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; };
|
||||
56D110FD28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */; };
|
||||
56D496541D812F5B008276D7 /* SQLExpressionLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A4CDAF1D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift */; };
|
||||
56D496551D812F83008276D7 /* FoundationDataTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AB2F1D108BA9006283EF /* FoundationDataTests.swift */; };
|
||||
56D496571D81303E008276D7 /* FoundationDateComponentsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C3251D23E6D800E59934 /* FoundationDateComponentsTests.swift */; };
|
||||
@@ -817,7 +853,6 @@
|
||||
56D496701D81309E008276D7 /* RecordPrimaryKeyRowIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */; };
|
||||
56D496711D81309E008276D7 /* RecordPrimaryKeySingleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382B1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift */; };
|
||||
56D496721D81309E008276D7 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */; };
|
||||
56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; };
|
||||
56D496751D81309E008276D7 /* RecordEditedTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */; };
|
||||
56D496771D81309E008276D7 /* RecordInitializersTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */; };
|
||||
56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */; };
|
||||
@@ -931,6 +966,14 @@
|
||||
56F61DD5283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
|
||||
56F61DD6283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
|
||||
56F61DD7283D344E00AF9884 /* getThreadsCount.c in Sources */ = {isa = PBXBuildFile; fileRef = 56F61DD4283D344E00AF9884 /* getThreadsCount.c */; };
|
||||
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; };
|
||||
56FA0C3128B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; };
|
||||
56FA0C3228B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; };
|
||||
56FA0C3328B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */; };
|
||||
56FA0C3928B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; };
|
||||
56FA0C3A28B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; };
|
||||
56FA0C3B28B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; };
|
||||
56FA0C3C28B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */; };
|
||||
56FBFED92210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
@@ -1025,7 +1068,6 @@
|
||||
AAA4DCD0230F1E0600C74B15 /* SQLInterpolation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 569D6DDD220EF9E100A058A9 /* SQLInterpolation.swift */; };
|
||||
AAA4DCD1230F1E0600C74B15 /* DatabaseError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238731B9C75030082EB20 /* DatabaseError.swift */; };
|
||||
AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5653EAFB20944C7B00F46237 /* HasManyAssociation.swift */; };
|
||||
AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567ECE4E2222E431009245CA /* GRDB-5.0.swift */; };
|
||||
AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 566AD8B11D5318F4002EC1A8 /* TableDefinition.swift */; };
|
||||
AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5698AD201DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift */; };
|
||||
AAA4DCD6230F1E0600C74B15 /* SQLRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56FBFED82210731A00945324 /* SQLRequest.swift */; };
|
||||
@@ -1035,7 +1077,7 @@
|
||||
AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */; };
|
||||
AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5605F1581C672E4000235C62 /* StandardLibrary.swift */; };
|
||||
AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
|
||||
AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* PersistableRecord.swift */; };
|
||||
AAA4DCDF230F1E0600C74B15 /* MutablePersistableRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */; };
|
||||
AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */; };
|
||||
AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */; };
|
||||
AAA4DCE3230F1E0600C74B15 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5613ED3421A95A5C00DC7A68 /* Map.swift */; };
|
||||
@@ -1132,7 +1174,6 @@
|
||||
AAA4DD5A230F262000C74B15 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
|
||||
AAA4DD5B230F262000C74B15 /* FetchRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56741EA71E66A8B3003E422D /* FetchRequestTests.swift */; };
|
||||
AAA4DD5C230F262000C74B15 /* DatabaseQueueBackupTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5672DE581CDB72520022BA81 /* DatabaseQueueBackupTests.swift */; };
|
||||
AAA4DD5D230F262000C74B15 /* RecordCopyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */; };
|
||||
AAA4DD5E230F262000C74B15 /* SQLLiteralTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B86E72220FF4E000524C16 /* SQLLiteralTests.swift */; };
|
||||
AAA4DD5F230F262000C74B15 /* FTS5PatternTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B964C01DA521450002DA19 /* FTS5PatternTests.swift */; };
|
||||
AAA4DD60230F262000C74B15 /* PersistableRecordTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363AA1C933FF8000BE133 /* PersistableRecordTests.swift */; };
|
||||
@@ -1313,11 +1354,12 @@
|
||||
560C97C61BFD0B8400BF8471 /* DatabaseFunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseFunctionTests.swift; sourceTree = "<group>"; };
|
||||
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConvertible.swift; sourceTree = "<group>"; };
|
||||
560D923F1C672C3E00F4F92B /* StatementColumnConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementColumnConvertible.swift; sourceTree = "<group>"; };
|
||||
560D92441C672C4B00F4F92B /* PersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = "<group>"; };
|
||||
560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = MutablePersistableRecord.swift; sourceTree = "<group>"; };
|
||||
560D92461C672C4B00F4F92B /* TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TableRecord.swift; sourceTree = "<group>"; };
|
||||
5611620725757583007AAF99 /* JoinAssociation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JoinAssociation.swift; sourceTree = "<group>"; };
|
||||
5613ED3421A95A5C00DC7A68 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = "<group>"; };
|
||||
5613ED4321A95B2C00DC7A68 /* ValueReducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueReducer.swift; sourceTree = "<group>"; };
|
||||
5615877F288D875E00A67323 /* Optional.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Optional.swift; sourceTree = "<group>"; };
|
||||
5615B25A222AE1B400061C1C /* AssociationHasOneThroughSQLDerivationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughSQLDerivationTests.swift; sourceTree = "<group>"; };
|
||||
5615B269222AFE8F00061C1C /* AssociationHasOneThroughRowScopeTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughRowScopeTests.swift; sourceTree = "<group>"; };
|
||||
5615B274222B107900061C1C /* AssociationHasOneThroughFetchableRecordTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssociationHasOneThroughFetchableRecordTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1470,6 +1512,7 @@
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionObserver.swift; sourceTree = "<group>"; };
|
||||
566B9C1F25C6CC24004542CF /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.swift; sourceTree = "<group>"; };
|
||||
566BE7172342542F00A8254B /* LockedBox.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LockedBox.swift; sourceTree = "<group>"; };
|
||||
566DDE0C288D763C0000DCFB /* Fixits.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Fixits.swift; sourceTree = "<group>"; };
|
||||
56703290212B544F007D270F /* DatabaseUUIDEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseUUIDEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSONRequiredEncoder.swift; sourceTree = "<group>"; };
|
||||
567156151CB142AA007DC145 /* DatabaseQueueReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseQueueReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1495,7 +1538,6 @@
|
||||
567A80521D41350C00C7DCEC /* IndexInfoTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = IndexInfoTests.swift; sourceTree = "<group>"; };
|
||||
567DAF141EAB61ED00FC0928 /* grdb_config.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = grdb_config.h; sourceTree = "<group>"; };
|
||||
567DAF341EAB789800FC0928 /* DatabaseLogErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseLogErrorTests.swift; sourceTree = "<group>"; };
|
||||
567ECE4E2222E431009245CA /* GRDB-5.0.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "GRDB-5.0.swift"; sourceTree = "<group>"; };
|
||||
567F45A71F888B2600030B59 /* TruncateOptimizationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TruncateOptimizationTests.swift; sourceTree = "<group>"; };
|
||||
568068301EBBA26100EFB8AA /* SQLRequestTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRequestTests.swift; sourceTree = "<group>"; };
|
||||
5682D71A239582AA004B58C4 /* DatabaseSuspensionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseSuspensionTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1571,7 +1613,6 @@
|
||||
56A2382A1B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeyRowIDTests.swift; sourceTree = "<group>"; };
|
||||
56A2382B1B9C74A90082EB20 /* RecordPrimaryKeySingleTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeySingleTests.swift; sourceTree = "<group>"; };
|
||||
56A2382C1B9C74A90082EB20 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift; sourceTree = "<group>"; };
|
||||
56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordCopyTests.swift; sourceTree = "<group>"; };
|
||||
56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordEditedTests.swift; sourceTree = "<group>"; };
|
||||
56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordInitializersTests.swift; sourceTree = "<group>"; };
|
||||
56A238331B9C74A90082EB20 /* RecordSubClassTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RecordSubClassTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1626,6 +1667,14 @@
|
||||
56CEB5181EAA328900BFAF62 /* FTS5+QueryInterface.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FTS5+QueryInterface.swift"; sourceTree = "<group>"; };
|
||||
56CEB5401EAA359A00BFAF62 /* Column.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Column.swift; sourceTree = "<group>"; };
|
||||
56CEB5421EAA359A00BFAF62 /* SQLExpression.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLExpression.swift; sourceTree = "<group>"; };
|
||||
56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Insert.swift"; sourceTree = "<group>"; };
|
||||
56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Update.swift"; sourceTree = "<group>"; };
|
||||
56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Save.swift"; sourceTree = "<group>"; };
|
||||
56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Delete.swift"; sourceTree = "<group>"; };
|
||||
56D110D228AFC81400E64463 /* PersistableRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersistableRecord.swift; sourceTree = "<group>"; };
|
||||
56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Insert.swift"; sourceTree = "<group>"; };
|
||||
56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Save.swift"; sourceTree = "<group>"; };
|
||||
56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+DAO.swift"; sourceTree = "<group>"; };
|
||||
56D5075D1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimaryKeyInfoTests.swift; sourceTree = "<group>"; };
|
||||
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
|
||||
56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
|
||||
@@ -1657,6 +1706,8 @@
|
||||
56F61DD0283D344D00AF9884 /* GRDBTests-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = "GRDBTests-Bridging-Header.h"; path = "GRDBTests/GRDBTests-Bridging-Header.h"; sourceTree = "<group>"; };
|
||||
56F61DD3283D344E00AF9884 /* getThreadsCount.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = getThreadsCount.h; sourceTree = "<group>"; };
|
||||
56F61DD4283D344E00AF9884 /* getThreadsCount.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; path = getThreadsCount.c; sourceTree = "<group>"; };
|
||||
56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "MutablePersistableRecord+Upsert.swift"; sourceTree = "<group>"; };
|
||||
56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "PersistableRecord+Upsert.swift"; sourceTree = "<group>"; };
|
||||
56FBFED82210731A00945324 /* SQLRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLRequest.swift; sourceTree = "<group>"; };
|
||||
56FDECE11BB32DFD009AD709 /* RowFromStatementTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowFromStatementTests.swift; sourceTree = "<group>"; };
|
||||
56FEB8F6248402E10081AF83 /* DatabaseTraceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseTraceTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1783,6 +1834,7 @@
|
||||
5674A6E21F307F0E0095F066 /* DatabaseValueConvertible+Encodable.swift */,
|
||||
5605F1571C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift */,
|
||||
56713FDC2691F409006153C3 /* JSONRequiredEncoder.swift */,
|
||||
5615877F288D875E00A67323 /* Optional.swift */,
|
||||
5605F1581C672E4000235C62 /* StandardLibrary.swift */,
|
||||
);
|
||||
path = StandardLibrary;
|
||||
@@ -1874,7 +1926,6 @@
|
||||
56176C9E1EACEDF9000F3F2B /* Record */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56A2382D1B9C74A90082EB20 /* RecordCopyTests.swift */,
|
||||
56A2382F1B9C74A90082EB20 /* RecordEditedTests.swift */,
|
||||
56A238321B9C74A90082EB20 /* RecordInitializersTests.swift */,
|
||||
56DA7CF6260FA9D400A8D97B /* RecordMinimalNonOptionalPrimaryKeySingleTests.swift */,
|
||||
@@ -2404,7 +2455,17 @@
|
||||
56CEB4F01EAA2EFA00BFAF62 /* FetchableRecord.swift */,
|
||||
5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */,
|
||||
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */,
|
||||
560D92441C672C4B00F4F92B /* PersistableRecord.swift */,
|
||||
560D92441C672C4B00F4F92B /* MutablePersistableRecord.swift */,
|
||||
56D110F928AFC97E00E64463 /* MutablePersistableRecord+DAO.swift */,
|
||||
56D110CD28AFC72100E64463 /* MutablePersistableRecord+Delete.swift */,
|
||||
56D110BE28AFC51000E64463 /* MutablePersistableRecord+Insert.swift */,
|
||||
56D110C828AFC68B00E64463 /* MutablePersistableRecord+Save.swift */,
|
||||
56D110C328AFC5A800E64463 /* MutablePersistableRecord+Update.swift */,
|
||||
56FA0C2F28B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift */,
|
||||
56D110D228AFC81400E64463 /* PersistableRecord.swift */,
|
||||
56D110D728AFC84000E64463 /* PersistableRecord+Insert.swift */,
|
||||
56D110DC28AFC8B400E64463 /* PersistableRecord+Save.swift */,
|
||||
56FA0C3828B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift */,
|
||||
56A238A11B9C753B0082EB20 /* Record.swift */,
|
||||
560D92461C672C4B00F4F92B /* TableRecord.swift */,
|
||||
);
|
||||
@@ -2423,14 +2484,6 @@
|
||||
path = ValueReducer;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56D7E449221595FE0052464B /* Fixit */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
567ECE4E2222E431009245CA /* GRDB-5.0.swift */,
|
||||
);
|
||||
path = Fixit;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
56DAA2C41DE99D8D006E10C8 /* Cursor */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -2526,8 +2579,8 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
56A2FA3524424D2A00E97D23 /* Export.swift */,
|
||||
566DDE0C288D763C0000DCFB /* Fixits.swift */,
|
||||
56A2386F1B9C75030082EB20 /* Core */,
|
||||
56D7E449221595FE0052464B /* Fixit */,
|
||||
5698AC291D9E5A480056AF8C /* FTS */,
|
||||
56A238911B9C750B0082EB20 /* Migration */,
|
||||
56300B6D1C53F592005A543B /* QueryInterface */,
|
||||
@@ -2754,7 +2807,7 @@
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastSwiftUpdateCheck = 0730;
|
||||
LastUpgradeCheck = 1200;
|
||||
LastUpgradeCheck = 1400;
|
||||
ORGANIZATIONNAME = "Gwendal Roué";
|
||||
TargetAttributes = {
|
||||
5654909F1D5A4798005622CB = {
|
||||
@@ -2942,6 +2995,7 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
56D110DF28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */,
|
||||
5616AAF3207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
56256ED225D1ACD0008C2BDD /* Table.swift in Sources */,
|
||||
56B964BF1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
@@ -2953,18 +3007,23 @@
|
||||
564CE5AE21B8FAB400652B19 /* DatabaseRegionObservation.swift in Sources */,
|
||||
565490CF1D5AE252005622CB /* NSNumber.swift in Sources */,
|
||||
56CEB51F1EAA328900BFAF62 /* FTS5+QueryInterface.swift in Sources */,
|
||||
56158782288D875E00A67323 /* Optional.swift in Sources */,
|
||||
56D91AA42205E03700770D8D /* SQLRelation.swift in Sources */,
|
||||
565490E21D5AE252005622CB /* Record.swift in Sources */,
|
||||
565490C11D5AE236005622CB /* FetchRequest.swift in Sources */,
|
||||
568ECB1A25D9161600B71526 /* SQLSubquery.swift in Sources */,
|
||||
56D110D028AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
|
||||
5613ED4621A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
|
||||
5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */,
|
||||
56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
|
||||
566DDE0F288D763C0000DCFB /* Fixits.swift in Sources */,
|
||||
5656A8B22295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
|
||||
5653EB0B20944C7C00F46237 /* Association.swift in Sources */,
|
||||
56D110C128AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
|
||||
564CE59F21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
|
||||
56F5ABDA1D814330001F60CB /* NSData.swift in Sources */,
|
||||
56D110D528AFC81400E64463 /* PersistableRecord.swift in Sources */,
|
||||
564F9C341F07611900877A00 /* DatabaseFunction.swift in Sources */,
|
||||
5659F4961EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
56894FD12606589C00268F4D /* Decimal.swift in Sources */,
|
||||
@@ -2973,6 +3032,7 @@
|
||||
56AE64142229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
5613ED3721A95A5C00DC7A68 /* Map.swift in Sources */,
|
||||
5659F48E1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
56FA0C3228B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */,
|
||||
564CE43321AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
563B8FC724A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
566B9C2225C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
@@ -2997,7 +3057,6 @@
|
||||
563EF45D2163309F007DAACD /* Inflections.swift in Sources */,
|
||||
569D6DE0220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
|
||||
5611620A25757583007AAF99 /* JoinAssociation.swift in Sources */,
|
||||
567ECE512222E431009245CA /* GRDB-5.0.swift in Sources */,
|
||||
565490BF1D5AE236005622CB /* DatabaseValueConvertible.swift in Sources */,
|
||||
566B91191FA4C3F50012D5B0 /* DatabaseCollation.swift in Sources */,
|
||||
560233C62724234F00529DF3 /* SharedValueObservation.swift in Sources */,
|
||||
@@ -3016,6 +3075,7 @@
|
||||
56DDDDF6242F87C70025E381 /* ValueObservationScheduler.swift in Sources */,
|
||||
5659F49E1EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
5653EB0E20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
|
||||
56D110DA28AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */,
|
||||
565490DA1D5AE252005622CB /* QueryInterfaceRequest.swift in Sources */,
|
||||
563B8FAE24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
565490CA1D5AE252005622CB /* DatabaseDateComponents.swift in Sources */,
|
||||
@@ -3043,17 +3103,20 @@
|
||||
56FBFEDB2210731A00945324 /* SQLRequest.swift in Sources */,
|
||||
56F5ABD91D814330001F60CB /* Data.swift in Sources */,
|
||||
565490D41D5AE252005622CB /* (null) in Sources */,
|
||||
56D110FC28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */,
|
||||
56713FDF2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
566475D21D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
565490B61D5AE236005622CB /* Configuration.swift in Sources */,
|
||||
565490E11D5AE252005622CB /* PersistableRecord.swift in Sources */,
|
||||
565490E11D5AE252005622CB /* MutablePersistableRecord.swift in Sources */,
|
||||
569BBA50229170FA00478429 /* Inflections+English.swift in Sources */,
|
||||
563B8FB724A1D029007A48C9 /* ReceiveValuesOn.swift in Sources */,
|
||||
566B91391FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
56FA0C3B28B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */,
|
||||
565490C81D5AE252005622CB /* CGFloat.swift in Sources */,
|
||||
56F5ABDC1D814330001F60CB /* URL.swift in Sources */,
|
||||
569EF0E4200D2D8400A9FA45 /* DatabaseRegion.swift in Sources */,
|
||||
5695962B222C462D002CB7C9 /* HasManyThroughAssociation.swift in Sources */,
|
||||
56D110C628AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
|
||||
565490D31D5AE252005622CB /* (null) in Sources */,
|
||||
566475D91D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
56AACAAA22ACED7100A40F2A /* Fetch.swift in Sources */,
|
||||
@@ -3076,6 +3139,7 @@
|
||||
565490CD1D5AE252005622CB /* Date.swift in Sources */,
|
||||
5653EB0820944C7C00F46237 /* SQLForeignKeyRequest.swift in Sources */,
|
||||
565490BE1D5AE236005622CB /* DatabaseValue.swift in Sources */,
|
||||
56D110CB28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -3102,12 +3166,14 @@
|
||||
files = (
|
||||
568ECAA025D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56713FDE2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
56158781288D875E00A67323 /* Optional.swift in Sources */,
|
||||
5636E9BF1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
563EF42E2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
56BB6EAC1D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
563B8FC624A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
56300B791C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
|
||||
5656A8B12295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
566DDE0E288D763C0000DCFB /* Fixits.swift in Sources */,
|
||||
56CEB5561EAA359A00BFAF62 /* SQLExpression.swift in Sources */,
|
||||
5674A6F91F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
|
||||
566475D61D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
@@ -3115,6 +3181,7 @@
|
||||
56012BA8257404E000B4925B /* CommonTableExpression.swift in Sources */,
|
||||
56256ED125D1ACD0008C2BDD /* Table.swift in Sources */,
|
||||
5653EB0A20944C7C00F46237 /* Association.swift in Sources */,
|
||||
56D110FB28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */,
|
||||
56A2387E1B9C75030082EB20 /* Database.swift in Sources */,
|
||||
56CEB4FD1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
5605F15A1C672E4000235C62 /* CGFloat.swift in Sources */,
|
||||
@@ -3122,11 +3189,13 @@
|
||||
5605F1641C672E4000235C62 /* Date.swift in Sources */,
|
||||
566B91361FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
564CE43221AA901800652B19 /* ValueConcurrentObserver.swift in Sources */,
|
||||
56D110D928AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */,
|
||||
568ECA8B25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
56AACAA922ACED7100A40F2A /* Fetch.swift in Sources */,
|
||||
5605F1721C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
56CEB5141EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
|
||||
566475CF1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
56D110CF28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
|
||||
5659F49B1EA8D989004A4992 /* Pool.swift in Sources */,
|
||||
5653EB2220944C7C00F46237 /* HasOneAssociation.swift in Sources */,
|
||||
563082E52430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
@@ -3136,6 +3205,7 @@
|
||||
568D13202207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
|
||||
5674048A1CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
|
||||
563EF416215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
|
||||
56FA0C3A28B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */,
|
||||
563363C51C942C37000BE133 /* DatabaseWriter.swift in Sources */,
|
||||
5698AD1B1DAAD17D0056AF8C /* FTS5Tokenizer.swift in Sources */,
|
||||
5653EB0420944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
|
||||
@@ -3146,6 +3216,7 @@
|
||||
56A238941B9C750B0082EB20 /* DatabaseMigrator.swift in Sources */,
|
||||
5605F16A1C672E4000235C62 /* NSString.swift in Sources */,
|
||||
566B910C1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
56D110DE28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */,
|
||||
56A8C2331D1914540096E9D4 /* UUID.swift in Sources */,
|
||||
560D92411C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
|
||||
56A238A51B9C753B0082EB20 /* Record.swift in Sources */,
|
||||
@@ -3159,14 +3230,17 @@
|
||||
4E13D2F42769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
|
||||
5656A81F2295B12F001FF3FF /* SQLAssociation.swift in Sources */,
|
||||
5617294F223533F40006E219 /* EncodableRecord.swift in Sources */,
|
||||
56FA0C3128B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */,
|
||||
563B8FAD24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
5653EC132098738B00F46237 /* SQLGenerationContext.swift in Sources */,
|
||||
5657AB121D10899D006283EF /* URL.swift in Sources */,
|
||||
5616AAF2207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
56D110CA28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */,
|
||||
5659F48B1EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
56A2387C1B9C75030082EB20 /* Configuration.swift in Sources */,
|
||||
56DAA2DE1DE9C827006E10C8 /* Cursor.swift in Sources */,
|
||||
560A37A51C8F625000949E71 /* DatabasePool.swift in Sources */,
|
||||
56D110D428AFC81400E64463 /* PersistableRecord.swift in Sources */,
|
||||
56256EDA25D1B316008C2BDD /* ForeignKey.swift in Sources */,
|
||||
5674A7081F307FCD0095F066 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
56AE64132229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
@@ -3184,6 +3258,7 @@
|
||||
5605F15E1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
|
||||
5695962A222C462D002CB7C9 /* HasManyThroughAssociation.swift in Sources */,
|
||||
563363C11C942C04000BE133 /* DatabaseReader.swift in Sources */,
|
||||
56D110C528AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
|
||||
56B964BC1DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
5605F1661C672E4000235C62 /* NSNull.swift in Sources */,
|
||||
5656A8AE2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */,
|
||||
@@ -3199,7 +3274,6 @@
|
||||
569D6DDF220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
|
||||
56A238821B9C75030082EB20 /* DatabaseError.swift in Sources */,
|
||||
5653EB0D20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
|
||||
567ECE502222E431009245CA /* GRDB-5.0.swift in Sources */,
|
||||
566AD8B51D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
|
||||
5698AD241DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
568ECB1925D9161600B71526 /* SQLSubquery.swift in Sources */,
|
||||
@@ -3211,9 +3285,10 @@
|
||||
56CEB5041EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
563B8F93249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
5605F1741C672E4000235C62 /* StandardLibrary.swift in Sources */,
|
||||
56D110C028AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
|
||||
56E9FACC221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
566B9C2125C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
560D92481C672C4B00F4F92B /* PersistableRecord.swift in Sources */,
|
||||
560D92481C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */,
|
||||
5613ED4521A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
|
||||
560D92431C672C3E00F4F92B /* StatementColumnConvertible.swift in Sources */,
|
||||
56717272261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
|
||||
@@ -3333,7 +3408,6 @@
|
||||
56176C7F1EACCD2F000F3F2B /* EncryptionTests.swift in Sources */,
|
||||
56741EAC1E66A8B3003E422D /* FetchRequestTests.swift in Sources */,
|
||||
5672DE5C1CDB72520022BA81 /* DatabaseQueueBackupTests.swift in Sources */,
|
||||
56A2385E1B9C74A90082EB20 /* RecordCopyTests.swift in Sources */,
|
||||
56B86E7A220FF4E000524C16 /* SQLLiteralTests.swift in Sources */,
|
||||
56176C6C1EACCCC9000F3F2B /* FTS5PatternTests.swift in Sources */,
|
||||
56419C7024A519A3004967E1 /* Support.swift in Sources */,
|
||||
@@ -3643,7 +3717,6 @@
|
||||
5653EADA20944B4F00F46237 /* AssociationRowScopeSearchTests.swift in Sources */,
|
||||
563B5336267E2F90009549B5 /* TableTests.swift in Sources */,
|
||||
56D4965A1D81304E008276D7 /* FoundationNSDataTests.swift in Sources */,
|
||||
56D496741D81309E008276D7 /* RecordCopyTests.swift in Sources */,
|
||||
56D496791D81309E008276D7 /* RecordWithColumnNameManglingTests.swift in Sources */,
|
||||
56D4966C1D81309E008276D7 /* RecordMinimalPrimaryKeyRowIDTests.swift in Sources */,
|
||||
564CE5BE21B8FFA300652B19 /* DatabaseRegionObservationTests.swift in Sources */,
|
||||
@@ -3711,12 +3784,14 @@
|
||||
files = (
|
||||
568ECAA225D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56713FE02691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
56158783288D875E00A67323 /* Optional.swift in Sources */,
|
||||
AAA4DC77230F1E0600C74B15 /* FetchRequest.swift in Sources */,
|
||||
AAA4DC78230F1E0600C74B15 /* AssociationAggregate.swift in Sources */,
|
||||
AAA4DC79230F1E0600C74B15 /* SchedulingWatchdog.swift in Sources */,
|
||||
563B8FC824A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
AAA4DC7A230F1E0600C74B15 /* QueryInterfaceRequest.swift in Sources */,
|
||||
AAA4DC7B230F1E0600C74B15 /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
566DDE10288D763C0000DCFB /* Fixits.swift in Sources */,
|
||||
AAA4DC7C230F1E0600C74B15 /* SQLExpression.swift in Sources */,
|
||||
AAA4DC7D230F1E0600C74B15 /* EncodableRecord+Encodable.swift in Sources */,
|
||||
AAA4DC7F230F1E0600C74B15 /* SQLOperators.swift in Sources */,
|
||||
@@ -3724,6 +3799,7 @@
|
||||
56012BB2257404E200B4925B /* CommonTableExpression.swift in Sources */,
|
||||
56256ED325D1ACD0008C2BDD /* Table.swift in Sources */,
|
||||
AAA4DC81230F1E0600C74B15 /* Association.swift in Sources */,
|
||||
56D110FD28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */,
|
||||
AAA4DC82230F1E0600C74B15 /* Database.swift in Sources */,
|
||||
AAA4DC83230F1E0600C74B15 /* FTS3.swift in Sources */,
|
||||
AAA4DC84230F1E0600C74B15 /* CGFloat.swift in Sources */,
|
||||
@@ -3731,11 +3807,13 @@
|
||||
AAA4DC87230F1E0600C74B15 /* Date.swift in Sources */,
|
||||
AAA4DC89230F1E0600C74B15 /* TransactionObserver.swift in Sources */,
|
||||
AAA4DC8A230F1E0600C74B15 /* ValueConcurrentObserver.swift in Sources */,
|
||||
56D110DB28AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */,
|
||||
568ECA8D25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
AAA4DC8B230F1E0600C74B15 /* Fetch.swift in Sources */,
|
||||
AAA4DC8C230F1E0600C74B15 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
AAA4DC8D230F1E0600C74B15 /* FTS3+QueryInterface.swift in Sources */,
|
||||
AAA4DC8E230F1E0600C74B15 /* SQLFunctions.swift in Sources */,
|
||||
56D110D128AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
|
||||
AAA4DC8F230F1E0600C74B15 /* Pool.swift in Sources */,
|
||||
AAA4DC90230F1E0600C74B15 /* HasOneAssociation.swift in Sources */,
|
||||
563082E72430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
@@ -3745,6 +3823,7 @@
|
||||
AAA4DC94230F1E0600C74B15 /* SQLQueryGenerator.swift in Sources */,
|
||||
AAA4DC95230F1E0600C74B15 /* RowAdapter.swift in Sources */,
|
||||
AAA4DC96230F1E0600C74B15 /* OrderedDictionary.swift in Sources */,
|
||||
56FA0C3C28B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */,
|
||||
AAA4DC97230F1E0600C74B15 /* DatabaseWriter.swift in Sources */,
|
||||
AAA4DC98230F1E0600C74B15 /* FTS5Tokenizer.swift in Sources */,
|
||||
AAA4DC99230F1E0600C74B15 /* BelongsToAssociation.swift in Sources */,
|
||||
@@ -3755,6 +3834,7 @@
|
||||
AAA4DC9E230F1E0600C74B15 /* DatabaseMigrator.swift in Sources */,
|
||||
AAA4DC9F230F1E0600C74B15 /* NSString.swift in Sources */,
|
||||
AAA4DCA0230F1E0600C74B15 /* Database+Statements.swift in Sources */,
|
||||
56D110E028AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */,
|
||||
AAA4DCA1230F1E0600C74B15 /* UUID.swift in Sources */,
|
||||
AAA4DCA2230F1E0600C74B15 /* DatabaseValueConvertible.swift in Sources */,
|
||||
AAA4DCA4230F1E0600C74B15 /* Record.swift in Sources */,
|
||||
@@ -3768,14 +3848,17 @@
|
||||
4E13D2F62769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
|
||||
AAA4DCA9230F1E0600C74B15 /* SQLAssociation.swift in Sources */,
|
||||
AAA4DCAA230F1E0600C74B15 /* EncodableRecord.swift in Sources */,
|
||||
56FA0C3328B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */,
|
||||
563B8FAF24A1CE44007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
AAA4DCAC230F1E0600C74B15 /* SQLGenerationContext.swift in Sources */,
|
||||
AAA4DCAD230F1E0600C74B15 /* URL.swift in Sources */,
|
||||
AAA4DCAE230F1E0600C74B15 /* RequestProtocols.swift in Sources */,
|
||||
56D110CC28AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */,
|
||||
AAA4DCAF230F1E0600C74B15 /* Utils.swift in Sources */,
|
||||
AAA4DCB0230F1E0600C74B15 /* Configuration.swift in Sources */,
|
||||
AAA4DCB1230F1E0600C74B15 /* Cursor.swift in Sources */,
|
||||
AAA4DCB2230F1E0600C74B15 /* DatabasePool.swift in Sources */,
|
||||
56D110D628AFC81400E64463 /* PersistableRecord.swift in Sources */,
|
||||
56256EDC25D1B316008C2BDD /* ForeignKey.swift in Sources */,
|
||||
AAA4DCB3230F1E0600C74B15 /* DatabaseValueConvertible+ReferenceConvertible.swift in Sources */,
|
||||
AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */,
|
||||
@@ -3793,6 +3876,7 @@
|
||||
AAA4DCC4230F1E0600C74B15 /* DatabaseDateComponents.swift in Sources */,
|
||||
AAA4DCC5230F1E0600C74B15 /* HasManyThroughAssociation.swift in Sources */,
|
||||
AAA4DCC6230F1E0600C74B15 /* DatabaseReader.swift in Sources */,
|
||||
56D110C728AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
|
||||
AAA4DCC8230F1E0600C74B15 /* FTS5Pattern.swift in Sources */,
|
||||
AAA4DCC9230F1E0600C74B15 /* NSNull.swift in Sources */,
|
||||
AAA4DCCA230F1E0600C74B15 /* TableRecord+Association.swift in Sources */,
|
||||
@@ -3808,7 +3892,6 @@
|
||||
AAA4DCD0230F1E0600C74B15 /* SQLInterpolation.swift in Sources */,
|
||||
AAA4DCD1230F1E0600C74B15 /* DatabaseError.swift in Sources */,
|
||||
AAA4DCD2230F1E0600C74B15 /* HasManyAssociation.swift in Sources */,
|
||||
AAA4DCD3230F1E0600C74B15 /* GRDB-5.0.swift in Sources */,
|
||||
AAA4DCD4230F1E0600C74B15 /* TableDefinition.swift in Sources */,
|
||||
AAA4DCD5230F1E0600C74B15 /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
568ECB1B25D9161600B71526 /* SQLSubquery.swift in Sources */,
|
||||
@@ -3820,9 +3903,10 @@
|
||||
AAA4DCDC230F1E0600C74B15 /* FTS4.swift in Sources */,
|
||||
563B8F95249E6171007A48C9 /* Trace.swift in Sources */,
|
||||
AAA4DCDD230F1E0600C74B15 /* StandardLibrary.swift in Sources */,
|
||||
56D110C228AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
|
||||
AAA4DCDE230F1E0600C74B15 /* SQLInterpolation+QueryInterface.swift in Sources */,
|
||||
566B9C2325C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
AAA4DCDF230F1E0600C74B15 /* PersistableRecord.swift in Sources */,
|
||||
AAA4DCDF230F1E0600C74B15 /* MutablePersistableRecord.swift in Sources */,
|
||||
AAA4DCE0230F1E0600C74B15 /* ValueReducer.swift in Sources */,
|
||||
AAA4DCE2230F1E0600C74B15 /* StatementColumnConvertible.swift in Sources */,
|
||||
56717274261C68EA00423B6F /* CaseInsensitiveIdentifier.swift in Sources */,
|
||||
@@ -3942,7 +4026,6 @@
|
||||
AAA4DD5A230F262000C74B15 /* EncryptionTests.swift in Sources */,
|
||||
AAA4DD5B230F262000C74B15 /* FetchRequestTests.swift in Sources */,
|
||||
AAA4DD5C230F262000C74B15 /* DatabaseQueueBackupTests.swift in Sources */,
|
||||
AAA4DD5D230F262000C74B15 /* RecordCopyTests.swift in Sources */,
|
||||
AAA4DD5E230F262000C74B15 /* SQLLiteralTests.swift in Sources */,
|
||||
AAA4DD5F230F262000C74B15 /* FTS5PatternTests.swift in Sources */,
|
||||
56419C7524A519A4004967E1 /* Support.swift in Sources */,
|
||||
@@ -4084,12 +4167,14 @@
|
||||
files = (
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
56158780288D875E00A67323 /* Optional.swift in Sources */,
|
||||
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
|
||||
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
|
||||
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
|
||||
5613ED4421A95B2C00DC7A68 /* ValueReducer.swift in Sources */,
|
||||
5636E9BC1D22574100B9B05F /* FetchRequest.swift in Sources */,
|
||||
566DDE0D288D763C0000DCFB /* Fixits.swift in Sources */,
|
||||
56BB6EA91D3009B100A1CA52 /* SchedulingWatchdog.swift in Sources */,
|
||||
563EF44A2161F179007DAACD /* Inflections.swift in Sources */,
|
||||
566B91091FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
@@ -4097,6 +4182,7 @@
|
||||
56012B9F257404DF00B4925B /* CommonTableExpression.swift in Sources */,
|
||||
56256ED025D1ACD0008C2BDD /* Table.swift in Sources */,
|
||||
563B06AB217EF0CC00B38F35 /* ValueObservation.swift in Sources */,
|
||||
56D110FA28AFC97E00E64463 /* MutablePersistableRecord+DAO.swift in Sources */,
|
||||
56CEB5111EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
|
||||
5659F4901EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
|
||||
566A841A2041146100E50BFD /* DatabaseSnapshot.swift in Sources */,
|
||||
@@ -4104,11 +4190,13 @@
|
||||
56CEB4F11EAA2EFA00BFAF62 /* FetchableRecord.swift in Sources */,
|
||||
56D91AA22205E03700770D8D /* SQLRelation.swift in Sources */,
|
||||
56300B781C53F592005A543B /* QueryInterfaceRequest.swift in Sources */,
|
||||
56D110D828AFC84000E64463 /* PersistableRecord+Insert.swift in Sources */,
|
||||
568ECA8A25D7013000B71526 /* SQLSelection.swift in Sources */,
|
||||
56AACAA822ACED7100A40F2A /* Fetch.swift in Sources */,
|
||||
566B91331FA4D3810012D5B0 /* TransactionObserver.swift in Sources */,
|
||||
566475D31D981D5E00FF74B8 /* SQLOperators.swift in Sources */,
|
||||
56CEB4FA1EAA2F4D00BFAF62 /* FTS3.swift in Sources */,
|
||||
56D110CE28AFC72100E64463 /* MutablePersistableRecord+Delete.swift in Sources */,
|
||||
563082E42430B6BE00C14A05 /* DatabaseCancellable.swift in Sources */,
|
||||
564CE59D21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
|
||||
5698AD351DABAF4A0056AF8C /* FTS5CustomTokenizer.swift in Sources */,
|
||||
@@ -4118,6 +4206,7 @@
|
||||
5605F1631C672E4000235C62 /* Date.swift in Sources */,
|
||||
5605F1711C672E4000235C62 /* DatabaseValueConvertible+RawRepresentable.swift in Sources */,
|
||||
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
|
||||
56FA0C3928B20ABE00B2DFF7 /* PersistableRecord+Upsert.swift in Sources */,
|
||||
566475CC1D981D5E00FF74B8 /* SQLFunctions.swift in Sources */,
|
||||
5698AC371D9E5A590056AF8C /* FTS3Pattern.swift in Sources */,
|
||||
563EF415215F87EB007DAACD /* OrderedDictionary.swift in Sources */,
|
||||
@@ -4128,6 +4217,7 @@
|
||||
56848973242DE36F002F9702 /* ValueObservationScheduler.swift in Sources */,
|
||||
5674A6F41F307F600095F066 /* EncodableRecord+Encodable.swift in Sources */,
|
||||
5664759A1D97D8A000FF74B8 /* SQLCollection.swift in Sources */,
|
||||
56D110DD28AFC8B400E64463 /* PersistableRecord+Save.swift in Sources */,
|
||||
567404881CEF84C8003ED5CC /* RowAdapter.swift in Sources */,
|
||||
5653EB0320944C7C00F46237 /* BelongsToAssociation.swift in Sources */,
|
||||
563363C41C942C37000BE133 /* DatabaseWriter.swift in Sources */,
|
||||
@@ -4141,14 +4231,17 @@
|
||||
4E13D2F32769B87F0037588C /* DatabaseBackupProgress.swift in Sources */,
|
||||
560A37A71C8FF6E500949E71 /* SerializedDatabase.swift in Sources */,
|
||||
563B8FAC24A1CE43007A48C9 /* DatabasePublishers.swift in Sources */,
|
||||
56FA0C3028B1F2DC00B2DFF7 /* MutablePersistableRecord+Upsert.swift in Sources */,
|
||||
5605F1691C672E4000235C62 /* NSString.swift in Sources */,
|
||||
560D92401C672C3E00F4F92B /* DatabaseValueConvertible.swift in Sources */,
|
||||
56A8C2301D1914540096E9D4 /* UUID.swift in Sources */,
|
||||
56CEB5011EAA2F4D00BFAF62 /* FTS4.swift in Sources */,
|
||||
56D110C928AFC68B00E64463 /* MutablePersistableRecord+Save.swift in Sources */,
|
||||
56AE64122229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
|
||||
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */,
|
||||
56256ED925D1B316008C2BDD /* ForeignKey.swift in Sources */,
|
||||
56D51D001EA789FA0074638A /* FetchableRecord+TableRecord.swift in Sources */,
|
||||
56D110D328AFC81400E64463 /* PersistableRecord.swift in Sources */,
|
||||
5653EB0920944C7C00F46237 /* Association.swift in Sources */,
|
||||
56A238851B9C75030082EB20 /* DatabaseValue.swift in Sources */,
|
||||
5671FC201DA3CAC9003BF4FF /* FTS3TokenizerDescriptor.swift in Sources */,
|
||||
@@ -4166,6 +4259,7 @@
|
||||
566B912B1FA4D0CC0012D5B0 /* StatementAuthorizer.swift in Sources */,
|
||||
56A2388B1B9C75030082EB20 /* Statement.swift in Sources */,
|
||||
5656A8AD2295BFD7001FF3FF /* TableRecord+Association.swift in Sources */,
|
||||
56D110C428AFC5A800E64463 /* MutablePersistableRecord+Update.swift in Sources */,
|
||||
5690C3401D23E82A00E59934 /* Data.swift in Sources */,
|
||||
5659F4881EA8D94E004A4992 /* Utils.swift in Sources */,
|
||||
566BE71E2342542F00A8254B /* LockedBox.swift in Sources */,
|
||||
@@ -4176,7 +4270,6 @@
|
||||
569D6DDE220EF9E100A058A9 /* SQLInterpolation.swift in Sources */,
|
||||
568D131F2207213E00674B58 /* SQLQueryGenerator.swift in Sources */,
|
||||
5605F15D1C672E4000235C62 /* DatabaseDateComponents.swift in Sources */,
|
||||
567ECE4F2222E431009245CA /* GRDB-5.0.swift in Sources */,
|
||||
56894FB72606589700268F4D /* Decimal.swift in Sources */,
|
||||
56B964B91DA51D0A0002DA19 /* FTS5Pattern.swift in Sources */,
|
||||
56FBFEDA2210731A00945324 /* SQLRequest.swift in Sources */,
|
||||
@@ -4193,6 +4286,7 @@
|
||||
5698AC781DA37DCB0056AF8C /* VirtualTableModule.swift in Sources */,
|
||||
56A2387D1B9C75030082EB20 /* Database.swift in Sources */,
|
||||
566AD8B21D5318F4002EC1A8 /* TableDefinition.swift in Sources */,
|
||||
56D110BF28AFC51000E64463 /* MutablePersistableRecord+Insert.swift in Sources */,
|
||||
566B9C2025C6CC24004542CF /* RowDecodingError.swift in Sources */,
|
||||
5698AD211DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
|
||||
56A238831B9C75030082EB20 /* DatabaseQueue.swift in Sources */,
|
||||
@@ -4205,7 +4299,7 @@
|
||||
5653EB2120944C7C00F46237 /* HasOneAssociation.swift in Sources */,
|
||||
5605F1731C672E4000235C62 /* StandardLibrary.swift in Sources */,
|
||||
5653EC122098738B00F46237 /* SQLGenerationContext.swift in Sources */,
|
||||
560D92471C672C4B00F4F92B /* PersistableRecord.swift in Sources */,
|
||||
560D92471C672C4B00F4F92B /* MutablePersistableRecord.swift in Sources */,
|
||||
5674A6E41F307F0E0095F066 /* DatabaseValueConvertible+Decodable.swift in Sources */,
|
||||
5653EB0C20944C7C00F46237 /* HasManyAssociation.swift in Sources */,
|
||||
5657AAB91D107001006283EF /* NSData.swift in Sources */,
|
||||
@@ -4307,6 +4401,7 @@
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
INFOPLIST_FILE = Tests/Info.plist;
|
||||
@@ -4328,6 +4423,7 @@
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
INFOPLIST_FILE = Tests/Info.plist;
|
||||
@@ -4471,6 +4567,7 @@
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
INFOPLIST_FILE = Tests/Info.plist;
|
||||
@@ -4497,6 +4594,7 @@
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
GCC_NO_COMMON_BLOCKS = YES;
|
||||
INFOPLIST_FILE = Tests/Info.plist;
|
||||
@@ -4671,6 +4769,7 @@
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
@@ -4728,6 +4827,7 @@
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = YES;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
GCC_C_LANGUAGE_STANDARD = gnu99;
|
||||
@@ -4757,6 +4857,7 @@
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEFINES_MODULE = YES;
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = 1;
|
||||
@@ -4782,6 +4883,7 @@
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CLANG_ENABLE_OBJC_WEAK = YES;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEFINES_MODULE = YES;
|
||||
DYLIB_COMPATIBILITY_VERSION = 1;
|
||||
DYLIB_CURRENT_VERSION = 1;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1230"
|
||||
LastUpgradeVersion = "1400"
|
||||
version = "1.3">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
-3
@@ -10,9 +10,6 @@
|
||||
<FileRef
|
||||
location = "group:TransactionObserver.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:CustomizedDecodingOfDatabaseRows.playground">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Associations.playground">
|
||||
</FileRef>
|
||||
|
||||
@@ -196,7 +196,7 @@ public struct Configuration {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
///
|
||||
/// // fatal error: A transaction has been left opened at the end of a database access
|
||||
/// try dbQueue.inDatabase { db in
|
||||
@@ -208,7 +208,7 @@ public struct Configuration {
|
||||
///
|
||||
/// var config = Configuration()
|
||||
/// config.allowsUnsafeTransactions = true
|
||||
/// let dbQueue = DatabaseQueue(configuration: config)
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
///
|
||||
/// try dbQueue.inDatabase { db in
|
||||
/// try db.beginTransaction()
|
||||
@@ -295,7 +295,7 @@ public struct Configuration {
|
||||
var SQLiteConnectionDidOpen: (() -> Void)?
|
||||
var SQLiteConnectionWillClose: ((SQLiteConnection) -> Void)?
|
||||
var SQLiteConnectionDidClose: (() -> Void)?
|
||||
var SQLiteOpenFlags: Int32 {
|
||||
var SQLiteOpenFlags: CInt {
|
||||
let readWriteFlags = readonly ? SQLITE_OPEN_READONLY : (SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE)
|
||||
return threadingMode.SQLiteOpenFlags | readWriteFlags
|
||||
}
|
||||
|
||||
+28
-23
@@ -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
|
||||
@@ -234,7 +237,7 @@ extension Sequence {
|
||||
/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`,
|
||||
/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`,
|
||||
/// `suffix`.
|
||||
public protocol Cursor: AnyObject {
|
||||
public protocol Cursor<Element>: AnyObject {
|
||||
/// The type of element traversed by the cursor.
|
||||
associatedtype Element
|
||||
|
||||
@@ -247,10 +250,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 +316,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.
|
||||
@@ -685,14 +690,14 @@ public final class AnyCursor<Element>: Cursor {
|
||||
|
||||
/// 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 {
|
||||
public convenience init(iterator: some IteratorProtocol<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 {
|
||||
public convenience init(_ s: some Sequence<Element>) {
|
||||
self.init(iterator: s.makeIterator())
|
||||
}
|
||||
|
||||
|
||||
+165
-104
@@ -1,5 +1,30 @@
|
||||
extension Database {
|
||||
/// A SQLite schema. See <https://sqlite.org/lang_naming.html>
|
||||
/// A cache for the available database schemas.
|
||||
struct SchemaCache {
|
||||
/// The available schema identifiers, in the order of SQLite resolution:
|
||||
/// temp, main, then attached databases.
|
||||
var schemaIdentifiers: [SchemaIdentifier]?
|
||||
|
||||
/// The schema cache for each identifier.
|
||||
fileprivate var schemas: [SchemaIdentifier: DatabaseSchemaCache] = [:]
|
||||
|
||||
/// The schema cache for a given identifier
|
||||
subscript(schemaID: SchemaIdentifier) -> DatabaseSchemaCache { // internal so that it can be tested
|
||||
get {
|
||||
schemas[schemaID] ?? DatabaseSchemaCache()
|
||||
}
|
||||
set {
|
||||
schemas[schemaID] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
mutating func clear() {
|
||||
schemaIdentifiers = nil
|
||||
schemas.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
/// An SQLite schema. See <https://sqlite.org/lang_naming.html>
|
||||
enum SchemaIdentifier: Hashable {
|
||||
/// The main database
|
||||
case main
|
||||
@@ -10,7 +35,12 @@ extension Database {
|
||||
/// An attached database: <https://sqlite.org/lang_attach.html>
|
||||
case attached(String)
|
||||
|
||||
/// The name of the schema in SQL queries
|
||||
/// The name of the schema in SQL queries.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SELECT * FROM main.player;
|
||||
/// -- ~~~~
|
||||
var sql: String {
|
||||
switch self {
|
||||
case .main: return "main"
|
||||
@@ -29,12 +59,12 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
/// A table identifier
|
||||
/// The identifier of a database table or view.
|
||||
struct TableIdentifier {
|
||||
/// The SQLite schema
|
||||
var schemaID: SchemaIdentifier
|
||||
|
||||
/// The table name
|
||||
/// The table or view name
|
||||
var name: String
|
||||
|
||||
/// Returns the receiver, quoted for safe insertion as an identifier in
|
||||
@@ -60,7 +90,7 @@ extension Database {
|
||||
// We also clear statement cache despite the automatic statement
|
||||
// recompilation (see https://www.sqlite.org/c3ref/prepare.html)
|
||||
// because the automatic statement recompilation only happens a
|
||||
// limited number of times.
|
||||
// limited number of times (`SQLITE_MAX_SCHEMA_RETRY`).
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
}
|
||||
@@ -68,9 +98,13 @@ extension Database {
|
||||
/// Clears the database schema cache if the database schema has changed
|
||||
/// since this method was last called.
|
||||
func clearSchemaCacheIfNeeded() throws {
|
||||
// `PRAGMA schema_version` fetches a 4-bytes integer (Int32), stored
|
||||
// at offset 40 of the database header:
|
||||
// <https://sqlite.org/pragma.html#pragma_schema_version>
|
||||
// <https://sqlite.org/fileformat2.html#database_header>
|
||||
let schemaVersion = try Int32.fetchOne(internalCachedStatement(sql: "PRAGMA schema_version"))
|
||||
if _lastSchemaVersion != schemaVersion {
|
||||
_lastSchemaVersion = schemaVersion
|
||||
if lastSchemaVersion != schemaVersion {
|
||||
lastSchemaVersion = schemaVersion
|
||||
clearSchemaCache()
|
||||
}
|
||||
}
|
||||
@@ -82,17 +116,17 @@ extension Database {
|
||||
return schemaIdentifiers
|
||||
}
|
||||
|
||||
var schemaIdentifiers = try Row
|
||||
.fetchAll(self, sql: "PRAGMA database_list")
|
||||
var schemaIdentifiers = try Array(Row
|
||||
.fetchCursor(self, sql: "PRAGMA database_list")
|
||||
.map { row -> SchemaIdentifier in
|
||||
switch row[1] as String {
|
||||
case "main": return .main
|
||||
case "temp": return .temp
|
||||
case let other: return .attached(other)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Temp schema shadows other schema: put it first
|
||||
// Temp schema shadows all other schemas: put it first
|
||||
if let tempIdx = schemaIdentifiers.firstIndex(of: .temp) {
|
||||
schemaIdentifiers.swapAt(tempIdx, 0)
|
||||
}
|
||||
@@ -101,7 +135,8 @@ extension Database {
|
||||
return schemaIdentifiers
|
||||
}
|
||||
|
||||
/// Returns whether a table exists in the main or temp schema.
|
||||
/// Returns whether a table exists, in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func tableExists(_ name: String) throws -> Bool {
|
||||
try schemaIdentifiers().contains {
|
||||
try exists(type: .table, name: name, in: $0)
|
||||
@@ -126,17 +161,7 @@ extension Database {
|
||||
// > "sqlite_".
|
||||
tableName.starts(with: "sqlite_") || tableName.starts(with: "pragma_")
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal SQLite table.
|
||||
///
|
||||
/// Those are tables whose name begins with `sqlite_` and `pragma_`.
|
||||
///
|
||||
/// For more information, see <https://www.sqlite.org/fileformat2.html>
|
||||
@available(*, deprecated, message: "Use Database.isSQLiteInternalTable(_:) static method instead.")
|
||||
public func isSQLiteInternalTable(_ tableName: String) -> Bool {
|
||||
Self.isSQLiteInternalTable(tableName)
|
||||
}
|
||||
|
||||
|
||||
/// Returns whether a table is an internal GRDB table.
|
||||
///
|
||||
/// Those are tables whose name begins with "grdb_".
|
||||
@@ -144,22 +169,16 @@ extension Database {
|
||||
tableName.starts(with: "grdb_")
|
||||
}
|
||||
|
||||
/// Returns whether a table is an internal GRDB table.
|
||||
///
|
||||
/// Those are tables whose name begins with "grdb_".
|
||||
@available(*, deprecated, message: "Use Database.isGRDBInternalTable(_:) static method instead.")
|
||||
public func isGRDBInternalTable(_ tableName: String) -> Bool {
|
||||
Self.isGRDBInternalTable(tableName)
|
||||
}
|
||||
|
||||
/// Returns whether a view exists in the main or temp schema.
|
||||
/// Returns whether a view exists, in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func viewExists(_ name: String) throws -> Bool {
|
||||
try schemaIdentifiers().contains {
|
||||
try exists(type: .view, name: name, in: $0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether a trigger exists in the main or temp schema.
|
||||
/// Returns whether a trigger exists, in the main or temp schema, or in an
|
||||
/// attached database.
|
||||
public func triggerExists(_ name: String) throws -> Bool {
|
||||
try schemaIdentifiers().contains {
|
||||
try exists(type: .trigger, name: name, in: $0)
|
||||
@@ -167,12 +186,9 @@ extension Database {
|
||||
}
|
||||
|
||||
private func exists(type: SchemaObjectType, name: String, in schemaID: SchemaIdentifier) throws -> Bool {
|
||||
// SQlite identifiers are case-insensitive, case-preserving:
|
||||
// SQLite identifiers are case-insensitive, case-preserving:
|
||||
// http://www.alberton.info/dbms_identifiers_and_case_sensitivity.html
|
||||
let name = name.lowercased()
|
||||
return try schema(schemaID)
|
||||
.names(ofType: type)
|
||||
.contains { $0.lowercased() == name }
|
||||
try schema(schemaID).containsObjectNamed(name, ofType: type)
|
||||
}
|
||||
|
||||
/// The primary key for table named `tableName`.
|
||||
@@ -246,7 +262,7 @@ extension Database {
|
||||
primaryKey = .hiddenRowID
|
||||
case 1:
|
||||
// Single column
|
||||
let pkColumn = pkColumns.first!
|
||||
let pkColumn = pkColumns[0]
|
||||
|
||||
// https://www.sqlite.org/lang_createtable.html:
|
||||
//
|
||||
@@ -292,12 +308,21 @@ extension Database {
|
||||
///
|
||||
/// - precondition: table exists.
|
||||
private func tableHasRowID(_ table: TableIdentifier) throws -> Bool {
|
||||
// Not need to cache the result, because this information feeds
|
||||
// No need to cache the result, because this information feeds
|
||||
// `PrimaryKeyInfo`, which is cached.
|
||||
//
|
||||
// Use a distinctive alias so that we better understand in the
|
||||
// future why this query appears in the error log.
|
||||
// https://github.com/groue/GRDB.swift/issues/945#issuecomment-804896196
|
||||
// To check if the table has a rowid, we compile a statement that
|
||||
// selects the `rowid` column. If compilation fails, we assume that the
|
||||
// table is WITHOUT ROWID. This is not a very robust test (users may
|
||||
// create WITHOUT ROWID tables with a `rowid` column), but nobody has
|
||||
// reported any problem yet.
|
||||
//
|
||||
// Since compilation may fail, we may feed the SQLite error log, and
|
||||
// users may wonder what are those errors. That's why we use a
|
||||
// distinctive alias (`checkWithoutRowidOptimization`), so that anyone
|
||||
// can search the GRDB code, find this documentation, and understand why
|
||||
// this query appears in the error log:
|
||||
// <https://github.com/groue/GRDB.swift/issues/945#issuecomment-804896196>
|
||||
//
|
||||
// We don't use `try makeStatement(sql:)` in order to avoid throwing an
|
||||
// error (this annoys users who set a breakpoint on Swift errors).
|
||||
@@ -316,8 +341,9 @@ extension Database {
|
||||
/// SQLite does not define any index for INTEGER PRIMARY KEY columns: this
|
||||
/// method does not return any index that represents the primary key.
|
||||
///
|
||||
/// If you want to know if a set of columns uniquely identify a row, prefer
|
||||
/// `table(_:hasUniqueKey:)` instead.
|
||||
/// If you want to know if a set of columns uniquely identifies a row, because
|
||||
/// the columns contain the primary key or a unique index, use
|
||||
/// ``table(_:hasUniqueKey:)``.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
public func indexes(on tableName: String) throws -> [IndexInfo] {
|
||||
@@ -341,6 +367,7 @@ extension Database {
|
||||
.compactMap { row -> IndexInfo? in
|
||||
let indexName: String = row[1]
|
||||
let unique: Bool = row[2]
|
||||
let origin: IndexInfo.Origin = row[3]
|
||||
|
||||
let indexInfoRows = try Row
|
||||
// [seqno:0 cid:2 name:"column"]
|
||||
@@ -362,7 +389,7 @@ extension Database {
|
||||
}
|
||||
columns.append(column)
|
||||
}
|
||||
return IndexInfo(name: indexName, columns: columns, unique: unique)
|
||||
return IndexInfo(name: indexName, columns: columns, isUnique: unique, origin: origin)
|
||||
}
|
||||
|
||||
if indexes.isEmpty {
|
||||
@@ -379,12 +406,21 @@ extension Database {
|
||||
}
|
||||
|
||||
/// True if a sequence of columns uniquely identifies a row, that is to say
|
||||
/// if the columns are the primary key, or if there is a unique index on them.
|
||||
public func table<T: Sequence>(
|
||||
/// if the columns contain the primary key, or a unique index.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
|
||||
/// // CREATE UNIQUE INDEX i ON t(a, b);
|
||||
/// try db.table("t", hasUniqueKey: ["id"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["a", "b"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["c"]) // false
|
||||
/// try db.table("t", hasUniqueKey: ["id", "a"]) // true
|
||||
/// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true
|
||||
public func table(
|
||||
_ tableName: String,
|
||||
hasUniqueKey columns: T)
|
||||
hasUniqueKey columns: some Sequence<String>)
|
||||
throws -> Bool
|
||||
where T.Iterator.Element == String
|
||||
{
|
||||
try columnsForUniqueKey(Array(columns), in: tableName) != nil
|
||||
}
|
||||
@@ -481,6 +517,12 @@ extension Database {
|
||||
throw DatabaseError.noSuchTable(tableName)
|
||||
}
|
||||
|
||||
private func foreignKeyViolations(in table: TableIdentifier) throws -> RecordCursor<ForeignKeyViolation> {
|
||||
try ForeignKeyViolation.fetchCursor(self, sql: """
|
||||
PRAGMA \(table.schemaID.sql).foreign_key_check(\(table.name.quotedDatabaseIdentifier))
|
||||
""")
|
||||
}
|
||||
|
||||
/// Throws a DatabaseError of extended code `SQLITE_CONSTRAINT_FOREIGNKEY`
|
||||
/// if there exists a foreign key violation in the database.
|
||||
public func checkForeignKeys() throws {
|
||||
@@ -493,20 +535,14 @@ extension Database {
|
||||
try checkForeignKeys(from: foreignKeyViolations(in: tableName))
|
||||
}
|
||||
|
||||
private func foreignKeyViolations(in table: TableIdentifier) throws -> RecordCursor<ForeignKeyViolation> {
|
||||
try ForeignKeyViolation.fetchCursor(self, sql: """
|
||||
PRAGMA \(table.schemaID.sql).foreign_key_check(\(table.name.quotedDatabaseIdentifier))
|
||||
""")
|
||||
}
|
||||
|
||||
private func checkForeignKeys(from violations: RecordCursor<ForeignKeyViolation>) throws {
|
||||
if let violation = try violations.next() {
|
||||
throw violation.databaseError(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the actual name of the database table, in the main or temp
|
||||
/// schema, or nil if the table does not exist.
|
||||
/// Returns the actual name of the database table, or nil if the table does
|
||||
/// not exist.
|
||||
///
|
||||
/// - throws: A DatabaseError if table does not exist.
|
||||
func canonicalTableName(_ tableName: String) throws -> String? {
|
||||
@@ -590,14 +626,6 @@ extension Database {
|
||||
// 2 | lastName | TEXT | 0 | NULL | 0 | 0
|
||||
let columnInfoQuery: String
|
||||
if sqlite3_libversion_number() < 3026000 {
|
||||
if sqlite3_libversion_number() < 3008005 {
|
||||
// Work around a bug in SQLite where PRAGMA table_info would
|
||||
// return a result even after the table was deleted.
|
||||
if try !tableExists(table) {
|
||||
schemaCache[table.schemaID].set(columns: .missing, forTable: table.name)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
columnInfoQuery = "PRAGMA \(table.schemaID.sql).table_info(\(table.name.quotedDatabaseIdentifier))"
|
||||
} else {
|
||||
// Use PRAGMA table_xinfo so that we can load generated columns
|
||||
@@ -625,14 +653,14 @@ extension Database {
|
||||
return columns
|
||||
}
|
||||
|
||||
/// If there exists a unique key on columns, return the columns
|
||||
/// ordered as the matching index (or primary key). Case of returned columns
|
||||
/// is not guaranteed.
|
||||
func columnsForUniqueKey<T: Sequence>(
|
||||
_ columns: T,
|
||||
/// If there exists a unique key that contains those columns, this method
|
||||
/// returns the columns of the unique key, ordered as the matching index (or
|
||||
/// primary key). The case of returned columns is not guaranteed to match
|
||||
/// the case of input columns.
|
||||
func columnsForUniqueKey(
|
||||
_ columns: some Sequence<String>,
|
||||
in tableName: String)
|
||||
throws -> [String]?
|
||||
where T.Iterator.Element == String
|
||||
{
|
||||
let lowercasedColumns = Set(columns.map { $0.lowercased() })
|
||||
if lowercasedColumns.isEmpty {
|
||||
@@ -640,25 +668,26 @@ extension Database {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Assume "rowid" is a primary key
|
||||
if lowercasedColumns == ["rowid"] {
|
||||
// Check rowid
|
||||
let primaryKey = try self.primaryKey(tableName)
|
||||
if primaryKey.tableHasRowID && lowercasedColumns == ["rowid"] {
|
||||
return ["rowid"]
|
||||
}
|
||||
|
||||
// Check primaryKey.
|
||||
let primaryKey = try self.primaryKey(tableName)
|
||||
// Check primaryKey
|
||||
if Set(primaryKey.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns) {
|
||||
return primaryKey.columns
|
||||
}
|
||||
|
||||
// Is there is an explicit unique index on the columns?
|
||||
let indexes = try self.indexes(on: tableName)
|
||||
let matchingIndex = indexes.first { index in
|
||||
// Check unique indexes
|
||||
let matchingIndex = try indexes(on: tableName).first { index in
|
||||
index.isUnique && Set(index.columns.map { $0.lowercased() }).isSubset(of: lowercasedColumns)
|
||||
}
|
||||
if let index = matchingIndex {
|
||||
return index.columns
|
||||
if let matchingIndex {
|
||||
return matchingIndex.columns
|
||||
}
|
||||
|
||||
// No matching unique key found
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -671,12 +700,21 @@ extension Database {
|
||||
let primaryKey = try self.primaryKey(tableName)
|
||||
if let rowIDColumn = primaryKey.rowIDColumn {
|
||||
// Prefer the user-provided name of the rowid
|
||||
//
|
||||
// // CREATE TABLE player (id INTEGER PRIMARY KEY, ...)
|
||||
// try db.existenceCheckColumns(in: "player") // ["id"]
|
||||
return [rowIDColumn]
|
||||
} else if primaryKey.tableHasRowID {
|
||||
// Prefer the rowid
|
||||
//
|
||||
// // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...)
|
||||
// try db.existenceCheckColumns(in: "player") // ["rowid"]
|
||||
return [Column.rowID.name]
|
||||
} else {
|
||||
// WITHOUT ROWID table: use primary key columns
|
||||
//
|
||||
// // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...) WITHOUT ROWID
|
||||
// try db.existenceCheckColumns(in: "player") // ["uuid"]
|
||||
return primaryKey.columns
|
||||
}
|
||||
} else {
|
||||
@@ -733,6 +771,9 @@ public struct ColumnInfo: FetchableRecord {
|
||||
/// expression may be a literal, as `1`, or `'foo'`. It may also contain a
|
||||
/// non-constant expression such as `CURRENT_TIMESTAMP`.
|
||||
///
|
||||
/// For more information, see
|
||||
/// <https://www.sqlite.org/lang_createtable.html#the_default_clause>.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try db.execute(sql: """
|
||||
@@ -745,22 +786,13 @@ public struct ColumnInfo: FetchableRecord {
|
||||
/// """)
|
||||
/// let columnInfos = try db.columns(in: "player")
|
||||
/// columnInfos[0].defaultValueSQL // nil
|
||||
/// columnInfos[1].defaultValueSQL // "'Anoynymous'"
|
||||
/// columnInfos[1].defaultValueSQL // "'Anonymous'"
|
||||
/// columnInfos[2].defaultValueSQL // "0"
|
||||
/// columnInfos[3].defaultValueSQL // "CURRENT_TIMESTAMP"
|
||||
public let defaultValueSQL: String?
|
||||
|
||||
/// Zero for columns that are not part of the primary key.
|
||||
///
|
||||
/// Before SQLite 3.7.16, it is 1 for columns that are part of the
|
||||
/// primary key.
|
||||
///
|
||||
/// Starting from SQLite 3.7.16, it is the one-based index of the column in
|
||||
/// the primary key for columns that are part of the primary key.
|
||||
///
|
||||
/// References:
|
||||
/// - <https://sqlite.org/releaselog/3_7_16.html>
|
||||
/// - <http://mailinglists.sqlite.org/cgi-bin/mailman/private/sqlite-users/2013-April/046034.html>
|
||||
/// For columns that are part of the primary key, this is the one-based
|
||||
/// index of the column in the primary key. For other columns, it is zero.
|
||||
public let primaryKeyIndex: Int
|
||||
|
||||
/// :nodoc:
|
||||
@@ -779,6 +811,26 @@ public struct ColumnInfo: FetchableRecord {
|
||||
///
|
||||
/// See `Database.indexes(on:)`
|
||||
public struct IndexInfo {
|
||||
/// The origin of an index.
|
||||
///
|
||||
/// See ``Database/indexes(on:)``.
|
||||
public struct Origin: RawRepresentable, Equatable, DatabaseValueConvertible {
|
||||
public var rawValue: String
|
||||
|
||||
public init(rawValue: String) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// An index created from a CREATE INDEX statement.
|
||||
public static let createIndex = Origin(rawValue: "c")
|
||||
|
||||
/// An index created by a UNIQUE constraint.
|
||||
public static let uniqueConstraint = Origin(rawValue: "u")
|
||||
|
||||
/// An index created by a PRIMARY KEY constraint.
|
||||
public static let primaryKeyConstraint = Origin(rawValue: "pk")
|
||||
}
|
||||
|
||||
/// The name of the index
|
||||
public let name: String
|
||||
|
||||
@@ -788,11 +840,8 @@ public struct IndexInfo {
|
||||
/// True if the index is unique
|
||||
public let isUnique: Bool
|
||||
|
||||
init(name: String, columns: [String], unique: Bool) {
|
||||
self.name = name
|
||||
self.columns = columns
|
||||
self.isUnique = unique
|
||||
}
|
||||
/// The origin of the index
|
||||
public let origin: Origin
|
||||
}
|
||||
|
||||
/// A foreign key violation produced by PRAGMA foreign_key_check
|
||||
@@ -998,14 +1047,24 @@ public struct PrimaryKeyInfo {
|
||||
var fastPrimaryKeyColumn: String? {
|
||||
if let rowIDColumn = rowIDColumn {
|
||||
// Prefer the user-provided name of the rowid
|
||||
//
|
||||
// // CREATE TABLE player (id INTEGER PRIMARY KEY, ...)
|
||||
// try db.primaryKey("player").fastPrimaryKeyColumn // "id"
|
||||
return rowIDColumn
|
||||
} else if tableHasRowID {
|
||||
// Prefer the rowid
|
||||
//
|
||||
// // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...)
|
||||
// try db.primaryKey("player").fastPrimaryKeyColumn // "rowid"
|
||||
return Column.rowID.name
|
||||
} else if columns.count == 1 {
|
||||
// WITHOUT ROWID table: use primary key column
|
||||
//
|
||||
// // CREATE TABLE player (uuid TEXT NOT NULL PRIMARY KEY, ...) WITHOUT ROWID
|
||||
// try db.primaryKey("player").fastPrimaryKeyColumn // "uuid"
|
||||
return columns[0]
|
||||
} else {
|
||||
// WITHOUT ROWID table with a multi-columns primary key
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -1041,6 +1100,7 @@ enum SchemaObjectType: String {
|
||||
case view
|
||||
}
|
||||
|
||||
/// All objects in a database schema (tables, views, indexes, triggers).
|
||||
struct SchemaInfo: Equatable {
|
||||
private var objects: Set<SchemaObject>
|
||||
|
||||
@@ -1051,12 +1111,13 @@ struct SchemaInfo: Equatable {
|
||||
""")
|
||||
}
|
||||
|
||||
/// All names for a given type
|
||||
func names(ofType type: SchemaObjectType) -> Set<String> {
|
||||
objects.reduce(into: []) { (set, key) in
|
||||
if key.type == type.rawValue {
|
||||
set.insert(key.name)
|
||||
}
|
||||
/// Returns whether there exists a object of given type with this name
|
||||
/// (case-insensitive).
|
||||
func containsObjectNamed(_ name: String, ofType type: SchemaObjectType) -> Bool {
|
||||
let name = name.lowercased()
|
||||
let type = type.rawValue
|
||||
return objects.contains {
|
||||
$0.type == type && $0.name.lowercased() == name
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ extension Database {
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// 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])!
|
||||
@@ -23,6 +25,8 @@ extension Database {
|
||||
|
||||
/// Returns a new prepared statement that can be reused.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// 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])!
|
||||
@@ -62,45 +66,7 @@ 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])!
|
||||
@@ -111,7 +77,7 @@ extension Database {
|
||||
/// 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 {
|
||||
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,6 +111,8 @@ extension Database {
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// 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])!
|
||||
@@ -165,6 +133,8 @@ extension Database {
|
||||
|
||||
/// Returns a prepared statement that can be reused.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// 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])!
|
||||
@@ -202,140 +172,15 @@ 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.
|
||||
///
|
||||
/// let statement = try db.makeUpdateStatement(sql: "INSERT INTO player (name) VALUES (?)")
|
||||
/// try statement.execute(arguments: ["Arthur"])
|
||||
/// try statement.execute(arguments: ["Barbara"])
|
||||
///
|
||||
/// - 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.
|
||||
///
|
||||
/// - 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 makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = ?
|
||||
/// """)
|
||||
/// try makeUpdateStatement(literal: """
|
||||
/// UPDATE player SET name = \("O'Brien")
|
||||
/// """)
|
||||
///
|
||||
/// // 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.
|
||||
///
|
||||
/// 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.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let statements = try db.allStatements(sql: """
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
@@ -420,6 +265,8 @@ extension Database {
|
||||
|
||||
/// Executes one or several SQL statements, separated by semi-colons.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name) VALUES (:name)",
|
||||
/// arguments: ["name": "Arthur"])
|
||||
@@ -430,8 +277,6 @@ extension Database {
|
||||
/// INSERT INTO player (name) VALUES (?);
|
||||
/// """, arguments: ["Arthur", "Barbara", "O'Brien"])
|
||||
///
|
||||
/// This method may throw a DatabaseError.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
@@ -455,8 +300,6 @@ extension Database {
|
||||
/// 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.
|
||||
public func execute(literal sqlLiteral: SQL) throws {
|
||||
@@ -467,17 +310,18 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor over all statements in a SQL string.
|
||||
public class SQLStatementCursor: Cursor {
|
||||
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
|
||||
@@ -488,27 +332,27 @@ public class 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 +389,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 +415,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 +430,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 +477,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
|
||||
|
||||
+177
-166
@@ -13,7 +13,7 @@ let SQLITE_TRANSIENT = unsafeBitCast(OpaquePointer(bitPattern: -1), to: sqlite3_
|
||||
/// You don't create a database directly. Instead, you use a DatabaseQueue, or
|
||||
/// a DatabasePool:
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue(...)
|
||||
/// let dbQueue = try DatabaseQueue(...)
|
||||
///
|
||||
/// // The Database is the `db` in the closure:
|
||||
/// try dbQueue.write { db in
|
||||
@@ -26,8 +26,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// MARK: - SQLite C API
|
||||
|
||||
/// The raw SQLite connection, suitable for the SQLite C API.
|
||||
/// It is constant, until close() sets it to nil.
|
||||
public var sqliteConnection: SQLiteConnection?
|
||||
///
|
||||
/// It is nil after the database has been successfully closed with
|
||||
/// ``DatabaseReader/close()``.
|
||||
public private(set) var sqliteConnection: SQLiteConnection?
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
@@ -125,62 +127,84 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Internal properties
|
||||
|
||||
// Caches
|
||||
struct SchemaCache {
|
||||
var schemaIdentifiers: [SchemaIdentifier]?
|
||||
fileprivate var schemas: [SchemaIdentifier: DatabaseSchemaCache] = [:]
|
||||
|
||||
subscript(schemaID: SchemaIdentifier) -> DatabaseSchemaCache { // internal so that it can be tested
|
||||
get {
|
||||
schemas[schemaID] ?? DatabaseSchemaCache()
|
||||
}
|
||||
set {
|
||||
schemas[schemaID] = newValue
|
||||
}
|
||||
}
|
||||
|
||||
mutating func clear() {
|
||||
schemaIdentifiers = nil
|
||||
schemas.removeAll()
|
||||
}
|
||||
}
|
||||
/// Support for schema changes performed with ``DatabasePool``: each read
|
||||
/// access needs to clear the schema cache if the schema has been modified
|
||||
/// by the writer connection since the previous read. This property is reset
|
||||
/// to `PRAGMA schema_version` at the beginning of each DatabasePool read.
|
||||
///
|
||||
/// DatabasePool writer connection and DatabaseQueue do not perform such
|
||||
/// automatic schema management: they won't clear their schema cache if an
|
||||
/// external connection modifies the schema.
|
||||
///
|
||||
/// See `clearSchemaCacheIfNeeded()`.
|
||||
var lastSchemaVersion: Int32?
|
||||
|
||||
var _lastSchemaVersion: Int32? // Support for clearSchemaCacheIfNeeded()
|
||||
/// The cache for the available database schemas (main, temp, attached databases).
|
||||
var schemaCache = SchemaCache()
|
||||
|
||||
/// The cache for statements managed by GRDB. It is distinct from
|
||||
/// `publicStatementCache` so that we do not mess with statement arguments
|
||||
/// set by the user.
|
||||
lazy var internalStatementCache = StatementCache(database: self)
|
||||
|
||||
/// The cache for statements managed by the user.
|
||||
lazy var publicStatementCache = StatementCache(database: self)
|
||||
|
||||
// Database observation
|
||||
/// The database authorizer provides information about compiled
|
||||
/// database statements, and prevents the truncate optimization when
|
||||
/// row deletions are observed by transaction observers.
|
||||
lazy var authorizer = StatementAuthorizer(self)
|
||||
lazy var observationBroker = DatabaseObservationBroker(self)
|
||||
|
||||
/// The observation broker supports database observation and
|
||||
/// transaction observers.
|
||||
///
|
||||
/// It is nil in read-only connections, because we do not report read-only
|
||||
/// transactions to transaction observers.
|
||||
private(set) var observationBroker: DatabaseObservationBroker?
|
||||
|
||||
/// The list of compile options used when building SQLite
|
||||
static let sqliteCompileOptions: Set<String> = DatabaseQueue().inDatabase {
|
||||
try! Set(String.fetchCursor($0, sql: "PRAGMA COMPILE_OPTIONS"))
|
||||
static func sqliteCompileOptions() throws -> Set<String> {
|
||||
try DatabaseQueue().inDatabase {
|
||||
try Set(String.fetchCursor($0, sql: "PRAGMA COMPILE_OPTIONS"))
|
||||
}
|
||||
}
|
||||
|
||||
/// If true, select statement execution is recorded.
|
||||
/// Use recordingSelectedRegion(_:), see `statementWillExecute(_:)`
|
||||
var isRecordingSelectedRegion = false
|
||||
/// Whether the database region selected by statement execution is
|
||||
/// recorded into `selectedRegion`.
|
||||
///
|
||||
/// To record the selected region, use `recordingSelection(_:_:)`.
|
||||
private(set) var isRecordingSelectedRegion = false
|
||||
|
||||
/// The database region selected by statement execution, when
|
||||
/// `isRecordingSelectedRegion` is true.
|
||||
var selectedRegion = DatabaseRegion()
|
||||
|
||||
/// Support for checkForAbortedTransaction()
|
||||
/// Support for `checkForAbortedTransaction()`
|
||||
var isInsideTransactionBlock = false
|
||||
|
||||
/// Support for checkForSuspensionViolation(from:)
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
@LockedBox var isSuspended = false
|
||||
|
||||
/// Support for checkForSuspensionViolation(from:)
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
/// This cache is never cleared: we assume journal mode never changes.
|
||||
var journalModeCache: String?
|
||||
|
||||
// MARK: - Private properties
|
||||
|
||||
/// Support for ``Configuration/busyMode``.
|
||||
private var busyCallback: BusyCallback?
|
||||
|
||||
/// Support for ``trace(options:_:)``.
|
||||
private var trace: ((TraceEvent) -> Void)?
|
||||
|
||||
/// The registered custom SQL functions.
|
||||
private var functions = Set<DatabaseFunction>()
|
||||
|
||||
/// The registered custom SQL collations.
|
||||
private var collations = Set<DatabaseCollation>()
|
||||
private var _readOnlyDepth = 0 // Modify with beginReadOnly/endReadOnly
|
||||
|
||||
/// Support for `beginReadOnly()` and `endReadOnly()`.
|
||||
private var readOnlyDepth = 0
|
||||
|
||||
// MARK: - Initializer
|
||||
|
||||
@@ -192,6 +216,12 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
self.sqliteConnection = try Database.openConnection(path: path, flags: configuration.SQLiteOpenFlags)
|
||||
self.description = description
|
||||
self.configuration = configuration
|
||||
|
||||
// We do not report read-only transactions to transaction observers, so
|
||||
// don't bother installing the observation broker for read-only connections.
|
||||
if !configuration.readonly {
|
||||
observationBroker = DatabaseObservationBroker(self)
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -200,7 +230,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Database Opening
|
||||
|
||||
private static func openConnection(path: String, flags: Int32) throws -> SQLiteConnection {
|
||||
private static func openConnection(path: String, flags: CInt) throws -> SQLiteConnection {
|
||||
// See <https://www.sqlite.org/c3ref/open.html>
|
||||
var sqliteConnection: SQLiteConnection? = nil
|
||||
let code = sqlite3_open_v2(path, &sqliteConnection, flags, nil)
|
||||
@@ -233,9 +263,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
setupDefaultFunctions()
|
||||
setupDefaultCollations()
|
||||
setupAuthorizer()
|
||||
if !configuration.readonly {
|
||||
observationBroker.installCommitAndRollbackHooks()
|
||||
}
|
||||
observationBroker?.installCommitAndRollbackHooks()
|
||||
try activateExtendedCodes()
|
||||
|
||||
#if SQLITE_HAS_CODEC
|
||||
@@ -273,7 +301,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
break
|
||||
|
||||
case .timeout(let duration):
|
||||
let milliseconds = Int32(duration * 1000)
|
||||
let milliseconds = CInt(duration * 1000)
|
||||
sqlite3_busy_timeout(sqliteConnection, milliseconds)
|
||||
|
||||
case .callback(let callback):
|
||||
@@ -294,12 +322,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
add(function: .capitalize)
|
||||
add(function: .lowercase)
|
||||
add(function: .uppercase)
|
||||
|
||||
if #available(OSX 10.11, watchOS 3.0, *) {
|
||||
add(function: .localizedCapitalize)
|
||||
add(function: .localizedLowercase)
|
||||
add(function: .localizedUppercase)
|
||||
}
|
||||
add(function: .localizedCapitalize)
|
||||
add(function: .localizedLowercase)
|
||||
add(function: .localizedUppercase)
|
||||
}
|
||||
|
||||
private func setupDefaultCollations() {
|
||||
@@ -318,19 +343,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
//
|
||||
// - DatabaseCursorTests.testIssue583()
|
||||
// - http://sqlite.1065341.n5.nabble.com/Issue-report-sqlite3-set-authorizer-triggers-error-4-516-SQLITE-ABORT-ROLLBACK-during-statement-itern-td107972.html
|
||||
let authorizerP = Unmanaged.passUnretained(authorizer).toOpaque()
|
||||
sqlite3_set_authorizer(
|
||||
sqliteConnection,
|
||||
{ (authorizerP, actionCode, cString1, cString2, cString3, cString4) -> Int32 in
|
||||
Unmanaged<StatementAuthorizer>
|
||||
.fromOpaque(authorizerP.unsafelyUnwrapped)
|
||||
.takeUnretainedValue()
|
||||
.authorize(actionCode, cString1, cString2, cString3, cString4)
|
||||
},
|
||||
authorizerP)
|
||||
authorizer.register()
|
||||
}
|
||||
|
||||
|
||||
private func activateExtendedCodes() throws {
|
||||
let code = sqlite3_extended_result_codes(sqliteConnection, 1)
|
||||
guard code == SQLITE_OK else {
|
||||
@@ -372,12 +387,15 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
func close() throws {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
guard let sqliteConnection = sqliteConnection else {
|
||||
guard let sqliteConnection else {
|
||||
// Already closed
|
||||
return
|
||||
}
|
||||
|
||||
configuration.SQLiteConnectionWillClose?(sqliteConnection)
|
||||
|
||||
// Finalize all cached statements since they would prevent
|
||||
// immediate connection closing.
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
|
||||
@@ -388,6 +406,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// > return SQLITE_BUSY.
|
||||
let code = sqlite3_close(sqliteConnection)
|
||||
guard code == SQLITE_OK else {
|
||||
// So there remain some unfinalized prepared statement somewhere.
|
||||
if let log = Self.logError {
|
||||
if code == SQLITE_BUSY {
|
||||
// Let the user know about unfinalized statements that did
|
||||
@@ -412,12 +431,15 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
func close_v2() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
|
||||
guard let sqliteConnection = sqliteConnection else {
|
||||
guard let sqliteConnection else {
|
||||
// Already closed
|
||||
return
|
||||
}
|
||||
|
||||
configuration.SQLiteConnectionWillClose?(sqliteConnection)
|
||||
|
||||
// Finalize all cached statements since they would prevent
|
||||
// immediate connection closing.
|
||||
internalStatementCache.clear()
|
||||
publicStatementCache.clear()
|
||||
|
||||
@@ -502,9 +524,9 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
collation.name,
|
||||
SQLITE_UTF8,
|
||||
collationPointer,
|
||||
{ (collationPointer, length1, buffer1, length2, buffer2) -> Int32 in
|
||||
{ (collationPointer, length1, buffer1, length2, buffer2) in
|
||||
let collation = Unmanaged<DatabaseCollation>.fromOpaque(collationPointer!).takeUnretainedValue()
|
||||
return Int32(collation.function(length1, buffer1, length2, buffer2).rawValue)
|
||||
return CInt(collation.function(length1, buffer1, length2, buffer2).rawValue)
|
||||
}, nil)
|
||||
guard code == SQLITE_OK else {
|
||||
// Assume a GRDB bug: there is no point throwing any error.
|
||||
@@ -524,23 +546,26 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Read-Only Access
|
||||
|
||||
/// MUST be balanced with `endReadOnly()`.
|
||||
func beginReadOnly() throws {
|
||||
if configuration.readonly { return }
|
||||
if _readOnlyDepth == 0 {
|
||||
if readOnlyDepth == 0 {
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 1").execute()
|
||||
}
|
||||
_readOnlyDepth += 1
|
||||
readOnlyDepth += 1
|
||||
}
|
||||
|
||||
/// MUST balance `beginReadOnly()`.
|
||||
func endReadOnly() throws {
|
||||
if configuration.readonly { return }
|
||||
_readOnlyDepth -= 1
|
||||
if _readOnlyDepth == 0 {
|
||||
readOnlyDepth -= 1
|
||||
assert(readOnlyDepth >= 0, "unbalanced endReadOnly()")
|
||||
if readOnlyDepth == 0 {
|
||||
try internalCachedStatement(sql: "PRAGMA query_only = 0").execute()
|
||||
}
|
||||
}
|
||||
|
||||
/// Grants read-only access, starting SQLite 3.8.0
|
||||
/// Grants read-only access in the wrapped closure.
|
||||
func readOnly<T>(_ block: () throws -> T) throws -> T {
|
||||
try beginReadOnly()
|
||||
return try throwingFirstError(
|
||||
@@ -548,13 +573,33 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
finally: endReadOnly)
|
||||
}
|
||||
|
||||
/// Returns whether database connection is read-only.
|
||||
/// Returns whether database connection is read-only (due to
|
||||
/// `SQLITE_OPEN_READONLY` or `PRAGMA query_only=1`).
|
||||
var isReadOnly: Bool {
|
||||
_readOnlyDepth > 0 || configuration.readonly
|
||||
readOnlyDepth > 0 || configuration.readonly
|
||||
}
|
||||
|
||||
// MARK: - Recording of the selected region
|
||||
|
||||
/// Extends the `region` argument with the database region selected by all
|
||||
/// statements executed by the closure.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// var region = DatabaseRegion()
|
||||
/// try db.recordingSelection(®ion) {
|
||||
/// let players = try Player.fetchAll(db)
|
||||
/// let team = try Team.fetchOne(db, id: 42)
|
||||
/// }
|
||||
/// print(region) // player(*),team(*)[42]
|
||||
///
|
||||
/// This method is used by ``ValueObservation``:
|
||||
///
|
||||
/// let playersObservation = ValueObservation.tracking { db in
|
||||
/// // Here all fetches are recorded, so that we know what is the
|
||||
/// // database region that must be observed.
|
||||
/// try Player.fetchAll(db)
|
||||
/// }
|
||||
func recordingSelection<T>(_ region: inout DatabaseRegion, _ block: () throws -> T) rethrows -> T {
|
||||
if region.isFullDatabase {
|
||||
return try block()
|
||||
@@ -606,57 +651,32 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
self.trace = trace
|
||||
|
||||
if options.isEmpty || trace == nil {
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
|
||||
#elseif os(Linux)
|
||||
#if os(Linux)
|
||||
sqlite3_trace(sqliteConnection, nil)
|
||||
#else
|
||||
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
|
||||
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
|
||||
} else {
|
||||
sqlite3_trace(sqliteConnection, nil, nil)
|
||||
}
|
||||
sqlite3_trace_v2(sqliteConnection, 0, nil, nil)
|
||||
#endif
|
||||
return
|
||||
}
|
||||
|
||||
// sqlite3_trace_v2 and sqlite3_expanded_sql were introduced in SQLite 3.14.0
|
||||
// http://www.sqlite.org/changes.html#version_3_14
|
||||
// It is available from macOS 10.12, tvOS 10.0, watchOS 3.0
|
||||
// https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS)
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql)
|
||||
return SQLITE_OK
|
||||
}, dbPointer)
|
||||
#elseif os(Linux)
|
||||
setupTrace_v1()
|
||||
#else
|
||||
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace_v2(sqliteConnection, UInt32(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql)
|
||||
return SQLITE_OK
|
||||
}, dbPointer)
|
||||
} else {
|
||||
setupTrace_v1()
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !(GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS))
|
||||
private func setupTrace_v1() {
|
||||
#if os(Linux)
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace(sqliteConnection, { (dbPointer, sql) in
|
||||
guard let sql = sql.map(String.init(cString:)) else { return }
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.trace?(Database.TraceEvent.statement(TraceEvent.Statement(impl: .trace_v1(sql))))
|
||||
}, dbPointer)
|
||||
#else
|
||||
let dbPointer = Unmanaged.passUnretained(self).toOpaque()
|
||||
sqlite3_trace_v2(sqliteConnection, CUnsignedInt(bitPattern: options.rawValue), { (mask, dbPointer, p, x) in
|
||||
let db = Unmanaged<Database>.fromOpaque(dbPointer!).takeUnretainedValue()
|
||||
db.trace_v2(CInt(bitPattern: mask), p, x, sqlite3_expanded_sql)
|
||||
return SQLITE_OK
|
||||
}, dbPointer)
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
// Precondition: configuration.trace != nil
|
||||
private func trace_v2(
|
||||
@@ -665,7 +685,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
_ x: UnsafeMutableRawPointer?,
|
||||
_ sqlite3_expanded_sql: @escaping @convention(c) (OpaquePointer?) -> UnsafeMutablePointer<Int8>?)
|
||||
{
|
||||
guard let trace = trace else { return }
|
||||
guard let trace else { return }
|
||||
|
||||
switch mask {
|
||||
case SQLITE_TRACE_STMT:
|
||||
@@ -688,13 +708,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
publicStatementArguments: configuration.publicStatementArguments))
|
||||
let duration = TimeInterval(durationP.pointee) / 1.0e9
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
#if !os(Linux)
|
||||
trace(TraceEvent.profile(statement: statement, duration: duration))
|
||||
#elseif os(Linux)
|
||||
#else
|
||||
if #available(OSX 10.12, tvOS 10.0, watchOS 3.0, *) {
|
||||
trace(TraceEvent.profile(statement: statement, duration: duration))
|
||||
}
|
||||
#endif
|
||||
}
|
||||
default:
|
||||
@@ -767,7 +782,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// DatabaseError of code `SQLITE_INTERRUPT`, or `SQLITE_ABORT`, except
|
||||
/// reads in WAL mode.
|
||||
///
|
||||
/// Suspension ends with resume().
|
||||
/// Suspension ends with `resume()`.
|
||||
func suspend() {
|
||||
$isSuspended.update { isSuspended in
|
||||
if isSuspended {
|
||||
@@ -799,7 +814,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
isSuspended = false
|
||||
}
|
||||
|
||||
/// Support for checkForSuspensionViolation(from:)
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
private func journalMode() throws -> String {
|
||||
if let journalMode = journalModeCache {
|
||||
return journalMode
|
||||
@@ -820,9 +835,11 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
return journalMode
|
||||
}
|
||||
|
||||
/// Throws SQLITE_ABORT for suspended databases, if statement would lock
|
||||
/// the database, in order to avoid the [`0xdead10cc`
|
||||
/// exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report).
|
||||
/// If the database is suspended, and executing the statement would lock the
|
||||
/// database in a way that may trigger the [`0xdead10cc` exception](https://developer.apple.com/documentation/xcode/understanding-the-exception-types-in-a-crash-report),
|
||||
/// this method rollbacks the current transaction and throws `SQLITE_ABORT`.
|
||||
///
|
||||
/// See `suspend()` and ``Configuration/observesSuspensionNotifications``.
|
||||
func checkForSuspensionViolation(from statement: Statement) throws {
|
||||
try $isSuspended.read { isSuspended in
|
||||
guard isSuspended else {
|
||||
@@ -867,22 +884,24 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Transactions & Savepoint
|
||||
|
||||
/// Throws SQLITE_ABORT if called from a transaction-wrapping method and
|
||||
/// Throws `SQLITE_ABORT` if called from a transaction-wrapping method and
|
||||
/// transaction has been aborted (for example, by `sqlite3_interrupt`, or a
|
||||
/// `ON CONFLICT ROLLBACK` clause.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try db.inTransaction {
|
||||
/// do {
|
||||
/// // Aborted by sqlite3_interrupt or any other
|
||||
/// // SQLite error which leaves transaction
|
||||
/// // Throws an error because the transaction was rollbacked.
|
||||
/// try ...
|
||||
/// } catch {
|
||||
/// // Catch the error and continue.
|
||||
/// ...
|
||||
/// } catch { ... }
|
||||
/// }
|
||||
///
|
||||
/// // <- Here we're inside an aborted transaction.
|
||||
/// try checkForAbortedTransaction(...) // throws
|
||||
/// try checkForAbortedTransaction(...) // throws SQLITE_ABORT
|
||||
/// ...
|
||||
///
|
||||
/// return .commit
|
||||
/// }
|
||||
func checkForAbortedTransaction(
|
||||
sql: @autoclosure () -> String? = nil,
|
||||
@@ -901,6 +920,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Executes a block inside a database transaction.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase do {
|
||||
/// try db.inTransaction {
|
||||
/// try db.execute(sql: "INSERT ...")
|
||||
@@ -911,26 +932,29 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// If the block throws an error, the transaction is rollbacked and the
|
||||
/// error is rethrown.
|
||||
///
|
||||
/// This method is not reentrant: you can't nest transactions.
|
||||
/// - warning: This method is not reentrant: you can't nest transactions.
|
||||
/// Use ``inSavepoint(_:)`` instead.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil).
|
||||
///
|
||||
/// If nil, and the database connection is read-only, the transaction
|
||||
/// kind is `.deferred`.
|
||||
/// kind is ``TransactionKind/deferred``.
|
||||
///
|
||||
/// If nil, and the database connection is not read-only, the
|
||||
/// transaction kind is `configuration.defaultTransactionKind`.
|
||||
/// transaction kind is ``Configuration/defaultTransactionKind``.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_transaction.html> for
|
||||
/// more information.
|
||||
/// - block: A block that executes SQL statements and return either
|
||||
/// .commit or .rollback.
|
||||
/// ``TransactionCompletion/commit`` or
|
||||
/// ``TransactionCompletion/rollback``.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inTransaction(_ kind: TransactionKind? = nil, _ block: () throws -> TransactionCompletion) throws {
|
||||
// Begin transaction
|
||||
try beginTransaction(kind)
|
||||
|
||||
// Support for `checkForAbortedTransaction()`.
|
||||
let wasInsideTransactionBlock = isInsideTransactionBlock
|
||||
isInsideTransactionBlock = true
|
||||
defer {
|
||||
@@ -989,6 +1013,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
if readOnly {
|
||||
// Enter read-only mode before starting a transaction, so that the
|
||||
// transaction commit does not trigger database observation.
|
||||
// See <https://github.com/groue/GRDB.swift/pull/1213>.
|
||||
try self.readOnly {
|
||||
try inSavepoint {
|
||||
result = try block()
|
||||
@@ -1006,6 +1031,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Executes a block inside a savepoint.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.inDatabase do {
|
||||
/// try db.inSavepoint {
|
||||
/// try db.execute(sql: "INSERT ...")
|
||||
@@ -1019,7 +1046,8 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// This method is reentrant: you can nest savepoints.
|
||||
///
|
||||
/// - parameter block: A block that executes SQL statements and return
|
||||
/// either .commit or .rollback.
|
||||
/// either ``TransactionCompletion/commit`` or
|
||||
/// ``TransactionCompletion/rollback``.
|
||||
/// - throws: The error thrown by the block.
|
||||
public func inSavepoint(_ block: () throws -> TransactionCompletion) throws {
|
||||
if !isInsideTransaction {
|
||||
@@ -1055,6 +1083,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
// the user uses "grdb" as a savepoint name.
|
||||
try execute(sql: "SAVEPOINT grdb")
|
||||
|
||||
// Support for `checkForAbortedTransaction()`.
|
||||
let wasInsideTransactionBlock = isInsideTransactionBlock
|
||||
isInsideTransactionBlock = true
|
||||
defer {
|
||||
@@ -1111,16 +1140,17 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// Begins a database transaction.
|
||||
///
|
||||
/// - parameter kind: The transaction type (default nil).
|
||||
/// - parameters:
|
||||
/// - kind: The transaction type (default nil).
|
||||
///
|
||||
/// If nil, and the database connection is read-only, the transaction kind
|
||||
/// is `.deferred`.
|
||||
/// If nil, and the database connection is read-only, the transaction
|
||||
/// kind is ``TransactionKind/deferred``.
|
||||
///
|
||||
/// If nil, and the database connection is not read-only, the transaction
|
||||
/// kind is `configuration.defaultTransactionKind`.
|
||||
/// If nil, and the database connection is not read-only, the
|
||||
/// transaction kind is ``Configuration/defaultTransactionKind``.
|
||||
///
|
||||
/// See <https://www.sqlite.org/lang_transaction.html> for
|
||||
/// more information.
|
||||
/// See <https://www.sqlite.org/lang_transaction.html> for
|
||||
/// more information.
|
||||
/// - throws: A DatabaseError whenever an SQLite error occurs.
|
||||
public func beginTransaction(_ kind: TransactionKind? = nil) throws {
|
||||
// SQLite throws an error for non-deferred transactions when read-only.
|
||||
@@ -1184,6 +1214,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// MARK: - Memory Management
|
||||
|
||||
/// Free as much memory as possible.
|
||||
public func releaseMemory() {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
sqlite3_db_release_memory(sqliteConnection)
|
||||
@@ -1280,7 +1311,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
/// any `DatabaseError` that would happen while performing the backup.
|
||||
public func backup(
|
||||
to destDb: Database,
|
||||
pagesPerStep: Int32 = -1,
|
||||
pagesPerStep: CInt = -1,
|
||||
progress: ((DatabaseBackupProgress) throws -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
@@ -1292,7 +1323,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
func backupInternal(
|
||||
to destDb: Database,
|
||||
pagesPerStep: Int32 = -1,
|
||||
pagesPerStep: CInt = -1,
|
||||
afterBackupInit: (() -> Void)? = nil,
|
||||
afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil)
|
||||
throws
|
||||
@@ -1377,7 +1408,7 @@ extension Database {
|
||||
/// }
|
||||
public func usePassphrase(_ passphrase: Data) throws {
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_key(sqliteConnection, $0.baseAddress, Int32($0.count))
|
||||
sqlite3_key(sqliteConnection, $0.baseAddress, CInt($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: String(cString: sqlite3_errmsg(sqliteConnection)))
|
||||
@@ -1407,7 +1438,7 @@ extension Database {
|
||||
// > schema of the original db into the new one:
|
||||
// > https://discuss.zetetic.net/t/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher-and-avoid-file-is-encrypted-or-is-not-a-database-errors/
|
||||
let code = passphrase.withUnsafeBytes {
|
||||
sqlite3_rekey(sqliteConnection, $0.baseAddress, Int32($0.count))
|
||||
sqlite3_rekey(sqliteConnection, $0.baseAddress, CInt($0.count))
|
||||
}
|
||||
guard code == SQLITE_OK else {
|
||||
throw DatabaseError(resultCode: code, message: lastErrorMessage)
|
||||
@@ -1441,7 +1472,7 @@ extension Database {
|
||||
///
|
||||
/// // Wait 1 second before failing with SQLITE_BUSY
|
||||
/// let configuration = Configuration(busyMode: .timeout(1))
|
||||
/// let dbQueue = DatabaseQueue(path: "...", configuration: configuration)
|
||||
/// let dbQueue = try DatabaseQueue(path: "...", configuration: configuration)
|
||||
///
|
||||
/// Relevant SQLite documentation:
|
||||
///
|
||||
@@ -1464,7 +1495,7 @@ extension Database {
|
||||
}
|
||||
|
||||
/// The available [checkpoint modes](https://www.sqlite.org/c3ref/wal_checkpoint_v2.html).
|
||||
public enum CheckpointMode: Int32 {
|
||||
public enum CheckpointMode: CInt {
|
||||
/// The `SQLITE_CHECKPOINT_PASSIVE` mode
|
||||
case passive = 0
|
||||
|
||||
@@ -1609,20 +1640,12 @@ extension Database {
|
||||
/// See `Database.trace(options:_:)`
|
||||
public static let statement = TracingOptions(rawValue: SQLITE_TRACE_STMT)
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
#if !os(Linux)
|
||||
/// Reports executed statements and the estimated duration that the
|
||||
/// statement took to run.
|
||||
///
|
||||
/// See `Database.trace(options:_:)`
|
||||
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
|
||||
#elseif os(Linux)
|
||||
#else
|
||||
/// Reports executed statements and the estimated duration that the
|
||||
/// statement took to run.
|
||||
///
|
||||
/// See `Database.trace(options:_:)`
|
||||
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
|
||||
public static let profile = TracingOptions(rawValue: SQLITE_TRACE_PROFILE)
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -1641,22 +1664,13 @@ extension Database {
|
||||
}
|
||||
var impl: Impl
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER || os(iOS)
|
||||
#if !os(Linux)
|
||||
/// The executed SQL, where bound parameters are not expanded.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
public var sql: String { _sql }
|
||||
#elseif os(Linux)
|
||||
#else
|
||||
/// The executed SQL, where bound parameters are not expanded.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// SELECT * FROM player WHERE email = ?
|
||||
@available(OSX 10.12, tvOS 10.0, watchOS 3.0, *)
|
||||
public var sql: String { _sql }
|
||||
#endif
|
||||
|
||||
var _sql: String {
|
||||
@@ -1667,11 +1681,9 @@ extension Database {
|
||||
|
||||
case let .trace_v2(sqliteStatement, unexpandedSQL, _, _):
|
||||
if let unexpandedSQL = unexpandedSQL {
|
||||
return String(cString: unexpandedSQL)
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
return String(cString: unexpandedSQL).trimmedSQLStatement
|
||||
} else {
|
||||
return String(cString: sqlite3_sql(sqliteStatement))
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1695,8 +1707,7 @@ extension Database {
|
||||
return ""
|
||||
}
|
||||
defer { sqlite3_free(cString) }
|
||||
return String(cString: cString)
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
return String(cString: cString).trimmedSQLStatement
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1792,7 +1803,7 @@ extension Database {
|
||||
case multiThread
|
||||
case serialized
|
||||
|
||||
var SQLiteOpenFlags: Int32 {
|
||||
var SQLiteOpenFlags: CInt {
|
||||
switch self {
|
||||
case .`default`:
|
||||
return 0
|
||||
|
||||
@@ -4,7 +4,7 @@ import Foundation
|
||||
public final class DatabaseCollation {
|
||||
/// 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.
|
||||
///
|
||||
|
||||
@@ -197,7 +197,7 @@ extension ResultCode {
|
||||
}
|
||||
}
|
||||
|
||||
extension ResultCode: GRDBSendable { }
|
||||
extension ResultCode: Sendable { }
|
||||
|
||||
/// DatabaseError wraps an SQLite error.
|
||||
public struct DatabaseError: Error, CustomStringConvertible, CustomNSError {
|
||||
|
||||
@@ -3,7 +3,7 @@ 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,7 +11,7 @@ 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.
|
||||
///
|
||||
@@ -41,11 +41,11 @@ public final class DatabaseFunction: Hashable {
|
||||
/// 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
|
||||
@@ -68,12 +68,12 @@ public final class DatabaseFunction: Hashable {
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> DatabaseValueConvertible? {
|
||||
/// func finalize() -> (any DatabaseValueConvertible)? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: fn)
|
||||
@@ -98,11 +98,11 @@ public final class DatabaseFunction: Hashable {
|
||||
/// 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() }
|
||||
}
|
||||
@@ -110,7 +110,7 @@ public final class DatabaseFunction: Hashable {
|
||||
/// Returns an SQL expression that applies the function.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/#sql-functions>
|
||||
public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression {
|
||||
public func callAsFunction(_ arguments: any SQLExpressible...) -> SQLExpression {
|
||||
switch kind {
|
||||
case .aggregate:
|
||||
return .function(name, arguments.map(\.sqlExpression))
|
||||
@@ -166,8 +166,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 +178,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 +197,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 +215,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 +233,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 +290,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 +316,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 +328,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -369,12 +371,12 @@ extension DatabaseFunction {
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// func finalize() -> DatabaseValueConvertible? {
|
||||
/// func finalize() -> (any DatabaseValueConvertible)? {
|
||||
/// return sum
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
/// let fn = DatabaseFunction("mysum", argumentCount: 1, aggregate: MySum.self)
|
||||
/// try dbQueue.write { db in
|
||||
/// db.add(function: fn)
|
||||
@@ -402,5 +404,5 @@ public protocol DatabaseAggregate {
|
||||
mutating func step(_ dbValues: [DatabaseValue]) throws
|
||||
|
||||
/// Returns the final result
|
||||
func finalize() throws -> DatabaseValueConvertible?
|
||||
func finalize() throws -> (any DatabaseValueConvertible)?
|
||||
}
|
||||
@@ -158,10 +158,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 +214,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 +343,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 +357,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 +389,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 +401,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 +432,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
|
||||
@@ -529,7 +522,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 +615,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
|
||||
}
|
||||
|
||||
@@ -653,17 +646,22 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
@_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 {
|
||||
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 (Database) -> Void) {
|
||||
// TODO: throw instead of crashing when the database is closed
|
||||
readerPool!.asyncBarrier {
|
||||
self.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)) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -727,7 +725,7 @@ extension DatabasePool: DatabaseReader {
|
||||
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 +756,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")
|
||||
|
||||
@@ -51,14 +51,13 @@ public final class DatabaseQueue: DatabaseWriter {
|
||||
|
||||
/// Opens an in-memory SQLite database.
|
||||
///
|
||||
/// let dbQueue = DatabaseQueue()
|
||||
/// let dbQueue = try DatabaseQueue()
|
||||
///
|
||||
/// 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")
|
||||
@@ -94,20 +93,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)
|
||||
}
|
||||
|
||||
@@ -309,12 +303,12 @@ 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,
|
||||
@@ -349,7 +343,7 @@ extension DatabaseQueue {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if configuration.readonly {
|
||||
// The easy case: the database does not change
|
||||
|
||||
@@ -19,7 +19,7 @@ import Dispatch
|
||||
/// 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 {
|
||||
public protocol DatabaseReader: AnyObject, Sendable {
|
||||
|
||||
/// The database configuration
|
||||
var configuration: Configuration { get }
|
||||
@@ -281,14 +281,14 @@ public protocol DatabaseReader: AnyObject, GRDBSendable {
|
||||
/// method instead.
|
||||
///
|
||||
/// - parameter observation: the stared observation
|
||||
/// - returns: a TransactionObserver
|
||||
/// - returns: a cancellable
|
||||
///
|
||||
/// :nodoc:
|
||||
func _add<Reducer: ValueReducer>(
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
}
|
||||
|
||||
extension DatabaseReader {
|
||||
@@ -341,8 +341,8 @@ extension DatabaseReader {
|
||||
/// - throws: The error thrown by `progress` if the backup is abandoned, or
|
||||
/// any `DatabaseError` that would happen while performing the backup.
|
||||
public func backup(
|
||||
to writer: DatabaseWriter,
|
||||
pagesPerStep: Int32 = -1,
|
||||
to writer: some DatabaseWriter,
|
||||
pagesPerStep: CInt = -1,
|
||||
progress: ((DatabaseBackupProgress) throws -> Void)? = nil)
|
||||
throws
|
||||
{
|
||||
@@ -356,7 +356,7 @@ extension DatabaseReader {
|
||||
|
||||
func backup(
|
||||
to destDb: Database,
|
||||
pagesPerStep: Int32 = -1,
|
||||
pagesPerStep: CInt = -1,
|
||||
afterBackupInit: (() -> Void)? = nil,
|
||||
afterBackupStep: ((DatabaseBackupProgress) throws -> Void)? = nil)
|
||||
throws
|
||||
@@ -371,11 +371,9 @@ 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.
|
||||
///
|
||||
@@ -422,7 +420,6 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: remove @escaping as soon as it is possible
|
||||
/// Asynchronously executes a function that accepts a database connection.
|
||||
///
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
@@ -465,7 +462,6 @@ extension DatabaseReader {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if canImport(Combine)
|
||||
extension DatabaseReader {
|
||||
@@ -557,7 +553,7 @@ extension DatabaseReader {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
if scheduler.immediateInitialValue() {
|
||||
do {
|
||||
@@ -601,10 +597,10 @@ extension DatabaseReader {
|
||||
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
|
||||
/// underlying database reader.
|
||||
public final class AnyDatabaseReader: DatabaseReader {
|
||||
private let base: DatabaseReader
|
||||
private let base: any DatabaseReader
|
||||
|
||||
/// Creates a database reader that wraps a base database reader.
|
||||
public init(_ base: DatabaseReader) {
|
||||
public init(_ base: some DatabaseReader) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
@@ -653,7 +649,7 @@ public final class AnyDatabaseReader: DatabaseReader {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
observation: observation,
|
||||
|
||||
@@ -38,7 +38,7 @@ 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
|
||||
}
|
||||
@@ -55,14 +55,6 @@ public struct DatabaseRegion: CustomStringConvertible, Equatable {
|
||||
/// from all tables.
|
||||
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.
|
||||
public init() {
|
||||
self.init(tableRegions: [:])
|
||||
@@ -71,9 +63,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 +87,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 +105,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 +125,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 +170,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 +183,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 +207,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
|
||||
}
|
||||
@@ -261,7 +253,7 @@ extension DatabaseRegion {
|
||||
extension DatabaseRegion {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
guard let tableRegions = tableRegions else {
|
||||
guard let tableRegions else {
|
||||
return "full database"
|
||||
}
|
||||
if tableRegions.isEmpty {
|
||||
@@ -336,7 +328,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)
|
||||
@@ -348,7 +340,7 @@ private struct TableRegion: Equatable {
|
||||
/// `DatabaseRegionConvertible` is the protocol for values that can be turned
|
||||
/// into a `DatabaseRegion`.
|
||||
///
|
||||
/// Such values specify the region obserbed by `DatabaseRegionObservation`.
|
||||
/// Such values specify the region observed by `DatabaseRegionObservation`.
|
||||
public protocol DatabaseRegionConvertible {
|
||||
/// Returns a database region.
|
||||
///
|
||||
@@ -356,13 +348,11 @@ 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:
|
||||
@@ -379,8 +369,8 @@ public struct AnyDatabaseRegionConvertible: DatabaseRegionConvertible {
|
||||
_region = region
|
||||
}
|
||||
|
||||
public init(_ region: DatabaseRegionConvertible) {
|
||||
_region = { try region.databaseRegion($0) }
|
||||
public init(_ region: some DatabaseRegionConvertible) {
|
||||
_region = region.databaseRegion
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@@ -398,7 +388,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))
|
||||
|
||||
@@ -10,16 +10,13 @@ import Foundation
|
||||
/// For example:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation(tracking: Player.all)
|
||||
/// let observer = try observation.start(in: dbQueue) { db: Database in
|
||||
/// print("Players have changed.")
|
||||
/// }
|
||||
/// let cancellable = try observation.start(
|
||||
/// in: dbQueue,
|
||||
/// onError: { error in ... },
|
||||
/// onChange: { (db: Database) in
|
||||
/// print("A modification of the player table has just been committed.")
|
||||
/// })
|
||||
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
|
||||
@@ -36,16 +33,19 @@ extension DatabaseRegionObservation {
|
||||
/// 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.")
|
||||
/// }
|
||||
/// let cancellable = observation.start(
|
||||
/// in: dbQueue,
|
||||
/// onError: { error in ... },
|
||||
/// onChange: { _ 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.
|
||||
/// The observation lasts until the cancellable returned by `start` is
|
||||
/// cancelled or deallocated.
|
||||
///
|
||||
/// - parameter regions: A list of observed regions.
|
||||
public init(tracking regions: DatabaseRegionConvertible...) {
|
||||
public init(tracking regions: any DatabaseRegionConvertible...) {
|
||||
self.init(tracking: regions)
|
||||
}
|
||||
|
||||
@@ -59,42 +59,91 @@ extension DatabaseRegionObservation {
|
||||
/// let observation = DatabaseRegionObservation(tracking: [Player.all()])
|
||||
///
|
||||
/// var count = 0
|
||||
/// let observer = observation.start(in: dbQueue) { _ in
|
||||
/// let cancellable = 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.
|
||||
/// The observation lasts until the cancellable returned by `start` is
|
||||
/// cancelled or deallocated.
|
||||
///
|
||||
/// - parameter regions: A list of observed regions.
|
||||
public init(tracking regions: [DatabaseRegionConvertible]) {
|
||||
self.init(
|
||||
extent: .observerLifetime,
|
||||
observedRegion: DatabaseRegion.union(regions))
|
||||
public init(tracking regions: [any DatabaseRegionConvertible]) {
|
||||
self.init(observedRegion: DatabaseRegion.union(regions))
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseRegionObservation {
|
||||
/// The state of a started DatabaseRegionObservation
|
||||
private enum ObservationState {
|
||||
case cancelled
|
||||
case pending
|
||||
case started(DatabaseRegionObserver)
|
||||
}
|
||||
|
||||
/// Starts the observation in the provided database writer (such as
|
||||
/// a database queue or database pool), and returns a transaction observer.
|
||||
///
|
||||
/// - parameter reader: A DatabaseWriter.
|
||||
/// For example:
|
||||
///
|
||||
/// let observation = DatabaseRegionObservation.tracking(Player.all())
|
||||
/// let cancellable = observation.start(
|
||||
/// in: dbQueue,
|
||||
/// onError: { error in ... },
|
||||
/// onChange: { (db: Database) in
|
||||
/// print("A modification of the player table has just been committed.")
|
||||
/// })
|
||||
///
|
||||
/// If the `start` method is called from a writing database access method,
|
||||
/// the observation of impactful transactions starts immediately. Otherwise,
|
||||
/// it blocks the current thread until a write access can be established.
|
||||
///
|
||||
/// - parameter writer: A DatabaseWriter.
|
||||
/// - parameter onError: A closure that is provided eventual errors that
|
||||
/// happen during observation
|
||||
/// - parameter onChange: A closure that is provided a database connection
|
||||
/// with write access each time the observed region has been modified.
|
||||
/// - returns: a TransactionObserver
|
||||
/// - returns: a cancellable.
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -111,7 +160,7 @@ extension DatabaseRegionObservation {
|
||||
/// Error completion, if any, is only emitted, synchronously,
|
||||
/// on subscription.
|
||||
@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)
|
||||
}
|
||||
}
|
||||
@@ -160,10 +209,10 @@ extension DatabasePublishers {
|
||||
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
|
||||
}
|
||||
@@ -183,13 +232,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 +253,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 +277,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 +298,7 @@ extension DatabasePublishers {
|
||||
|
||||
func cancel() {
|
||||
lock.synchronized {
|
||||
observer = nil
|
||||
cancellable = nil
|
||||
state = .finished
|
||||
}
|
||||
}
|
||||
@@ -272,6 +317,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
|
||||
@@ -89,7 +89,7 @@ extension DatabaseSnapshot {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
_addReadOnly(
|
||||
observation: observation,
|
||||
|
||||
@@ -31,7 +31,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
case blob(Data)
|
||||
|
||||
/// Returns Int64, Double, String, Data or nil.
|
||||
public var value: DatabaseValueConvertible? {
|
||||
public var value: (any DatabaseValueConvertible)? {
|
||||
switch self {
|
||||
case .null:
|
||||
return nil
|
||||
@@ -67,7 +67,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
///
|
||||
/// The result is nil unless object 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
|
||||
@@ -116,7 +116,7 @@ public struct DatabaseValue: Hashable, CustomStringConvertible, DatabaseValueCon
|
||||
}
|
||||
|
||||
/// Returns a DatabaseValue initialized from a raw SQLite statement pointer.
|
||||
init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_NULL:
|
||||
storage = .null
|
||||
@@ -157,13 +157,11 @@ 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
|
||||
extension DatabaseValue.Storage: @unchecked Sendable { }
|
||||
#endif
|
||||
|
||||
// MARK: - Hashable & Equatable
|
||||
|
||||
|
||||
@@ -19,7 +19,17 @@ public protocol DatabaseValueConvertible: SQLExpressible, StatementBinding {
|
||||
var databaseValue: DatabaseValue { get }
|
||||
|
||||
/// Returns a value initialized from `dbValue`, if possible.
|
||||
///
|
||||
/// - parameter dbValue: A DatabaseValue.
|
||||
/// - returns: A decoded value, or, if decoding is impossible, nil.
|
||||
static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self?
|
||||
|
||||
/// Creates a value from a missing column, if possible.
|
||||
///
|
||||
/// - warning: Do not customize the default implementation.
|
||||
///
|
||||
/// - returns: A decoded value, or, if decoding is impossible, nil.
|
||||
static func fromMissingColumn() -> Self?
|
||||
}
|
||||
|
||||
extension DatabaseValueConvertible {
|
||||
@@ -30,6 +40,12 @@ extension DatabaseValueConvertible {
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
databaseValue.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
|
||||
// `Optional` overrides this default behavior.
|
||||
/// Default implementation fails to decode a value from a missing column.
|
||||
public static func fromMissingColumn() -> Self? {
|
||||
nil // failure.
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
@@ -49,7 +65,7 @@ extension DatabaseValueConvertible {
|
||||
|
||||
static func decode(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
atUncheckedIndex index: CInt,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self
|
||||
{
|
||||
@@ -62,7 +78,7 @@ extension DatabaseValueConvertible {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try decode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
atUncheckedIndex: CInt(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
return try decode(
|
||||
@@ -70,48 +86,9 @@ extension DatabaseValueConvertible {
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
static func decodeIfPresent(
|
||||
fromDatabaseValue dbValue: DatabaseValue,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self?
|
||||
{
|
||||
// Use fromDatabaseValue before checking for null: this allows DatabaseValue to convert NULL to .null.
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
|
||||
}
|
||||
}
|
||||
|
||||
static func decodeIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self?
|
||||
{
|
||||
let dbValue = DatabaseValue(sqliteStatement: sqliteStatement, index: index)
|
||||
if let value = fromDatabaseValue(dbValue) {
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
return nil
|
||||
} else {
|
||||
throw RowDecodingError.valueMismatch(Self.self, context: context(), databaseValue: dbValue)
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
static func decodeIfPresent(fromRow row: Row, atUncheckedIndex index: Int) throws -> Self? {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try decodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
return try decodeIfPresent(
|
||||
fromDatabaseValue: row.impl.databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
try Optional<Self>.decode(fromRow: row, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,16 +105,17 @@ extension DatabaseValueConvertible {
|
||||
/// }
|
||||
public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: DatabaseCursor {
|
||||
public typealias Element = Value
|
||||
public let statement: Statement
|
||||
/// :nodoc:
|
||||
public let _statement: Statement
|
||||
/// :nodoc:
|
||||
public var _isDone = false
|
||||
private let columnIndex: Int32
|
||||
private let columnIndex: CInt
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
self._statement = statement
|
||||
if let adapter = adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
columnIndex = 0
|
||||
}
|
||||
@@ -149,61 +127,15 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
deinit {
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? statement.reset()
|
||||
try? _statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _element(sqliteStatement: SQLiteStatement) -> Value {
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
try! Value.decode(
|
||||
public func _element(sqliteStatement: SQLiteStatement) throws -> Value {
|
||||
try Value.decode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: columnIndex,
|
||||
context: RowDecodingContext(statement: statement, index: Int(columnIndex)))
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of optional database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let urls: NullableDatabaseValueCursor<URL> = try Optional<URL>.fetchCursor(db, sql: "SELECT url FROM link")
|
||||
/// while let url = urls.next() { // URL?
|
||||
/// print(url)
|
||||
/// }
|
||||
/// }
|
||||
public final class NullableDatabaseValueCursor<Value: DatabaseValueConvertible>: DatabaseCursor {
|
||||
public typealias Element = Value?
|
||||
public let statement: Statement
|
||||
/// :nodoc:
|
||||
public var _isDone = false
|
||||
private let columnIndex: Int32
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
if let adapter = adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
columnIndex = 0
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
public func _element(sqliteStatement: SQLiteStatement) -> Value? {
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
try! Value.decodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: columnIndex,
|
||||
context: RowDecodingContext(statement: statement, index: Int(columnIndex)))
|
||||
context: RowDecodingContext(statement: _statement, index: Int(columnIndex)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,7 +178,7 @@ extension DatabaseValueConvertible {
|
||||
public static func fetchCursor(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
{
|
||||
try DatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
@@ -266,7 +198,7 @@ extension DatabaseValueConvertible {
|
||||
public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
@@ -289,11 +221,11 @@ extension DatabaseValueConvertible {
|
||||
public static func fetchOne(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Self?
|
||||
{
|
||||
// fetchOne returns nil if there is no row, or if there is a row with a null value
|
||||
let cursor = try NullableDatabaseValueCursor<Self>(statement: statement, arguments: arguments, adapter: adapter)
|
||||
let cursor = try DatabaseValueCursor<Self?>(statement: statement, arguments: arguments, adapter: adapter)
|
||||
return try cursor.next() ?? nil
|
||||
}
|
||||
}
|
||||
@@ -313,7 +245,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Set<Self>
|
||||
{
|
||||
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
@@ -347,7 +279,7 @@ extension DatabaseValueConvertible {
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> DatabaseValueCursor<Self>
|
||||
{
|
||||
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
@@ -368,7 +300,7 @@ extension DatabaseValueConvertible {
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
@@ -392,7 +324,7 @@ extension DatabaseValueConvertible {
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Self?
|
||||
{
|
||||
try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
@@ -415,7 +347,7 @@ extension DatabaseValueConvertible where Self: Hashable {
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Set<Self>
|
||||
{
|
||||
try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
@@ -506,7 +438,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
@@ -526,7 +458,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
|
||||
/// An array of fetched values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -541,7 +473,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -555,7 +487,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible {
|
||||
extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
|
||||
/// A set of fetched values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let strings = try request.fetchSet(db) // Set<String>
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -565,295 +497,3 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
|
||||
try RowDecoder.fetchSet(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch cursors
|
||||
/// and arrays of optional DatabaseValueConvertible:
|
||||
///
|
||||
/// try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From Prepared Statement
|
||||
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
try NullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchAll(statement) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & Hashable {
|
||||
/// Returns a set of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchSet(statement) // Set<String?>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
{
|
||||
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
|
||||
/// Returns a cursor over optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchAll(db, sql: "SELECT name FROM ...") // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & Hashable {
|
||||
/// Returns a set of optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try String.fetchSet(db, sql: "SELECT name FROM ...") // Set<String?>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
{
|
||||
try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching From FetchRequest
|
||||
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
|
||||
throws -> NullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchCursor(request.statement, adapter: request.adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Wrapped?] {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(request.statement, adapter: request.adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & Hashable {
|
||||
/// Returns a set of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try Optional<String>.fetchSet(db, request) // Set<String?>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A set of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet<R: FetchRequest>(_ db: Database, _ request: R) throws -> Set<Wrapped?> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchSet(request.statement, adapter: request.adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible {
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> NullableDatabaseValueCursor<RowDecoder.Wrapped> {
|
||||
try Optional<RowDecoder.Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchAll(db) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] {
|
||||
try Optional<RowDecoder.Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String?
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? {
|
||||
try RowDecoder.Wrapped.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder: _OptionalProtocol, RowDecoder.Wrapped: DatabaseValueConvertible & Hashable {
|
||||
/// A set of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchSet(db) // Set<String?>
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder.Wrapped?> {
|
||||
try Optional<RowDecoder.Wrapped>.fetchSet(db, self)
|
||||
}
|
||||
}
|
||||
@@ -89,7 +89,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// - parameter updates: The updates to the database.
|
||||
/// - throws: The error thrown by the updates.
|
||||
@_disfavoredOverload // SR-15150 Async overloading in protocol implementation fails
|
||||
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) rethrows -> T
|
||||
func barrierWriteWithoutTransaction<T>(_ updates: (Database) throws -> T) throws -> T
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// outside of any transaction, and returns the result.
|
||||
@@ -98,8 +98,10 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// until all pending writes and reads are completed. They postpone all
|
||||
/// other writes and reads until they are completed.
|
||||
///
|
||||
/// - parameter updates: The updates to the database.
|
||||
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void)
|
||||
/// - parameter updates: A function that accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the barrier access to the database.
|
||||
func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void)
|
||||
|
||||
/// Asynchronously executes database updates in a protected dispatch queue,
|
||||
/// wrapped inside a transaction.
|
||||
@@ -286,13 +288,13 @@ extension DatabaseWriter {
|
||||
/// the observer lifetime (observation lasts until observer
|
||||
/// is deallocated).
|
||||
public func add(
|
||||
transactionObserver: TransactionObserver,
|
||||
transactionObserver: some TransactionObserver,
|
||||
extent: Database.TransactionObservationExtent = .observerLifetime)
|
||||
{
|
||||
writeWithoutTransaction { $0.add(transactionObserver: transactionObserver, extent: extent) }
|
||||
}
|
||||
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
public func remove(transactionObserver: some TransactionObserver) {
|
||||
writeWithoutTransaction { $0.remove(transactionObserver: transactionObserver) }
|
||||
}
|
||||
|
||||
@@ -365,7 +367,7 @@ extension DatabaseWriter {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
assert(!configuration.readonly, "Use _addReadOnly(observation:) instead")
|
||||
let observer = ValueWriteOnlyObserver(
|
||||
@@ -380,11 +382,9 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=5.6) && canImport(_Concurrency)
|
||||
extension DatabaseWriter {
|
||||
// MARK: - Asynchronous Database Access
|
||||
|
||||
// TODO: remove @escaping as soon as it is possible
|
||||
/// Asynchronously executes database updates, wrapped inside a transaction,
|
||||
/// and returns the result.
|
||||
///
|
||||
@@ -408,7 +408,6 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: remove @escaping as soon as it is possible
|
||||
/// Asynchronously executes database updates, outside of any transaction,
|
||||
/// and returns the result.
|
||||
///
|
||||
@@ -432,7 +431,6 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: remove @escaping as soon as it is possible
|
||||
/// Asynchronously executes database updates, outside of any transaction,
|
||||
/// and returns the result.
|
||||
///
|
||||
@@ -450,12 +448,8 @@ extension DatabaseWriter {
|
||||
async throws -> T
|
||||
{
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
asyncBarrierWriteWithoutTransaction { db in
|
||||
do {
|
||||
try continuation.resume(returning: updates(db))
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
asyncBarrierWriteWithoutTransaction { dbResult in
|
||||
continuation.resume(with: dbResult.flatMap { db in Result { try updates(db) } })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -494,8 +488,6 @@ extension DatabaseWriter {
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
#if canImport(Combine)
|
||||
extension DatabaseWriter {
|
||||
@@ -633,7 +625,7 @@ extension DatabasePublishers {
|
||||
public typealias Output = Output
|
||||
public typealias Failure = Error
|
||||
|
||||
fileprivate let upstream: AnyPublisher<Output, Error>
|
||||
fileprivate let upstream: any Publisher<Output, Error>
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
|
||||
upstream.receive(subscriber: subscriber)
|
||||
@@ -644,7 +636,7 @@ extension DatabasePublishers {
|
||||
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
|
||||
extension Publisher where Failure == Error {
|
||||
fileprivate func eraseToWritePublisher() -> DatabasePublishers.Write<Output> {
|
||||
.init(upstream: eraseToAnyPublisher())
|
||||
.init(upstream: self)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -693,10 +685,10 @@ public class DatabaseFuture<Value> {
|
||||
/// Instances of AnyDatabaseWriter forward their methods to an arbitrary
|
||||
/// underlying database writer.
|
||||
public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
private let base: DatabaseWriter
|
||||
private let base: any DatabaseWriter
|
||||
|
||||
/// Creates a database writer that wraps a base database writer.
|
||||
public init(_ base: DatabaseWriter) {
|
||||
public init(_ base: some DatabaseWriter) {
|
||||
self.base = base
|
||||
}
|
||||
|
||||
@@ -760,11 +752,11 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
}
|
||||
|
||||
@_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 base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Database) -> Void) {
|
||||
public func asyncBarrierWriteWithoutTransaction(_ updates: @escaping (Result<Database, Error>) -> Void) {
|
||||
base.asyncBarrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
@@ -790,7 +782,7 @@ public final class AnyDatabaseWriter: DatabaseWriter {
|
||||
observation: ValueObservation<Reducer>,
|
||||
scheduling scheduler: ValueObservationScheduler,
|
||||
onChange: @escaping (Reducer.Value) -> Void)
|
||||
-> DatabaseCancellable
|
||||
-> AnyDatabaseCancellable
|
||||
{
|
||||
base._add(
|
||||
observation: observation,
|
||||
|
||||
@@ -4,13 +4,14 @@
|
||||
/// rows should be interpreted.
|
||||
///
|
||||
/// struct Player: FetchableRecord { ... }
|
||||
/// let request: ... // Some FetchRequest that fetches Player
|
||||
/// let request: some FetchRequest<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 {
|
||||
public protocol FetchRequest<RowDecoder>: SQLSubqueryable, DatabaseRegionConvertible {
|
||||
/// The type that tells how fetched database rows should be interpreted.
|
||||
associatedtype RowDecoder
|
||||
|
||||
@@ -52,14 +53,14 @@ public struct PreparedRequest {
|
||||
public var statement: Statement
|
||||
|
||||
/// An eventual adapter for rows fetched by the select statement
|
||||
public var adapter: RowAdapter?
|
||||
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,7 +75,7 @@ extension PreparedRequest: Refinable { }
|
||||
|
||||
extension FetchRequest {
|
||||
/// Returns an adapted request.
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
public func adapted(_ adapter: @escaping (Database) throws -> any RowAdapter) -> AdaptedFetchRequest<Self> {
|
||||
AdaptedFetchRequest(self, adapter)
|
||||
}
|
||||
}
|
||||
@@ -84,11 +85,11 @@ public struct AdaptedFetchRequest<Base: FetchRequest>: FetchRequest {
|
||||
public typealias RowDecoder = Base.RowDecoder
|
||||
|
||||
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
|
||||
}
|
||||
@@ -154,9 +155,7 @@ 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
|
||||
{
|
||||
public init(_ request: some FetchRequest<RowDecoder>) {
|
||||
self.init(request: ConcreteFetchRequestEraser(request: request))
|
||||
}
|
||||
}
|
||||
|
||||
+169
-314
@@ -7,7 +7,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection,
|
||||
{
|
||||
// It is not a violation of the Demeter law when another type uses this
|
||||
// property, which is exposed for optimizations.
|
||||
let impl: RowImpl
|
||||
let impl: any RowImpl
|
||||
|
||||
/// Unless we are producing a row array, we use a single row when iterating
|
||||
/// a statement:
|
||||
@@ -44,7 +44,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection,
|
||||
}
|
||||
|
||||
/// Creates a row from a dictionary of values.
|
||||
public convenience init(_ dictionary: [String: DatabaseValueConvertible?]) {
|
||||
public convenience init(_ dictionary: [String: (any DatabaseValueConvertible)?]) {
|
||||
self.init(impl: ArrayRowImpl(columns: dictionary.map { ($0, $1?.databaseValue ?? .null) }))
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection,
|
||||
/// The result is nil unless all dictionary keys are strings, and values
|
||||
/// adopt DatabaseValueConvertible.
|
||||
public convenience init?(_ dictionary: [AnyHashable: Any]) {
|
||||
var initDictionary = [String: DatabaseValueConvertible?]()
|
||||
var initDictionary = [String: (any DatabaseValueConvertible)?]()
|
||||
for (key, value) in dictionary {
|
||||
guard let columnName = key as? String else {
|
||||
return nil
|
||||
@@ -73,7 +73,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection,
|
||||
/// let row: Row = ["foo": 1, "foo": "bar", "baz": nil]
|
||||
/// print(row)
|
||||
/// // Prints [foo:1 foo:"bar" baz:NULL]
|
||||
public convenience init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) {
|
||||
public convenience init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) {
|
||||
self.init(impl: ArrayRowImpl(columns: elements.map { ($0, $1?.databaseValue ?? .null) }))
|
||||
}
|
||||
|
||||
@@ -128,7 +128,7 @@ public final class Row: Equatable, Hashable, RandomAccessCollection,
|
||||
columnNames: statement.columnNames))
|
||||
}
|
||||
|
||||
init(impl: RowImpl) {
|
||||
init(impl: any RowImpl) {
|
||||
self.statement = nil
|
||||
self.sqliteStatement = nil
|
||||
self.impl = impl
|
||||
@@ -213,7 +213,7 @@ extension Row {
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
public subscript(_ index: Int) -> DatabaseValueConvertible? {
|
||||
public subscript(_ index: Int) -> (any DatabaseValueConvertible)? {
|
||||
_checkIndex(index)
|
||||
return impl.databaseValue(atUncheckedIndex: index).storage.value
|
||||
}
|
||||
@@ -223,39 +223,18 @@ extension Row {
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
|
||||
/// value is converted to the requested type `Value`. Should this conversion
|
||||
/// fail, a fatal error is raised.
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value? {
|
||||
try! decodeIfPresent(Value.self, atIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
/// For example:
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
|
||||
/// let score: Int = row[0] // 42
|
||||
///
|
||||
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
|
||||
/// value is converted to the requested type `Value`. Should this conversion
|
||||
/// fail, a fatal error is raised.
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
|
||||
/// let name: String = row[0] // "Alice"
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value? {
|
||||
try! decodeIfPresent(Value.self, atIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// This method crashes if the fetched SQLite value is NULL, or if the
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
|
||||
/// let name: String? = row[0] // nil
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ index: Int) -> Value {
|
||||
try! decode(Value.self, atIndex: index)
|
||||
@@ -266,12 +245,22 @@ extension Row {
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// This method crashes if the fetched SQLite value is NULL, or if the
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
/// ``StatementColumnConvertible``. It can trigger SQLite built-in
|
||||
/// conversions (see <https://www.sqlite.org/datatype3.html>).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42")!
|
||||
/// let score: Int = row[0] // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice'")!
|
||||
/// let name: String = row[0] // "Alice"
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL")!
|
||||
/// let name: String? = row[0] // nil
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ index: Int) -> Value {
|
||||
@@ -285,7 +274,7 @@ extension Row {
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// The result is nil if the row does not contain the column.
|
||||
public subscript(_ columnName: String) -> DatabaseValueConvertible? {
|
||||
public subscript(_ columnName: String) -> (any DatabaseValueConvertible)? {
|
||||
// IMPLEMENTATION NOTE
|
||||
// This method has a single known use case: checking if the value is nil,
|
||||
// as in:
|
||||
@@ -304,40 +293,23 @@ extension Row {
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. Otherwise the SQLite value is converted to the requested type
|
||||
/// `Value`. Should this conversion fail, a fatal error is raised.
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value? {
|
||||
try! decodeIfPresent(Value.self, forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
/// For example:
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score: Int = row["score"] // 42
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. Otherwise the SQLite value is converted to the requested type
|
||||
/// `Value`. Should this conversion fail, a fatal error is raised.
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String = row["name"] // "Alice"
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value? {
|
||||
try! decodeIfPresent(Value.self, forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = row["name"] // nil
|
||||
///
|
||||
/// If the row does not contain the column, a fatal error is raised.
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// This method crashes if the fetched SQLite value is NULL, or if the
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT ...")!
|
||||
/// let name: String? = row["missing"] // nil
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
@@ -348,27 +320,40 @@ extension Row {
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain the column, a fatal error is raised.
|
||||
///
|
||||
/// This method crashes if the fetched SQLite value is NULL, or if the
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// `StatementColumnConvertible`. It can trigger SQLite built-in conversions
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score: Int = row["score"] // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String = row["name"] // "Alice"
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = row["name"] // nil
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT ...")!
|
||||
/// let name: String? = row["missing"] // nil
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns Int64, Double, String, NSData or nil, depending on the value
|
||||
/// Returns Int64, Double, String, Data or nil, depending on the value
|
||||
/// stored at the given column.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// The result is nil if the row does not contain the column.
|
||||
public subscript<Column: ColumnExpression>(_ column: Column) -> DatabaseValueConvertible? {
|
||||
public subscript(_ column: some ColumnExpression) -> (any DatabaseValueConvertible)? {
|
||||
self[column.name]
|
||||
}
|
||||
|
||||
@@ -377,47 +362,25 @@ extension Row {
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. Otherwise the SQLite value is converted to the requested type
|
||||
/// `Value`. Should this conversion fail, a fatal error is raised.
|
||||
/// For example:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score: Int = row[Column("score")] // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String = row[Column("name")] // "Alice"
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = row[Column("name")] // nil
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT ...")!
|
||||
/// let name: String? = row[Column("missing")] // nil
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible, Column: ColumnExpression>(_ column: Column) -> Value? {
|
||||
try! decodeIfPresent(Value.self, forKey: column.name)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. Otherwise the SQLite value is converted to the requested type
|
||||
/// `Value`. Should this conversion fail, a fatal error is raised.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inlinable
|
||||
public subscript<Value, Column>(_ column: Column)
|
||||
-> Value?
|
||||
where
|
||||
Value: DatabaseValueConvertible & StatementColumnConvertible,
|
||||
Column: ColumnExpression
|
||||
{
|
||||
try! decodeIfPresent(Value.self, forKey: column.name)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain the column, a fatal error is raised.
|
||||
///
|
||||
/// This method crashes if the fetched SQLite value is NULL, or if the
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible, Column: ColumnExpression>(_ column: Column) -> Value {
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: some ColumnExpression) -> Value {
|
||||
try! decode(Value.self, forKey: column.name)
|
||||
}
|
||||
|
||||
@@ -426,25 +389,36 @@ extension Row {
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the row does not contain the column, a fatal error is raised.
|
||||
///
|
||||
/// This method crashes if the fetched SQLite value is NULL, or if the
|
||||
/// SQLite value can not be converted to `Value`.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// ``StatementColumnConvertible``. It can trigger SQLite built-in conversions
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 42 AS score")!
|
||||
/// let score: Int = row[Column("score")] // 42
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT 'Alice' AS name")!
|
||||
/// let name: String = row[Column("name")] // "Alice"
|
||||
///
|
||||
/// When the database value may be nil, ask for an optional:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT NULL AS name")!
|
||||
/// let name: String? = row[Column("name")] // nil
|
||||
///
|
||||
/// When the column does not exist, nil is returned:
|
||||
///
|
||||
/// let row = try Row.fetchOne(db, sql: "SELECT ...")!
|
||||
/// let name: String? = row[Column("missing")] // nil
|
||||
@inlinable
|
||||
public subscript<Value, Column>(_ column: Column)
|
||||
public subscript<Value>(_ column: some ColumnExpression)
|
||||
-> Value
|
||||
where
|
||||
Value: DatabaseValueConvertible & StatementColumnConvertible,
|
||||
Column: ColumnExpression
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
try! decode(Value.self, forKey: column.name)
|
||||
}
|
||||
|
||||
/// Returns the optional Data at given index.
|
||||
/// Returns the optional `Data` at given index.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
@@ -458,7 +432,7 @@ extension Row {
|
||||
try! decodeDataNoCopyIfPresent(atIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the optional Data at given column.
|
||||
/// Returns the optional `Data` at given column.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
@@ -473,18 +447,18 @@ extension Row {
|
||||
try! decodeDataNoCopyIfPresent(forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns the optional `NSData` at given column.
|
||||
/// Returns the optional `Data` at given column.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. If the SQLite value can not be converted to NSData, a fatal error
|
||||
/// nil. If the SQLite value can not be converted to Data, a fatal error
|
||||
/// is raised.
|
||||
///
|
||||
/// The returned data does not owns its bytes: it must not be used longer
|
||||
/// than the row's lifetime.
|
||||
public func dataNoCopy<Column: ColumnExpression>(_ column: Column) -> Data? {
|
||||
public func dataNoCopy(_ column: some ColumnExpression) -> Data? {
|
||||
try! decodeDataNoCopyIfPresent(forKey: column.name)
|
||||
}
|
||||
}
|
||||
@@ -513,7 +487,7 @@ extension Row {
|
||||
/// let request = Book.including(required: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Book(row: row).title)
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// let author: Author = row["author"]
|
||||
@@ -525,7 +499,7 @@ extension Row {
|
||||
/// let request = Book.including(required: Book.author.including(required: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Book(row: row).title)
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// let country: Country = row["country"]
|
||||
@@ -548,7 +522,7 @@ extension Row {
|
||||
/// let request = Book.including(optional: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Book(row: row).title)
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// let author: Author? = row["author"]
|
||||
@@ -560,7 +534,7 @@ extension Row {
|
||||
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Book(row: row).title)
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// let country: Country? = row["country"]
|
||||
@@ -583,7 +557,7 @@ extension Row {
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Author(row: row).name)
|
||||
/// try print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// let books: [Book] = row["books"]
|
||||
@@ -605,7 +579,7 @@ extension Row {
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Author(row: row).name)
|
||||
/// try print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// let books: Set<Book> = row["books"]
|
||||
@@ -702,24 +676,6 @@ extension Row {
|
||||
// MARK: - Throwing DatabaseValueConvertible Decoding Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
|
||||
/// value is converted to the requested type `Value`. If the conversion
|
||||
/// fail, a `RowDecodingError` is thrown.
|
||||
@inlinable
|
||||
func decodeIfPresent<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
_checkIndex(index)
|
||||
return try Value.decodeIfPresent(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
@@ -737,26 +693,6 @@ extension Row {
|
||||
return try Value.decode(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. Otherwise the SQLite value is converted to the requested type
|
||||
/// `Value`. If the conversion fails, a `RowDecodingError` is thrown.
|
||||
@inlinable
|
||||
func decodeIfPresent<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forKey columnName: String)
|
||||
throws -> Value?
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return try Value.decodeIfPresent(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
@@ -772,7 +708,11 @@ extension Row {
|
||||
throws -> Value
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self))
|
||||
if let value = Value.fromMissingColumn() {
|
||||
return value
|
||||
} else {
|
||||
throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self))
|
||||
}
|
||||
}
|
||||
return try Value.decode(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
@@ -781,29 +721,6 @@ extension Row {
|
||||
// MARK: - Throwing DatabaseValueConvertible & StatementColumnConvertible Decoding Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
/// righmost column.
|
||||
///
|
||||
/// If the SQLite value is NULL, the result is nil. Otherwise the SQLite
|
||||
/// value is converted to the requested type `Value`. If the conversion
|
||||
/// fail, a `RowDecodingError` is thrown.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
func decodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
_checkIndex(index)
|
||||
return try Value.fastDecodeIfPresent(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given index, converted to the requested type.
|
||||
///
|
||||
/// Indexes span from 0 for the leftmost column to (row.count - 1) for the
|
||||
@@ -826,31 +743,6 @@ extension Row {
|
||||
return try Value.fastDecode(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
/// the same name, the leftmost column is considered.
|
||||
///
|
||||
/// If the column is missing or if the SQLite value is NULL, the result is
|
||||
/// nil. Otherwise the SQLite value is converted to the requested type
|
||||
/// `Value`. If the conversion fails, a `RowDecodingError` is thrown.
|
||||
///
|
||||
/// This method exists as an optimization opportunity for types that adopt
|
||||
/// StatementColumnConvertible. It *may* trigger SQLite built-in conversions
|
||||
/// (see <https://www.sqlite.org/datatype3.html>).
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
func decodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forKey columnName: String)
|
||||
throws -> Value?
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
return nil
|
||||
}
|
||||
return try Value.fastDecodeIfPresent(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
///
|
||||
/// Column name lookup is case-insensitive, and when several columns have
|
||||
@@ -870,7 +762,11 @@ extension Row {
|
||||
throws -> Value
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self))
|
||||
if let value = Value.fromMissingColumn() {
|
||||
return value
|
||||
} else {
|
||||
throw RowDecodingError.columnNotFound(columnName, context: RowDecodingContext(row: self))
|
||||
}
|
||||
}
|
||||
return try Value.fastDecode(fromRow: self, atUncheckedIndex: index)
|
||||
}
|
||||
@@ -884,16 +780,6 @@ extension Row {
|
||||
{
|
||||
try impl.fastDecode(type, atUncheckedIndex: index)
|
||||
}
|
||||
|
||||
// Support for fast decoding in scoped rows
|
||||
@usableFromInline
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
try impl.fastDecodeIfPresent(type, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Throwing Data Decoding Methods
|
||||
@@ -986,7 +872,7 @@ extension Row {
|
||||
/// let request = Book.including(optional: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Book(row: row).title)
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// let author: Author? = row["author"]
|
||||
@@ -998,7 +884,7 @@ extension Row {
|
||||
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Book(row: row).title)
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// let country: Country? = row["country"]
|
||||
@@ -1018,7 +904,7 @@ extension Row {
|
||||
guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else {
|
||||
return nil
|
||||
}
|
||||
return Record(row: scopedRow)
|
||||
return try Record(row: scopedRow)
|
||||
}
|
||||
|
||||
/// Returns the record associated with the given scope.
|
||||
@@ -1028,7 +914,7 @@ extension Row {
|
||||
/// let request = Book.including(required: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Book(row: row).title)
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// let author: Author = row["author"]
|
||||
@@ -1040,7 +926,7 @@ extension Row {
|
||||
/// let request = Book.including(required: Book.author.including(required: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Book(row: row).title)
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// let country: Country = row["country"]
|
||||
@@ -1087,7 +973,7 @@ extension Row {
|
||||
scope \(String(reflecting: scope)) only contains null values
|
||||
"""))
|
||||
}
|
||||
return Record(row: scopedRow)
|
||||
return try Record(row: scopedRow)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1101,7 +987,7 @@ extension Row {
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Author(row: row).name)
|
||||
/// try print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// let books: [Book] = row["books"]
|
||||
@@ -1140,7 +1026,7 @@ extension Row {
|
||||
var collection = Collection()
|
||||
collection.reserveCapacity(rows.count)
|
||||
for row in rows {
|
||||
collection.append(Collection.Element(row: row))
|
||||
try collection.append(Collection.Element(row: row))
|
||||
}
|
||||
return collection
|
||||
}
|
||||
@@ -1152,7 +1038,7 @@ extension Row {
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// print(Author(row: row).name)
|
||||
/// try print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// let books: Set<Book> = row["books"]
|
||||
@@ -1186,7 +1072,7 @@ extension Row {
|
||||
}
|
||||
var set = Set<Record>(minimumCapacity: rows.count)
|
||||
for row in rows {
|
||||
set.insert(Record(row: row))
|
||||
try set.insert(Record(row: row))
|
||||
}
|
||||
return set
|
||||
}
|
||||
@@ -1201,13 +1087,14 @@ extension Row {
|
||||
/// }
|
||||
public final class RowCursor: DatabaseCursor {
|
||||
public typealias Element = Row
|
||||
public let statement: Statement
|
||||
/// :nodoc:
|
||||
public let _statement: Statement
|
||||
/// :nodoc:
|
||||
public var _isDone = false
|
||||
@usableFromInline let _row: Row // Reused for performance
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
self._statement = statement
|
||||
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
@@ -1217,7 +1104,7 @@ public final class RowCursor: DatabaseCursor {
|
||||
deinit {
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? statement.reset()
|
||||
try? _statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@@ -1261,7 +1148,7 @@ extension Row {
|
||||
public static func fetchCursor(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> RowCursor
|
||||
{
|
||||
try RowCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
@@ -1281,7 +1168,7 @@ extension Row {
|
||||
public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> [Row]
|
||||
{
|
||||
// The cursor reuses a single mutable row. Return immutable copies.
|
||||
@@ -1302,7 +1189,7 @@ extension Row {
|
||||
public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Set<Row>
|
||||
{
|
||||
// The cursor reuses a single mutable row. Return immutable copies.
|
||||
@@ -1323,7 +1210,7 @@ extension Row {
|
||||
public static func fetchOne(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Row?
|
||||
{
|
||||
let cursor = try fetchCursor(statement, arguments: arguments, adapter: adapter)
|
||||
@@ -1370,7 +1257,7 @@ extension Row {
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> RowCursor
|
||||
{
|
||||
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
@@ -1395,7 +1282,7 @@ extension Row {
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> [Row]
|
||||
{
|
||||
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
@@ -1420,7 +1307,7 @@ extension Row {
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Set<Row>
|
||||
{
|
||||
try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
@@ -1445,7 +1332,7 @@ extension Row {
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Row?
|
||||
{
|
||||
try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
@@ -1547,13 +1434,13 @@ extension Row {
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest where RowDecoder == Row {
|
||||
extension FetchRequest<Row> {
|
||||
|
||||
// MARK: Fetching Rows
|
||||
|
||||
/// A cursor over fetched rows.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches Row
|
||||
/// let request: some FetchRequest<Row> = ...
|
||||
/// let rows = try request.fetchCursor(db) // RowCursor
|
||||
/// while let row = try rows.next() { // Row
|
||||
/// let id: Int64 = row[0]
|
||||
@@ -1582,7 +1469,7 @@ extension FetchRequest where RowDecoder == Row {
|
||||
|
||||
/// An array of fetched rows.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches Row
|
||||
/// let request: some FetchRequest<Row> = ...
|
||||
/// let rows = try request.fetchAll(db)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -1594,7 +1481,7 @@ extension FetchRequest where RowDecoder == Row {
|
||||
|
||||
/// A set of fetched rows.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches Row
|
||||
/// let request: some FetchRequest<Row> = ...
|
||||
/// let rows = try request.fetchSet(db)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -1606,7 +1493,7 @@ extension FetchRequest where RowDecoder == Row {
|
||||
|
||||
/// The first fetched row.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches Row
|
||||
/// let request: some FetchRequest<Row> = ...
|
||||
/// let row = try request.fetchOne(db)
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -1810,13 +1697,13 @@ extension Row {
|
||||
/// row.scopes["bar"] // [bar:2]
|
||||
/// row.scopes["baz"] // nil
|
||||
public struct ScopesView: Collection {
|
||||
public typealias Index = Dictionary<String, _LayoutedRowAdapter>.Index
|
||||
public typealias Index = Dictionary<String, any _LayoutedRowAdapter>.Index
|
||||
private let row: Row
|
||||
private let scopes: [String: _LayoutedRowAdapter]
|
||||
private let scopes: [String: any _LayoutedRowAdapter]
|
||||
private let prefetchedRows: Row.PrefetchedRowsView
|
||||
|
||||
/// The scopes defined on this row.
|
||||
public var names: Dictionary<String, _LayoutedRowAdapter>.Keys {
|
||||
public var names: Dictionary<String, any _LayoutedRowAdapter>.Keys {
|
||||
scopes.keys
|
||||
}
|
||||
|
||||
@@ -1824,7 +1711,7 @@ extension Row {
|
||||
self.init(row: Row(), scopes: [:], prefetchedRows: Row.PrefetchedRowsView())
|
||||
}
|
||||
|
||||
init(row: Row, scopes: [String: _LayoutedRowAdapter], prefetchedRows: Row.PrefetchedRowsView) {
|
||||
init(row: Row, scopes: [String: any _LayoutedRowAdapter], prefetchedRows: Row.PrefetchedRowsView) {
|
||||
self.row = row
|
||||
self.scopes = scopes
|
||||
self.prefetchedRows = prefetchedRows
|
||||
@@ -2039,7 +1926,7 @@ extension Row {
|
||||
}
|
||||
}
|
||||
|
||||
extension OrderedDictionary where Key == String, Value == Row.Prefetch {
|
||||
extension OrderedDictionary<String, Row.Prefetch> {
|
||||
fileprivate mutating func setRows(_ rows: [Row], forKeyPath keyPath: [String]) {
|
||||
var keyPath = keyPath
|
||||
let key = keyPath.removeFirst()
|
||||
@@ -2068,11 +1955,6 @@ protocol RowImpl {
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value?
|
||||
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data
|
||||
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data?
|
||||
@@ -2123,17 +2005,6 @@ extension RowImpl {
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
// unless customized, use slow decoding (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
try Value.decodeIfPresent(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
|
||||
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
try Data.decode(
|
||||
@@ -2143,7 +2014,7 @@ extension RowImpl {
|
||||
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
|
||||
// unless customized, copy data (see StatementRowImpl and AdaptedRowImpl for customization)
|
||||
try Data.decodeIfPresent(
|
||||
try Optional<Data>.decode(
|
||||
fromDatabaseValue: databaseValue(atUncheckedIndex: index),
|
||||
context: RowDecodingContext(row: Row(impl: self), key: .columnIndex(index)))
|
||||
}
|
||||
@@ -2154,9 +2025,7 @@ extension RowImpl {
|
||||
struct ArrayRowImpl: RowImpl {
|
||||
let columns: [(String, DatabaseValue)]
|
||||
|
||||
init<C>(columns: C)
|
||||
where C: Collection, C.Element == (String, DatabaseValue)
|
||||
{
|
||||
init(columns: some Collection<(String, DatabaseValue)>) {
|
||||
self.columns = Array(columns)
|
||||
}
|
||||
|
||||
@@ -2182,12 +2051,9 @@ struct ArrayRowImpl: RowImpl {
|
||||
}
|
||||
}
|
||||
|
||||
#if swift(>=5.6) && canImport(_Concurrency)
|
||||
// @unchecked because columns property is not inferred as Sendable
|
||||
// TODO: remove this @unchecked when compiler can handle tuples.
|
||||
extension ArrayRowImpl: @unchecked Sendable { }
|
||||
#endif
|
||||
|
||||
|
||||
// TODO: merge with ArrayRowImpl eventually?
|
||||
/// See Row.init(copiedFromStatementRef:sqliteStatement:)
|
||||
@@ -2238,7 +2104,7 @@ private struct StatementRowImpl: RowImpl {
|
||||
self.sqliteStatement = sqliteStatement
|
||||
// Optimize row[columnName]
|
||||
let lowercaseColumnNames = (0..<sqlite3_column_count(sqliteStatement))
|
||||
.map { String(cString: sqlite3_column_name(sqliteStatement, Int32($0))).lowercased() }
|
||||
.map { String(cString: sqlite3_column_name(sqliteStatement, CInt($0))).lowercased() }
|
||||
self.lowercaseColumnIndexes = Dictionary(
|
||||
lowercaseColumnNames
|
||||
.enumerated()
|
||||
@@ -2254,11 +2120,11 @@ private struct StatementRowImpl: RowImpl {
|
||||
|
||||
func hasNull(atUncheckedIndex index: Int) -> Bool {
|
||||
// Avoid extracting values, because this modifies the SQLite statement.
|
||||
sqlite3_column_type(sqliteStatement, Int32(index)) == SQLITE_NULL
|
||||
sqlite3_column_type(sqliteStatement, CInt(index)) == SQLITE_NULL
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
DatabaseValue(sqliteStatement: sqliteStatement, index: CInt(index))
|
||||
}
|
||||
|
||||
func fastDecode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
@@ -2268,40 +2134,29 @@ private struct StatementRowImpl: RowImpl {
|
||||
{
|
||||
try Value.fastDecode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(statement: statement, index: index))
|
||||
}
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
try Value.fastDecodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
atUncheckedIndex: CInt(index),
|
||||
context: RowDecodingContext(statement: statement, index: index))
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopy(atUncheckedIndex index: Int) throws -> Data {
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
guard sqlite3_column_type(sqliteStatement, CInt(index)) != SQLITE_NULL else {
|
||||
throw RowDecodingError.valueMismatch(Data.self, statement: statement, index: index)
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, CInt(index)) else {
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, CInt(index)))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
func fastDecodeDataNoCopyIfPresent(atUncheckedIndex index: Int) throws -> Data? {
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
guard sqlite3_column_type(sqliteStatement, CInt(index)) != SQLITE_NULL else {
|
||||
return nil
|
||||
}
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, Int32(index)) else {
|
||||
guard let bytes = sqlite3_column_blob(sqliteStatement, CInt(index)) else {
|
||||
return Data()
|
||||
}
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, Int32(index)))
|
||||
let count = Int(sqlite3_column_bytes(sqliteStatement, CInt(index)))
|
||||
return Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: bytes), count: count, deallocator: .none)
|
||||
}
|
||||
|
||||
@@ -2328,11 +2183,11 @@ private struct SQLiteStatementRowImpl: RowImpl {
|
||||
var isFetched: Bool { true }
|
||||
|
||||
func columnName(atUncheckedIndex index: Int) -> String {
|
||||
String(cString: sqlite3_column_name(sqliteStatement, Int32(index)))
|
||||
String(cString: sqlite3_column_name(sqliteStatement, CInt(index)))
|
||||
}
|
||||
|
||||
func databaseValue(atUncheckedIndex index: Int) -> DatabaseValue {
|
||||
DatabaseValue(sqliteStatement: sqliteStatement, index: Int32(index))
|
||||
DatabaseValue(sqliteStatement: sqliteStatement, index: CInt(index))
|
||||
}
|
||||
|
||||
func index(forColumn name: String) -> Int? {
|
||||
|
||||
+27
-36
@@ -18,7 +18,7 @@ import Foundation
|
||||
/// row.scopes["b"] // [2, 3, 4]
|
||||
/// row.scopes["c"] // [5, 6]
|
||||
/// row.scopes["d"] // [7, 8]
|
||||
public func splittingRowAdapters(columnCounts: [Int]) -> [RowAdapter] {
|
||||
public func splittingRowAdapters(columnCounts: [Int]) -> [any RowAdapter] {
|
||||
guard !columnCounts.isEmpty else {
|
||||
// Identity adapter
|
||||
return [SuffixRowAdapter(fromIndex: 0)]
|
||||
@@ -66,14 +66,14 @@ 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(layoutColumns: some Sequence<(Int, String)>) {
|
||||
self._layoutColumns = Array(layoutColumns)
|
||||
self.lowercaseColumnIndexes = Dictionary(
|
||||
layoutColumns
|
||||
@@ -97,7 +97,7 @@ extension _LayoutedColumnMapping: _LayoutedRowAdapter {
|
||||
public var _mapping: _LayoutedColumnMapping { self }
|
||||
|
||||
/// Returns the empty dictionary.
|
||||
public var _scopes: [String: _LayoutedRowAdapter] { [:] }
|
||||
public var _scopes: [String: any _LayoutedRowAdapter] { [:] }
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@@ -124,7 +124,7 @@ public protocol _LayoutedRowAdapter {
|
||||
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
|
||||
@@ -169,14 +169,14 @@ 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
|
||||
@@ -208,7 +208,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 +218,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)
|
||||
}
|
||||
}
|
||||
@@ -229,7 +229,7 @@ public struct EmptyRowAdapter: RowAdapter {
|
||||
public init() { }
|
||||
|
||||
/// :nodoc:
|
||||
public func _layoutedAdapter(from layout: _RowLayout) throws -> _LayoutedRowAdapter {
|
||||
public func _layoutedAdapter(from layout: some _RowLayout) throws -> any _LayoutedRowAdapter {
|
||||
_LayoutedColumnMapping(layoutColumns: [])
|
||||
}
|
||||
}
|
||||
@@ -252,7 +252,7 @@ public struct ColumnMapping: RowAdapter {
|
||||
}
|
||||
|
||||
/// :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 {
|
||||
@@ -293,7 +293,7 @@ public struct SuffixRowAdapter: RowAdapter {
|
||||
}
|
||||
|
||||
/// :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))
|
||||
}
|
||||
}
|
||||
@@ -322,7 +322,7 @@ public struct RangeRowAdapter: RowAdapter {
|
||||
}
|
||||
|
||||
/// :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 +352,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 +392,13 @@ 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 +413,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)
|
||||
}
|
||||
}
|
||||
@@ -444,7 +444,7 @@ public struct RenameColumnAdapter: RowAdapter {
|
||||
}
|
||||
|
||||
/// :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 +452,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 +467,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,15 +503,6 @@ struct AdaptedRowImpl: RowImpl {
|
||||
return try Value.fastDecode(fromRow: base, atUncheckedIndex: mappedIndex)
|
||||
}
|
||||
|
||||
func fastDecodeIfPresent<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type,
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Value?
|
||||
{
|
||||
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)
|
||||
|
||||
@@ -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
|
||||
|
||||
+74
-12
@@ -10,16 +10,42 @@
|
||||
/// try db.execute(literal: query)
|
||||
/// }
|
||||
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 +53,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 +91,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
|
||||
@@ -96,7 +134,7 @@ public struct SQL {
|
||||
/// let emailLiteral = [columnLiteral, suffixLiteral].joined(separator: " || ")
|
||||
/// let request = User.select(emailLiteral.sqlExpression)
|
||||
/// let emails = try String.fetchAll(db, request)
|
||||
public init(_ expression: SQLSpecificExpressible) {
|
||||
public init(_ expression: some SQLSpecificExpressible) {
|
||||
self.init(elements: [.expression(expression.sqlExpression)])
|
||||
}
|
||||
|
||||
@@ -172,7 +210,7 @@ extension SQL: SQLSpecificExpressible {
|
||||
/// Use this property when you need an explicit `SQLExpression`.
|
||||
/// For example:
|
||||
///
|
||||
/// func date(_ value: SQLExpressible) -> SQLExpression {
|
||||
/// func date(_ value: some SQLExpressible) -> SQLExpression {
|
||||
/// SQL("DATE(\(value))").sqlExpression
|
||||
/// }
|
||||
///
|
||||
@@ -185,20 +223,36 @@ extension SQL: SQLSpecificExpressible {
|
||||
}
|
||||
|
||||
extension SQL: SQLSelectable {
|
||||
/// Creates a literal SQL expression.
|
||||
///
|
||||
/// Use this property when you need an explicit `SQLSelection`. For example:
|
||||
///
|
||||
/// // 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.
|
||||
///
|
||||
/// Use this property when you need an explicit `SQLOrdering`. For example:
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY name DESC
|
||||
/// let ordering = SQL("name DESC").sqlOrdering
|
||||
/// let request = Player.order(ordering)
|
||||
public var sqlOrdering: SQLOrdering {
|
||||
.literal(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension Sequence where Element == SQL {
|
||||
extension Sequence<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.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
@@ -206,6 +260,9 @@ extension Sequence where Element == SQL {
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
///
|
||||
/// - Note: The separator is a raw SQL string, not an SQL literal that
|
||||
/// supports [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
public func joined(separator: String = "") -> SQL {
|
||||
if separator.isEmpty {
|
||||
return SQL(elements: flatMap(\.elements))
|
||||
@@ -215,9 +272,11 @@ extension Sequence where Element == SQL {
|
||||
}
|
||||
}
|
||||
|
||||
extension Collection where Element == SQL {
|
||||
extension Collection<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.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// let components: [SQL] = [
|
||||
/// "UPDATE player",
|
||||
@@ -225,6 +284,9 @@ extension Collection where Element == SQL {
|
||||
/// "WHERE id = \(id)"
|
||||
/// ]
|
||||
/// let query = components.joined(separator: " ")
|
||||
///
|
||||
/// - Note: The separator is a raw SQL string, not an SQL literal that
|
||||
/// supports [SQL Interpolation](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md).
|
||||
public func joined(separator: String = "") -> SQL {
|
||||
if separator.isEmpty {
|
||||
return SQL(elements: flatMap(\.elements))
|
||||
|
||||
@@ -13,14 +13,14 @@ public struct SQLRequest<RowDecoder> {
|
||||
}
|
||||
|
||||
/// The request adapter
|
||||
public var adapter: RowAdapter?
|
||||
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)
|
||||
{
|
||||
@@ -51,7 +51,7 @@ extension SQLRequest {
|
||||
public init(
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil,
|
||||
adapter: (any RowAdapter)? = nil,
|
||||
cached: Bool = false)
|
||||
{
|
||||
self.init(
|
||||
@@ -77,7 +77,7 @@ extension SQLRequest {
|
||||
/// - 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,7 +86,7 @@ extension SQLRequest {
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRequest where RowDecoder == Row {
|
||||
extension SQLRequest<Row> {
|
||||
/// Creates a request from an SQL string, optional arguments, and
|
||||
/// optional row adapter.
|
||||
///
|
||||
@@ -104,7 +104,7 @@ extension SQLRequest where RowDecoder == Row {
|
||||
public init(
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil,
|
||||
adapter: (any RowAdapter)? = nil,
|
||||
cached: Bool = false)
|
||||
{
|
||||
self.init(
|
||||
@@ -130,7 +130,7 @@ extension SQLRequest where RowDecoder == Row {
|
||||
/// - 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,
|
||||
|
||||
@@ -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
|
||||
+90
-53
@@ -3,9 +3,26 @@ import Foundation
|
||||
/// A raw SQLite statement, suitable for the SQLite C API.
|
||||
public typealias SQLiteStatement = OpaquePointer
|
||||
|
||||
extension CharacterSet {
|
||||
/// Statements are separated by semicolons and white spaces
|
||||
static let sqlStatementSeparators = CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines)
|
||||
extension String {
|
||||
/// SQL statements are separated by semicolons and white spaces.
|
||||
///
|
||||
/// This character set is not an accurate representation of actual SQLite
|
||||
/// separators (which do not include non-ASCII white spaces for example),
|
||||
/// and must not be used for parsing. Its only purpose is to trim compiled
|
||||
/// SQL statements with `String.trimmedSQLStatement`.
|
||||
private static let sqlStatementSeparators = CharacterSet(charactersIn: ";").union(.whitespacesAndNewlines)
|
||||
|
||||
/// Returns a string trimmed from SQL statement separators.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// // "SELECT * FROM player"
|
||||
/// " SELECT * FROM player;".trimmedSQLStatement
|
||||
///
|
||||
/// - precondition: the input string is a successfully compiled SQL statement.
|
||||
var trimmedSQLStatement: String {
|
||||
trimmingCharacters(in: String.sqlStatementSeparators)
|
||||
}
|
||||
}
|
||||
|
||||
/// A statement represents an SQL query.
|
||||
@@ -27,28 +44,30 @@ public final class Statement {
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
// trim white space and semicolumn for homogeneous output
|
||||
return String(cString: sqlite3_sql(sqliteStatement))
|
||||
.trimmingCharacters(in: .sqlStatementSeparators)
|
||||
return String(cString: sqlite3_sql(sqliteStatement)).trimmedSQLStatement
|
||||
}
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public lazy var columnNames: [String] = {
|
||||
let sqliteStatement = self.sqliteStatement
|
||||
return (0..<Int32(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
return (0..<CInt(self.columnCount)).map { String(cString: sqlite3_column_name(sqliteStatement, $0)) }
|
||||
}()
|
||||
|
||||
// Database region is computed during statement compilation, and maybe
|
||||
// extended for select statements compiled by QueryInterfaceRequest, in
|
||||
// order to perform focused database observation. See
|
||||
// SQLQueryGenerator.makeStatement(_:)
|
||||
// The database region is reported by `sqlite3_set_authorizer`, and maybe
|
||||
// refined in `SQLQueryGenerator.makeStatement(_:)` when we have enough
|
||||
// information about the statement.
|
||||
/// The database region that the statement looks into.
|
||||
public internal(set) var databaseRegion = DatabaseRegion()
|
||||
|
||||
/// If true, the database schema cache gets invalidated after this statement
|
||||
/// is executed.
|
||||
/// is executed (reported by `sqlite3_set_authorizer`).
|
||||
private(set) var invalidatesDatabaseSchemaCache = false
|
||||
|
||||
/// The eventual effect of transactions, as reported by `sqlite3_set_authorizer`.
|
||||
private(set) var transactionEffect: TransactionEffect?
|
||||
private(set) var databaseEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// The effects on the database (reported by `sqlite3_set_authorizer`).
|
||||
private(set) var authorizerEventKinds: [DatabaseEventKind] = []
|
||||
|
||||
/// Returns true if and only if the prepared statement makes no direct
|
||||
/// changes to the content of the database file.
|
||||
@@ -58,6 +77,11 @@ public final class Statement {
|
||||
sqlite3_stmt_readonly(sqliteStatement) != 0
|
||||
}
|
||||
|
||||
/// Returns whether the statement deletes some rows
|
||||
var isDeleteStatement: Bool {
|
||||
authorizerEventKinds.contains(where: \.isDelete)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
unowned let database: Database
|
||||
|
||||
@@ -83,7 +107,7 @@ public final class Statement {
|
||||
database: Database,
|
||||
statementStart: UnsafePointer<Int8>,
|
||||
statementEnd: UnsafeMutablePointer<UnsafePointer<Int8>?>,
|
||||
prepFlags: Int32) throws
|
||||
prepFlags: CUnsignedInt) throws
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(database)
|
||||
|
||||
@@ -92,16 +116,16 @@ public final class Statement {
|
||||
authorizer.reset()
|
||||
|
||||
var sqliteStatement: SQLiteStatement? = nil
|
||||
let code: Int32
|
||||
let code: CInt
|
||||
// sqlite3_prepare_v3 was introduced in SQLite 3.20.0 http://www.sqlite.org/changes.html#version_3_20
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
database.sqliteConnection, statementStart, -1, prepFlags,
|
||||
&sqliteStatement, statementEnd)
|
||||
#else
|
||||
if #available(iOS 12.0, OSX 10.14, tvOS 12.0, watchOS 5.0, *) {
|
||||
code = sqlite3_prepare_v3(
|
||||
database.sqliteConnection, statementStart, -1, UInt32(bitPattern: prepFlags),
|
||||
database.sqliteConnection, statementStart, -1, prepFlags,
|
||||
&sqliteStatement, statementEnd)
|
||||
} else {
|
||||
code = sqlite3_prepare_v2(database.sqliteConnection, statementStart, -1, &sqliteStatement, statementEnd)
|
||||
@@ -115,16 +139,16 @@ public final class Statement {
|
||||
sql: String(cString: statementStart))
|
||||
}
|
||||
|
||||
guard let statement = sqliteStatement else {
|
||||
guard let sqliteStatement else {
|
||||
return nil
|
||||
}
|
||||
|
||||
self.database = database
|
||||
self.sqliteStatement = statement
|
||||
self.sqliteStatement = sqliteStatement
|
||||
self.databaseRegion = authorizer.selectedRegion
|
||||
self.invalidatesDatabaseSchemaCache = authorizer.invalidatesDatabaseSchemaCache
|
||||
self.transactionEffect = authorizer.transactionEffect
|
||||
self.databaseEventKinds = authorizer.databaseEventKinds
|
||||
self.authorizerEventKinds = authorizer.databaseEventKinds
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -143,7 +167,7 @@ public final class Statement {
|
||||
|
||||
// Returns ["id", nil", "name"] for "INSERT INTO table VALUES (:id, ?, :name)"
|
||||
fileprivate lazy var sqliteArgumentNames: [String?] = {
|
||||
(0..<Int32(self.sqliteArgumentCount)).map {
|
||||
(0..<CInt(self.sqliteArgumentCount)).map {
|
||||
guard let cString = sqlite3_bind_parameter_name(self.sqliteStatement, $0 + 1) else {
|
||||
return nil
|
||||
}
|
||||
@@ -211,7 +235,7 @@ public final class Statement {
|
||||
clearBindings()
|
||||
|
||||
var valuesIterator = arguments.values.makeIterator()
|
||||
for (index, argumentName) in zip(Int32(1)..., sqliteArgumentNames) {
|
||||
for (index, argumentName) in zip(CInt(1)..., sqliteArgumentNames) {
|
||||
if let argumentName = argumentName, let value = arguments.namedValues[argumentName] {
|
||||
bind(value, at: index)
|
||||
} else if let value = valuesIterator.next() {
|
||||
@@ -244,13 +268,13 @@ public final class Statement {
|
||||
argumentsNeedValidation = false
|
||||
try reset()
|
||||
clearBindings()
|
||||
for (index, dbValue) in zip(Int32(1)..., bindings) {
|
||||
for (index, dbValue) in zip(CInt(1)..., bindings) {
|
||||
bind(dbValue, at: index)
|
||||
}
|
||||
}
|
||||
|
||||
// 1-based index
|
||||
func bind<T: StatementBinding>(_ value: T, at index: CInt) {
|
||||
func bind(_ value: some StatementBinding, at index: CInt) {
|
||||
let code = value.bind(to: sqliteStatement, at: index)
|
||||
|
||||
// It looks like sqlite3_bind_xxx() functions do not access the file system.
|
||||
@@ -358,12 +382,6 @@ public final class Statement {
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, deprecated, renamed: "Statement")
|
||||
public typealias SelectStatement = Statement
|
||||
|
||||
@available(*, deprecated, renamed: "Statement")
|
||||
public typealias UpdateStatement = Statement
|
||||
|
||||
extension Statement: CustomStringConvertible {
|
||||
public var description: String {
|
||||
SchedulingWatchdog.allows(database) ? sql : "Statement"
|
||||
@@ -402,15 +420,34 @@ public protocol _DatabaseCursor: Cursor {
|
||||
/// Must be initialized to false.
|
||||
var _isDone: Bool { get set }
|
||||
|
||||
/// The statement iterated by the cursor
|
||||
var _statement: Statement { get }
|
||||
|
||||
/// Called after one successful call to `sqlite3_step()`. Returns the
|
||||
/// element for the current statement step.
|
||||
func _element(sqliteStatement: SQLiteStatement) throws -> Element
|
||||
}
|
||||
|
||||
/// A protocol for cursors that iterate a database statement.
|
||||
public protocol DatabaseCursor: _DatabaseCursor {
|
||||
/// The statement iterated by the cursor
|
||||
var statement: Statement { get }
|
||||
public protocol DatabaseCursor: _DatabaseCursor { }
|
||||
|
||||
// Read-only access to statement information. We don't want the user to modify
|
||||
// a statement through a cursor, in case this would mess with the cursor state.
|
||||
extension DatabaseCursor {
|
||||
/// The SQL query
|
||||
public var sql: String { _statement.sql }
|
||||
|
||||
/// The SQL statement arguments.
|
||||
public var arguments: StatementArguments { _statement.arguments }
|
||||
|
||||
/// The column names, ordered from left to right.
|
||||
public var columnNames: [String] { _statement.columnNames }
|
||||
|
||||
/// The number of columns in the resulting rows.
|
||||
public var columnCount: Int { _statement.columnCount }
|
||||
|
||||
/// The database region that the cursor looks into.
|
||||
public var databaseRegion: DatabaseRegion { _statement.databaseRegion }
|
||||
}
|
||||
|
||||
extension DatabaseCursor {
|
||||
@@ -419,7 +456,7 @@ extension DatabaseCursor {
|
||||
if _isDone {
|
||||
return nil
|
||||
}
|
||||
if let element = try statement.step(_element) {
|
||||
if let element = try _statement.step(_element) {
|
||||
return element
|
||||
}
|
||||
_isDone = true
|
||||
@@ -431,7 +468,9 @@ extension DatabaseCursor {
|
||||
@inlinable
|
||||
public func forEach(_ body: (Element) throws -> Void) throws {
|
||||
if _isDone { return }
|
||||
try statement.forEachStep { try body(_element(sqliteStatement: $0)) }
|
||||
try _statement.forEachStep {
|
||||
try body(_element(sqliteStatement: $0))
|
||||
}
|
||||
_isDone = true
|
||||
}
|
||||
}
|
||||
@@ -448,12 +487,12 @@ extension DatabaseCursor {
|
||||
/// }
|
||||
final class StatementCursor: DatabaseCursor {
|
||||
typealias Element = Void
|
||||
let statement: Statement
|
||||
let _statement: Statement
|
||||
var _isDone = false
|
||||
|
||||
// Use Statement.makeCursor() instead
|
||||
init(statement: Statement, arguments: StatementArguments? = nil) throws {
|
||||
self.statement = statement
|
||||
self._statement = statement
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
@@ -462,7 +501,7 @@ final class StatementCursor: DatabaseCursor {
|
||||
deinit {
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? statement.reset()
|
||||
try? _statement.reset()
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@@ -473,7 +512,7 @@ final class StatementCursor: DatabaseCursor {
|
||||
|
||||
extension Statement {
|
||||
var releasesDatabaseLock: Bool {
|
||||
guard let transactionEffect = transactionEffect else {
|
||||
guard let transactionEffect else {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -584,7 +623,7 @@ public protocol StatementBinding {
|
||||
/// .filter(sql: "team = :team", arguments: ["team": "Blue"])
|
||||
/// .filter(sql: "score > ?", arguments: [1000])
|
||||
/// .fetchAll(db)
|
||||
public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
public struct StatementArguments: CustomStringConvertible, Hashable,
|
||||
ExpressibleByArrayLiteral, ExpressibleByDictionaryLiteral
|
||||
{
|
||||
private(set) var values: [DatabaseValue]
|
||||
@@ -607,12 +646,12 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
|
||||
/// Creates statement arguments from a sequence of optional values.
|
||||
///
|
||||
/// let values: [DatabaseValueConvertible?] = ["foo", 1, nil]
|
||||
/// let values: [(any DatabaseValueConvertible)?] = ["foo", 1, nil]
|
||||
/// db.execute(sql: "INSERT ... (?,?,?)", arguments: StatementArguments(values))
|
||||
///
|
||||
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element == DatabaseValueConvertible? {
|
||||
public init(_ sequence: some Sequence<(any DatabaseValueConvertible)?>) {
|
||||
values = sequence.map { $0?.databaseValue ?? .null }
|
||||
namedValues = .init()
|
||||
}
|
||||
@@ -624,7 +663,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
///
|
||||
/// - parameter sequence: A sequence of DatabaseValueConvertible values.
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence: Swift.Sequence>(_ sequence: Sequence) where Sequence.Element: DatabaseValueConvertible {
|
||||
public init(_ sequence: some Sequence<some DatabaseValueConvertible>) {
|
||||
values = sequence.map(\.databaseValue)
|
||||
namedValues = .init()
|
||||
}
|
||||
@@ -655,12 +694,12 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
/// Creates statement arguments from a sequence of (key, value) dictionary,
|
||||
/// such as a dictionary.
|
||||
///
|
||||
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
|
||||
/// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"]
|
||||
/// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
|
||||
///
|
||||
/// - parameter sequence: A sequence of (key, value) pairs
|
||||
/// - returns: A StatementArguments.
|
||||
public init(_ dictionary: [String: DatabaseValueConvertible?]) {
|
||||
public init(_ dictionary: [String: (any DatabaseValueConvertible)?]) {
|
||||
namedValues = dictionary.mapValues { $0?.databaseValue ?? .null }
|
||||
values = .init()
|
||||
}
|
||||
@@ -668,14 +707,12 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
/// Creates statement arguments from a sequence of (key, value) pairs, such
|
||||
/// as a dictionary.
|
||||
///
|
||||
/// let values: [String: DatabaseValueConvertible?] = ["firstName": nil, "lastName": "Miller"]
|
||||
/// let values: [String: (any DatabaseValueConvertible)?] = ["firstName": nil, "lastName": "Miller"]
|
||||
/// db.execute(sql: "INSERT ... (:firstName, :lastName)", arguments: StatementArguments(values))
|
||||
///
|
||||
/// - parameter sequence: A sequence of (key, value) pairs
|
||||
/// - returns: A StatementArguments.
|
||||
public init<Sequence>(_ sequence: Sequence)
|
||||
where Sequence: Swift.Sequence, Sequence.Element == (String, DatabaseValueConvertible?)
|
||||
{
|
||||
public init(_ sequence: some Sequence<(String, (any DatabaseValueConvertible)?)>) {
|
||||
namedValues = .init(minimumCapacity: sequence.underestimatedCount)
|
||||
for (key, value) in sequence {
|
||||
namedValues[key] = value?.databaseValue ?? .null
|
||||
@@ -691,7 +728,7 @@ public struct StatementArguments: CustomStringConvertible, Equatable,
|
||||
/// - parameter dictionary: A dictionary.
|
||||
/// - returns: A StatementArguments.
|
||||
public init?(_ dictionary: [AnyHashable: Any]) {
|
||||
var initDictionary = [String: DatabaseValueConvertible?]()
|
||||
var initDictionary = [String: (any DatabaseValueConvertible)?]()
|
||||
for (key, value) in dictionary {
|
||||
guard let columnName = key as? String else {
|
||||
return nil
|
||||
@@ -910,7 +947,7 @@ extension StatementArguments {
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name, score) VALUES (?, ?)"
|
||||
/// arguments: arguments)
|
||||
public init(arrayLiteral elements: DatabaseValueConvertible?...) {
|
||||
public init(arrayLiteral elements: (any DatabaseValueConvertible)?...) {
|
||||
self.init(elements)
|
||||
}
|
||||
}
|
||||
@@ -923,7 +960,7 @@ extension StatementArguments {
|
||||
/// try db.execute(
|
||||
/// sql: "INSERT INTO player (name, score) VALUES (:name, :score)"
|
||||
/// arguments: arguments)
|
||||
public init(dictionaryLiteral elements: (String, DatabaseValueConvertible?)...) {
|
||||
public init(dictionaryLiteral elements: (String, (any DatabaseValueConvertible)?)...) {
|
||||
self.init(elements)
|
||||
}
|
||||
}
|
||||
@@ -933,11 +970,11 @@ extension StatementArguments {
|
||||
/// :nodoc:
|
||||
public var description: String {
|
||||
let valuesDescriptions = values.map(\.description)
|
||||
let namedValuesDescriptions = namedValues.map { (key, value) -> String in
|
||||
let namedValuesDescriptions = namedValues.map { (key, value) in
|
||||
"\(String(reflecting: key)): \(value)"
|
||||
}
|
||||
return "[" + (namedValuesDescriptions + valuesDescriptions).joined(separator: ", ") + "]"
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments: GRDBSendable { }
|
||||
extension StatementArguments: Sendable { }
|
||||
@@ -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
|
||||
@@ -152,19 +174,6 @@ final class StatementAuthorizer {
|
||||
if 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 +181,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 +195,7 @@ final class StatementAuthorizer {
|
||||
}
|
||||
|
||||
private struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible {
|
||||
let rawValue: Int32
|
||||
let rawValue: CInt
|
||||
|
||||
var description: String {
|
||||
switch rawValue {
|
||||
|
||||
@@ -19,27 +19,53 @@
|
||||
/// }
|
||||
/// }
|
||||
public protocol StatementColumnConvertible {
|
||||
|
||||
/// Initializes a value from a raw SQLite statement pointer, if possible.
|
||||
/// Creates a value from a raw SQLite statement pointer, if possible.
|
||||
///
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
/// This method can be called with a NULL database value.
|
||||
///
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
/// init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
/// self = sqlite3_column_int64(sqliteStatement, index)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// This initializer is never called for NULL database values. Just return
|
||||
/// `nil` for failed conversions: GRDB will interpret a nil result as a
|
||||
/// decoding failure.
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/column_blob.html> for more information.
|
||||
/// - warning: Do not customize the default implementation.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
init?(sqliteStatement: SQLiteStatement, index: Int32)
|
||||
/// - returns: A decoded value, or, if decoding is impossible, nil.
|
||||
static func fromStatement(
|
||||
_ sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: CInt)
|
||||
-> Self?
|
||||
|
||||
/// Creates a value from a raw SQLite statement pointer, if possible.
|
||||
///
|
||||
/// For example, here is the how Int64 adopts StatementColumnConvertible:
|
||||
///
|
||||
/// extension Int64: StatementColumnConvertible {
|
||||
/// init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
/// self = sqlite3_column_int64(sqliteStatement, index)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/column_blob.html> for more information.
|
||||
///
|
||||
/// - precondition: This initializer must not be called with NULL database
|
||||
/// values.
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
/// - returns: A decoded value, or, if decoding is impossible, nil.
|
||||
init?(sqliteStatement: SQLiteStatement, index: CInt)
|
||||
}
|
||||
|
||||
extension StatementColumnConvertible {
|
||||
// `Optional` overrides this default behavior.
|
||||
/// Default implementation fails on decoding NULL.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
return self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Conversions
|
||||
@@ -48,7 +74,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
@usableFromInline
|
||||
/* private */ static func _valueMismatch(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
atUncheckedIndex index: CInt,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Never
|
||||
{
|
||||
@@ -59,22 +85,6 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
context: context())
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
static func fastDecode(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self
|
||||
{
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL,
|
||||
let value = self.init(sqliteStatement: sqliteStatement, index: index)
|
||||
else {
|
||||
try _valueMismatch(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context())
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
static func fastDecode(
|
||||
@@ -85,7 +95,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try fastDecode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
atUncheckedIndex: CInt(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
@@ -94,21 +104,20 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(
|
||||
static func fastDecode(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
atUncheckedIndex index: CInt,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
throws -> Self?
|
||||
throws -> Self
|
||||
{
|
||||
if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
return nil
|
||||
}
|
||||
guard let value = self.init(sqliteStatement: sqliteStatement, index: index) else {
|
||||
if let value = fromStatement(sqliteStatement, atUncheckedIndex: index) {
|
||||
return value
|
||||
} else {
|
||||
try _valueMismatch(fromStatement: sqliteStatement, atUncheckedIndex: index, context: context())
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
// Support for Decodable
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
static func fastDecodeIfPresent(
|
||||
@@ -116,14 +125,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
atUncheckedIndex index: Int)
|
||||
throws -> Self?
|
||||
{
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try fastDecodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
return try row.fastDecodeIfPresent(Self.self, atUncheckedIndex: index)
|
||||
try Optional<Self>.fastDecode(fromRow: row, atUncheckedIndex: index)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,16 +144,17 @@ public final class FastDatabaseValueCursor<Value>: DatabaseCursor
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
public typealias Element = Value
|
||||
public let statement: Statement
|
||||
/// :nodoc:
|
||||
public let _statement: Statement
|
||||
/// :nodoc:
|
||||
public var _isDone = false
|
||||
@usableFromInline let columnIndex: Int32
|
||||
@usableFromInline let columnIndex: CInt
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
self._statement = statement
|
||||
if let adapter = adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
columnIndex = try CInt(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
columnIndex = 0
|
||||
}
|
||||
@@ -163,66 +166,16 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
deinit {
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? statement.reset()
|
||||
try? _statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@inlinable
|
||||
public func _element(sqliteStatement: SQLiteStatement) -> Value {
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
try! Value.fastDecode(
|
||||
public func _element(sqliteStatement: SQLiteStatement) throws -> Value {
|
||||
try Value.fastDecode(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: columnIndex,
|
||||
context: RowDecodingContext(statement: statement, index: Int(columnIndex)))
|
||||
}
|
||||
}
|
||||
|
||||
/// A cursor of optional database values extracted from a single column.
|
||||
/// For example:
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let emails: FastNullableDatabaseValueCursor<String> =
|
||||
/// try Optional<String>.fetchCursor(db, sql: "SELECT email FROM player")
|
||||
/// while let email = emails.next() { // String?
|
||||
/// print(email ?? "<NULL>")
|
||||
/// }
|
||||
/// }
|
||||
public final class FastNullableDatabaseValueCursor<Value>: DatabaseCursor
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
public typealias Element = Value?
|
||||
public let statement: Statement
|
||||
/// :nodoc:
|
||||
public var _isDone = false
|
||||
@usableFromInline let columnIndex: Int32
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws {
|
||||
self.statement = statement
|
||||
if let adapter = adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
columnIndex = try Int32(adapter.baseColumnIndex(atIndex: 0, layout: statement))
|
||||
} else {
|
||||
columnIndex = 0
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.reset(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Statement reset fails when sqlite3_step has previously failed.
|
||||
// Just ignore reset error.
|
||||
try? statement.reset()
|
||||
}
|
||||
|
||||
/// :nodoc:
|
||||
@inlinable
|
||||
public func _element(sqliteStatement: SQLiteStatement) -> Value? {
|
||||
// TODO GRDB6: don't crash on decoding errors
|
||||
try! Value.fastDecodeIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: columnIndex,
|
||||
context: RowDecodingContext(statement: statement, index: Int(columnIndex)))
|
||||
context: RowDecodingContext(statement: _statement, index: Int(columnIndex)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -257,7 +210,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
public static func fetchCursor(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
{
|
||||
try FastDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
@@ -277,7 +230,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
@@ -297,11 +250,11 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
public static func fetchOne(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Self?
|
||||
{
|
||||
// fetchOne returns nil if there is no row, or if there is a row with a null value
|
||||
let cursor = try FastNullableDatabaseValueCursor<Self>(
|
||||
// fetchOne handles both a missing row, and one row with a NULL value.
|
||||
let cursor = try FastDatabaseValueCursor<Self?>(
|
||||
statement: statement,
|
||||
arguments: arguments,
|
||||
adapter: adapter)
|
||||
@@ -324,7 +277,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Set<Self>
|
||||
{
|
||||
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
@@ -358,7 +311,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> FastDatabaseValueCursor<Self>
|
||||
{
|
||||
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
@@ -379,7 +332,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> [Self]
|
||||
{
|
||||
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
@@ -400,7 +353,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible {
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Self?
|
||||
{
|
||||
try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
@@ -423,7 +376,7 @@ extension DatabaseValueConvertible where Self: StatementColumnConvertible & Hash
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
adapter: (any RowAdapter)? = nil)
|
||||
throws -> Set<Self>
|
||||
{
|
||||
try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
@@ -513,7 +466,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
|
||||
/// A cursor over fetched values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String
|
||||
/// while let string = try strings.next() { // String
|
||||
/// ...
|
||||
@@ -533,7 +486,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
|
||||
/// An array of fetched values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let strings = try request.fetchAll(db) // [String]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -548,7 +501,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -562,7 +515,7 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementColumnConvertible & Hashable {
|
||||
/// A set of fetched values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String
|
||||
/// let request: some FetchRequest<String> = ...
|
||||
/// let strings = try request.fetchSet(db) // Set<String>
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
@@ -572,303 +525,3 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & StatementCol
|
||||
try RowDecoder.fetchSet(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swift's Optional comes with built-in methods that allow to fetch cursors
|
||||
/// and arrays of optional DatabaseValueConvertible:
|
||||
///
|
||||
/// try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...", arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(db, sql: "SELECT name FROM ...", arguments:...) // [String?]
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// try Optional<String>.fetchCursor(statement, arguments:...) // Cursor of String?
|
||||
/// try Optional<String>.fetchAll(statement, arguments:...) // [String?]
|
||||
///
|
||||
/// DatabaseValueConvertible is adopted by Bool, Int, String, etc.
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From Prepared Statement
|
||||
|
||||
/// Returns a cursor over optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchCursor(statement) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
try FastNullableDatabaseValueCursor(statement: statement, arguments: arguments, adapter: adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchAll(statement) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable {
|
||||
/// Returns a set of optional values fetched from a prepared statement.
|
||||
///
|
||||
/// let statement = try db.makeStatement(sql: "SELECT name FROM ...")
|
||||
/// let names = try Optional<String>.fetchSet(statement) // Set<String?>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - statement: The statement to run.
|
||||
/// - arguments: Optional statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ statement: Statement,
|
||||
arguments: StatementArguments? = nil,
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
{
|
||||
try Set(fetchCursor(statement, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From SQL
|
||||
|
||||
/// Returns a cursor over optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try Optional<String>.fetchCursor(db, sql: "SELECT name FROM ...") // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try Optional<String>.fetchAll(db, sql: "SELECT name FROM ...") // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> [Wrapped?]
|
||||
{
|
||||
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable {
|
||||
/// Returns a set of optional values fetched from an SQL query.
|
||||
///
|
||||
/// let names = try Optional<String>.fetchSet(db, sql: "SELECT name FROM ...") // Set<String?>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - sql: An SQL query.
|
||||
/// - arguments: Statement arguments.
|
||||
/// - adapter: Optional RowAdapter
|
||||
/// - returns: A set of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet(
|
||||
_ db: Database,
|
||||
sql: String,
|
||||
arguments: StatementArguments = StatementArguments(),
|
||||
adapter: RowAdapter? = nil)
|
||||
throws -> Set<Wrapped?>
|
||||
{
|
||||
try fetchSet(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible {
|
||||
|
||||
// MARK: Fetching From FetchRequest
|
||||
|
||||
/// Returns a cursor over optional values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try Optional<String>.fetchCursor(db, request) // Cursor of String?
|
||||
/// while let name = try names.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A cursor over fetched optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R)
|
||||
throws -> FastNullableDatabaseValueCursor<Wrapped>
|
||||
{
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchCursor(request.statement, adapter: request.adapter)
|
||||
}
|
||||
|
||||
/// Returns an array of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try Optional<String>.fetchAll(db, request) // [String?]
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: An array of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [Wrapped?] {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchAll(request.statement, adapter: request.adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable {
|
||||
/// Returns a set of optional values fetched from a fetch request.
|
||||
///
|
||||
/// let request = Player.select(Column("name"))
|
||||
/// let names = try Optional<String>.fetchSet(db, request) // Set<String?>
|
||||
///
|
||||
/// - parameters:
|
||||
/// - db: A database connection.
|
||||
/// - request: A FetchRequest.
|
||||
/// - returns: A set of optional values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public static func fetchSet<R: FetchRequest>(_ db: Database, _ request: R) throws -> Set<Wrapped?> {
|
||||
let request = try request.makePreparedRequest(db, forSingleResult: false)
|
||||
return try fetchSet(request.statement, adapter: request.adapter)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest
|
||||
where
|
||||
RowDecoder: _OptionalProtocol,
|
||||
RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
|
||||
// MARK: Fetching Optional values
|
||||
|
||||
/// A cursor over fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchCursor(db) // Cursor of String?
|
||||
/// while let string = try strings.next() { // String?
|
||||
/// ...
|
||||
/// }
|
||||
///
|
||||
/// If the database is modified during the cursor iteration, the remaining
|
||||
/// elements are undefined.
|
||||
///
|
||||
/// The cursor must be iterated in a protected dispatch queue.
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A cursor over fetched values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchCursor(_ db: Database) throws -> FastNullableDatabaseValueCursor<RowDecoder.Wrapped> {
|
||||
try Optional<RowDecoder.Wrapped>.fetchCursor(db, self)
|
||||
}
|
||||
|
||||
/// An array of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchAll(db) // [String?]
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An array of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchAll(_ db: Database) throws -> [RowDecoder.Wrapped?] {
|
||||
try Optional<RowDecoder.Wrapped>.fetchAll(db, self)
|
||||
}
|
||||
|
||||
/// The first fetched value.
|
||||
///
|
||||
/// The result is nil if the request returns no row, or if no value can be
|
||||
/// extracted from the first row.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches String?
|
||||
/// let string = try request.fetchOne(db) // String?
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: An optional value.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchOne(_ db: Database) throws -> RowDecoder.Wrapped? {
|
||||
try RowDecoder.Wrapped.fetchOne(db, self)
|
||||
}
|
||||
}
|
||||
|
||||
extension FetchRequest
|
||||
where
|
||||
RowDecoder: _OptionalProtocol,
|
||||
RowDecoder.Wrapped: DatabaseValueConvertible & StatementColumnConvertible & Hashable
|
||||
{
|
||||
/// A set of fetched optional values.
|
||||
///
|
||||
/// let request: ... // Some FetchRequest that fetches Optional<String>
|
||||
/// let strings = try request.fetchSet(db) // Set<String?>
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - returns: A set of values.
|
||||
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
|
||||
public func fetchSet(_ db: Database) throws -> Set<RowDecoder.Wrapped?> {
|
||||
try Optional<RowDecoder.Wrapped>.fetchSet(db, self)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -33,7 +33,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,21 +43,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)
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ extension Data {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return try fastDecodeNoCopy(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
atUncheckedIndex: CInt(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
@@ -78,17 +78,17 @@ extension Data {
|
||||
|
||||
static func fastDecodeNoCopyIfPresent(
|
||||
fromStatement sqliteStatement: SQLiteStatement,
|
||||
atUncheckedIndex index: Int32,
|
||||
atUncheckedIndex index: CInt,
|
||||
context: @autoclosure () -> RowDecodingContext)
|
||||
-> Data?
|
||||
{
|
||||
guard sqlite3_column_type(sqliteStatement, Int32(index)) != SQLITE_NULL else {
|
||||
guard sqlite3_column_type(sqliteStatement, index) != SQLITE_NULL else {
|
||||
return nil
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ extension Data {
|
||||
if let sqliteStatement = row.sqliteStatement {
|
||||
return fastDecodeNoCopyIfPresent(
|
||||
fromStatement: sqliteStatement,
|
||||
atUncheckedIndex: Int32(index),
|
||||
atUncheckedIndex: CInt(index),
|
||||
context: RowDecodingContext(row: row, key: .columnIndex(index)))
|
||||
}
|
||||
// Support for fast decoding from adapted rows
|
||||
|
||||
@@ -71,17 +71,17 @@ 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)
|
||||
|
||||
@@ -120,7 +120,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))
|
||||
|
||||
@@ -28,7 +28,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))
|
||||
|
||||
@@ -51,7 +51,7 @@ extension UUID: DatabaseValueConvertible {
|
||||
extension UUID: StatementColumnConvertible {
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
switch sqlite3_column_type(sqliteStatement, index) {
|
||||
case SQLITE_TEXT:
|
||||
let string = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
|
||||
@@ -2,7 +2,7 @@ import Foundation
|
||||
|
||||
private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
|
||||
let dbValue: DatabaseValue
|
||||
let codingPath: [CodingKey]
|
||||
let codingPath: [any CodingKey]
|
||||
|
||||
/// Decodes a null value.
|
||||
///
|
||||
@@ -153,7 +153,7 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
|
||||
|
||||
private struct DatabaseValueDecoder: Decoder {
|
||||
let dbValue: DatabaseValue
|
||||
let codingPath: [CodingKey]
|
||||
let codingPath: [any CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { [:] }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
|
||||
|
||||
@@ -3,7 +3,7 @@ import Foundation
|
||||
private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
|
||||
let encode: (DatabaseValue) -> Void
|
||||
|
||||
var codingPath: [CodingKey] { [] }
|
||||
var codingPath: [any CodingKey] { [] }
|
||||
|
||||
/// Encodes a null value.
|
||||
///
|
||||
@@ -37,7 +37,7 @@ private struct DatabaseValueEncodingContainer: SingleValueEncodingContainer {
|
||||
/// - throws: `EncodingError.invalidValue` if the given value is invalid in the current context for this format.
|
||||
/// - precondition: May not be called after a previous `self.encode(_:)` call.
|
||||
mutating func encode<T>(_ value: T) throws where T: Encodable {
|
||||
if let dbValueConvertible = value as? DatabaseValueConvertible {
|
||||
if let dbValueConvertible = value as? any DatabaseValueConvertible {
|
||||
// Prefer DatabaseValueConvertible encoding over Decodable.
|
||||
// This allows us to encode Date as String, for example.
|
||||
encode(dbValueConvertible.databaseValue)
|
||||
@@ -57,7 +57,7 @@ private class DatabaseValueEncoder: Encoder {
|
||||
|
||||
/// The path of coding keys taken to get to this point in encoding.
|
||||
/// A `nil` value indicates an unkeyed container.
|
||||
var codingPath: [CodingKey] { [] }
|
||||
var codingPath: [any CodingKey] { [] }
|
||||
|
||||
/// Any contextual information set by the user for encoding.
|
||||
var userInfo: [CodingUserInfoKey: Any] = [:]
|
||||
@@ -119,10 +119,8 @@ private class DatabaseValueEncoder: Encoder {
|
||||
encoder.dataEncodingStrategy = .base64
|
||||
encoder.dateEncodingStrategy = .millisecondsSince1970
|
||||
encoder.nonConformingFloatEncodingStrategy = .throw
|
||||
if #available(watchOS 4.0, OSX 10.13, iOS 11.0, tvOS 11.0, *) {
|
||||
// guarantee some stability in order to ease value comparison
|
||||
encoder.outputFormatting = .sortedKeys
|
||||
}
|
||||
// guarantee some stability in order to ease value comparison
|
||||
encoder.outputFormatting = .sortedKeys
|
||||
let jsonData = try encoder.encode(value)
|
||||
|
||||
// Store JSON String in the database for easier debugging and
|
||||
|
||||
@@ -10,6 +10,8 @@ extension SQLOrderingTerm where Self: RawRepresentable, Self.RawValue: SQLOrderi
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLSpecificExpressible where Self: RawRepresentable, Self.RawValue: SQLSpecificExpressible { }
|
||||
|
||||
extension SQLExpressible where Self: RawRepresentable, Self.RawValue: SQLExpressible {
|
||||
/// Returns the raw value as an SQL expression.
|
||||
public var sqlExpression: SQLExpression {
|
||||
@@ -23,6 +25,30 @@ extension StatementBinding where Self: RawRepresentable, Self.RawValue: Statemen
|
||||
}
|
||||
}
|
||||
|
||||
/// `StatementColumnConvertible` is free for `RawRepresentable` types whose raw
|
||||
/// value is itself `StatementColumnConvertible`.
|
||||
///
|
||||
/// // If the RawValue adopts StatementColumnConvertible...
|
||||
/// enum Color : Int {
|
||||
/// case red
|
||||
/// case white
|
||||
/// case rose
|
||||
/// }
|
||||
///
|
||||
/// // ... then the RawRepresentable type can freely
|
||||
/// // adopt StatementColumnConvertible:
|
||||
/// extension Color: StatementColumnConvertible { }
|
||||
extension StatementColumnConvertible where Self: RawRepresentable, Self.RawValue: StatementColumnConvertible {
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
guard let rawValue = RawValue(sqliteStatement: sqliteStatement, index: index) else {
|
||||
return nil
|
||||
}
|
||||
self.init(rawValue: rawValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// `DatabaseValueConvertible` is free for `RawRepresentable` types whose raw
|
||||
/// value is itself `DatabaseValueConvertible`.
|
||||
///
|
||||
|
||||
@@ -2,7 +2,7 @@ struct JSONRequiredError: Error { }
|
||||
|
||||
/// The encoder that always ends up with a JSONRequiredError
|
||||
struct JSONRequiredEncoder: Encoder {
|
||||
var codingPath: [CodingKey]
|
||||
var codingPath: [any CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
|
||||
|
||||
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey {
|
||||
@@ -15,7 +15,7 @@ struct JSONRequiredEncoder: Encoder {
|
||||
func singleValueContainer() -> SingleValueEncodingContainer { self }
|
||||
|
||||
struct KeyedContainer<KeyType: CodingKey>: KeyedEncodingContainerProtocol {
|
||||
var codingPath: [CodingKey]
|
||||
var codingPath: [any CodingKey]
|
||||
var userInfo: [CodingUserInfoKey: Any] { Record.databaseEncodingUserInfo }
|
||||
|
||||
// swiftlint:disable comma
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
extension Optional: StatementBinding where Wrapped: StatementBinding {
|
||||
public func bind(to sqliteStatement: SQLiteStatement, at index: CInt) -> CInt {
|
||||
switch self {
|
||||
case .none:
|
||||
return sqlite3_bind_null(sqliteStatement, index)
|
||||
case let .some(value):
|
||||
return value.bind(to: sqliteStatement, at: index)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional: SQLExpressible where Wrapped: SQLExpressible {
|
||||
public var sqlExpression: SQLExpression {
|
||||
switch self {
|
||||
case .none:
|
||||
return .null
|
||||
case let .some(value):
|
||||
return value.sqlExpression
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional: SQLOrderingTerm where Wrapped: SQLOrderingTerm {
|
||||
public var sqlOrdering: SQLOrdering {
|
||||
switch self {
|
||||
case .none:
|
||||
return .expression(.null)
|
||||
case let .some(value):
|
||||
return value.sqlOrdering
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional: SQLSelectable where Wrapped: SQLSelectable {
|
||||
public var sqlSelection: SQLSelection {
|
||||
switch self {
|
||||
case .none:
|
||||
return .expression(.null)
|
||||
case let .some(value):
|
||||
return value.sqlSelection
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional: SQLSpecificExpressible where Wrapped: SQLSpecificExpressible { }
|
||||
|
||||
extension Optional: DatabaseValueConvertible where Wrapped: DatabaseValueConvertible {
|
||||
public var databaseValue: DatabaseValue {
|
||||
switch self {
|
||||
case .none:
|
||||
return .null
|
||||
case let .some(value):
|
||||
return value.databaseValue
|
||||
}
|
||||
}
|
||||
|
||||
public static func fromMissingColumn() -> Self? {
|
||||
.some(.none) // success
|
||||
}
|
||||
|
||||
public static func fromDatabaseValue(_ dbValue: DatabaseValue) -> Self? {
|
||||
if let value = Wrapped.fromDatabaseValue(dbValue) {
|
||||
// Valid value
|
||||
return value
|
||||
} else if dbValue.isNull {
|
||||
// NULL
|
||||
return .some(.none)
|
||||
} else {
|
||||
// Invalid value
|
||||
return .none
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Optional: StatementColumnConvertible where Wrapped: StatementColumnConvertible {
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public static func fromStatement(_ sqliteStatement: SQLiteStatement, atUncheckedIndex index: CInt) -> Self? {
|
||||
if let value = Wrapped.fromStatement(sqliteStatement, atUncheckedIndex: index) {
|
||||
// Valid value
|
||||
return value
|
||||
} else if sqlite3_column_type(sqliteStatement, index) == SQLITE_NULL {
|
||||
// NULL
|
||||
return .some(.none)
|
||||
} else {
|
||||
// Invalid value
|
||||
return .none
|
||||
}
|
||||
}
|
||||
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
guard let value = Wrapped(sqliteStatement: sqliteStatement, index: index) else {
|
||||
return nil
|
||||
}
|
||||
self = .some(value)
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ extension Bool: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
self = sqlite3_column_int64(sqliteStatement, index) != 0
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ extension Int: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = Int(exactly: int64) else { return nil }
|
||||
self = v
|
||||
@@ -131,7 +131,7 @@ extension Int8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = Int8(exactly: int64) else { return nil }
|
||||
self = v
|
||||
@@ -162,7 +162,7 @@ extension Int16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = Int16(exactly: int64) else { return nil }
|
||||
self = v
|
||||
@@ -193,7 +193,7 @@ extension Int32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = Int32(exactly: int64) else { return nil }
|
||||
self = v
|
||||
@@ -222,7 +222,7 @@ extension Int64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
self = sqlite3_column_int64(sqliteStatement, index)
|
||||
}
|
||||
|
||||
@@ -260,7 +260,7 @@ extension UInt: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = UInt(exactly: int64) else { return nil }
|
||||
self = v
|
||||
@@ -291,7 +291,7 @@ extension UInt8: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = UInt8(exactly: int64) else { return nil }
|
||||
self = v
|
||||
@@ -322,7 +322,7 @@ extension UInt16: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = UInt16(exactly: int64) else { return nil }
|
||||
self = v
|
||||
@@ -353,7 +353,7 @@ extension UInt32: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = UInt32(exactly: int64) else { return nil }
|
||||
self = v
|
||||
@@ -384,7 +384,7 @@ extension UInt64: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - index: The column index.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public init?(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init?(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
let int64 = sqlite3_column_int64(sqliteStatement, index)
|
||||
guard let v = UInt64(exactly: int64) else { return nil }
|
||||
self = v
|
||||
@@ -413,7 +413,7 @@ extension Double: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
self = sqlite3_column_double(sqliteStatement, index)
|
||||
}
|
||||
|
||||
@@ -447,7 +447,7 @@ extension Float: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
self = Float(sqlite3_column_double(sqliteStatement, index))
|
||||
}
|
||||
|
||||
@@ -481,7 +481,7 @@ extension String: DatabaseValueConvertible, StatementColumnConvertible {
|
||||
/// - parameters:
|
||||
/// - sqliteStatement: A pointer to an SQLite statement.
|
||||
/// - index: The column index.
|
||||
public init(sqliteStatement: SQLiteStatement, index: Int32) {
|
||||
public init(sqliteStatement: SQLiteStatement, index: CInt) {
|
||||
self = String(cString: sqlite3_column_text(sqliteStatement, index)!)
|
||||
}
|
||||
|
||||
@@ -587,7 +587,6 @@ extension DatabaseFunction {
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedCapitalize =
|
||||
DatabaseFunction("swiftLocalizedCapitalizedString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -608,7 +607,6 @@ extension DatabaseFunction {
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedLowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedLowercase =
|
||||
DatabaseFunction("swiftLocalizedLowercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
@@ -629,7 +627,6 @@ extension DatabaseFunction {
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedUppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
@available(OSX 10.11, watchOS 3.0, *)
|
||||
public static let localizedUppercase =
|
||||
DatabaseFunction("swiftLocalizedUppercaseString", argumentCount: 1, pure: true) { dbValues in
|
||||
guard let string = String.fromDatabaseValue(dbValues[0]) else {
|
||||
|
||||
+218
-140
@@ -5,75 +5,93 @@ extension Database {
|
||||
/// Add a transaction observer, so that it gets notified of
|
||||
/// database changes.
|
||||
///
|
||||
/// This method has no effect on read-only database connections.
|
||||
///
|
||||
/// - parameter transactionObserver: A transaction observer.
|
||||
/// - parameter extent: The duration of the observation. The default is
|
||||
/// the observer lifetime (observation lasts until observer
|
||||
/// is deallocated).
|
||||
public func add(
|
||||
transactionObserver: TransactionObserver,
|
||||
transactionObserver: some TransactionObserver,
|
||||
extent: TransactionObservationExtent = .observerLifetime)
|
||||
{
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
guard let observationBroker else { return }
|
||||
|
||||
// Drop cached statements that delete, because the addition of an
|
||||
// observer may change the need for truncate optimization prevention.
|
||||
publicStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) }
|
||||
internalStatementCache.removeAll{ $0.databaseEventKinds.contains(where: \.isDelete) }
|
||||
publicStatementCache.removeAll { $0.isDeleteStatement }
|
||||
internalStatementCache.removeAll{ $0.isDeleteStatement }
|
||||
|
||||
observationBroker.add(transactionObserver: transactionObserver, extent: extent)
|
||||
}
|
||||
|
||||
/// Remove a transaction observer.
|
||||
public func remove(transactionObserver: TransactionObserver) {
|
||||
public func remove(transactionObserver: some TransactionObserver) {
|
||||
SchedulingWatchdog.preconditionValidQueue(self)
|
||||
guard let observationBroker else { return }
|
||||
|
||||
// Drop cached statements that delete, because the removal of an
|
||||
// observer may change the need for truncate optimization prevention.
|
||||
publicStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) }
|
||||
internalStatementCache.removeAll { $0.databaseEventKinds.contains(where: \.isDelete) }
|
||||
publicStatementCache.removeAll { $0.isDeleteStatement }
|
||||
internalStatementCache.removeAll { $0.isDeleteStatement }
|
||||
|
||||
observationBroker.remove(transactionObserver: transactionObserver)
|
||||
}
|
||||
|
||||
/// Registers a closure to be executed after the next or current
|
||||
/// Registers closures to be executed after the next or current
|
||||
/// transaction completion.
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// db.afterNextTransactionCommit { _ in
|
||||
/// db.afterNextTransaction { _ in
|
||||
/// print("success")
|
||||
/// }
|
||||
/// ...
|
||||
/// } // prints "success"
|
||||
/// } // prints "commit"
|
||||
///
|
||||
/// If the transaction is rollbacked, the closure is not executed.
|
||||
/// Closure are executed in a protected dispatch queue, serialized will all
|
||||
/// database updates.
|
||||
///
|
||||
/// If the transaction is committed, the closure is executed in a protected
|
||||
/// dispatch queue, serialized will all database updates.
|
||||
public func afterNextTransactionCommit(_ closure: @escaping (Database) -> Void) {
|
||||
class CommitHandler: TransactionObserver {
|
||||
let closure: (Database) -> Void
|
||||
|
||||
init(_ closure: @escaping (Database) -> Void) {
|
||||
self.closure = closure
|
||||
/// - precondition: Database is not read-only.
|
||||
/// - parameter onCommit: A closure execute on transaction commit.
|
||||
/// - parameter onRollback: A closure execute on transaction rollback.
|
||||
public func afterNextTransaction(
|
||||
onCommit: @escaping (Database) -> Void,
|
||||
onRollback: @escaping (Database) -> Void = { _ in })
|
||||
{
|
||||
class TransactionHandler: TransactionObserver {
|
||||
let onCommit: (Database) -> Void
|
||||
let onRollback: (Database) -> Void
|
||||
|
||||
init(onCommit: @escaping (Database) -> Void, onRollback: @escaping (Database) -> Void) {
|
||||
self.onCommit = onCommit
|
||||
self.onRollback = onRollback
|
||||
}
|
||||
|
||||
// Ignore individual changes and transaction rollbacks
|
||||
// Ignore changes
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool { false }
|
||||
func databaseDidChange(with event: DatabaseEvent) { }
|
||||
func databaseDidRollback(_ db: Database) { }
|
||||
|
||||
// On commit, run closure
|
||||
func databaseDidCommit(_ db: Database) {
|
||||
closure(db)
|
||||
onCommit(db)
|
||||
}
|
||||
|
||||
func databaseDidRollback(_ db: Database) {
|
||||
onRollback(db)
|
||||
}
|
||||
}
|
||||
|
||||
add(transactionObserver: CommitHandler(closure), extent: .nextTransaction)
|
||||
// We don't notify read-only transactions to transaction observers
|
||||
GRDBPrecondition(!isReadOnly, "Read-only transactions are not notified")
|
||||
|
||||
add(
|
||||
transactionObserver: TransactionHandler(onCommit: onCommit, onRollback: onRollback),
|
||||
extent: .nextTransaction)
|
||||
}
|
||||
|
||||
/// The extent of a transaction observation
|
||||
/// The extent of a transaction observation.
|
||||
///
|
||||
/// See Database.add(transactionObserver:extent:)
|
||||
/// See ``Database/add(transactionObserver:extent:)``.
|
||||
public enum TransactionObservationExtent {
|
||||
/// Observation lasts until observer is deallocated
|
||||
case observerLifetime
|
||||
@@ -160,7 +178,7 @@ extension Database {
|
||||
///
|
||||
/// try db.execute(sql: "COMMIT")
|
||||
///
|
||||
/// During the statement *execution*, SQlite tells the broker that the
|
||||
/// During the statement *execution*, SQLite tells the broker that the
|
||||
/// transaction is about to be committed through sqlite3_commit_hook. The broker
|
||||
/// invokes observer.databaseWillCommit(). If the observer throws an error, the
|
||||
/// broker asks SQLite to rollback the transaction. Otherwise, the broker lets
|
||||
@@ -169,20 +187,32 @@ extension Database {
|
||||
/// After the statement *has been executed*, the broker calls
|
||||
/// observer.databaseDidCommit().
|
||||
class DatabaseObservationBroker {
|
||||
private unowned var database: Database
|
||||
private var savepointStack = SavepointStack()
|
||||
private var transactionState: TransactionState = .none
|
||||
private unowned let database: Database
|
||||
|
||||
/// The savepoint stack allows us to hold database event notifications until
|
||||
/// all savepoints are released. The goal is to only tell transaction
|
||||
/// observers about database changes that have a chance to be committed
|
||||
/// on disk.
|
||||
private let savepointStack = SavepointStack()
|
||||
|
||||
/// Tracks the transaction completion, as reported by the
|
||||
/// `sqlite3_commit_hook` and `sqlite3_rollback_hook` callbacks.
|
||||
private var transactionCompletion = TransactionCompletion.none
|
||||
|
||||
/// The registered transaction observers.
|
||||
private var transactionObservations: [TransactionObservation] = []
|
||||
|
||||
/// The observers for an individual statement execution.
|
||||
private var statementObservations: [StatementObservation] = [] {
|
||||
didSet { observesDatabaseChanges = !statementObservations.isEmpty }
|
||||
}
|
||||
private var observesDatabaseChanges = false {
|
||||
didSet {
|
||||
if observesDatabaseChanges == oldValue { return }
|
||||
if observesDatabaseChanges {
|
||||
installUpdateHook()
|
||||
} else {
|
||||
uninstallUpdateHook()
|
||||
let isEmpty = statementObservations.isEmpty
|
||||
if isEmpty != oldValue.isEmpty {
|
||||
if isEmpty {
|
||||
// Avoid processing database changes if nobody is interested
|
||||
uninstallUpdateHook()
|
||||
} else {
|
||||
installUpdateHook()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,25 +223,26 @@ class DatabaseObservationBroker {
|
||||
|
||||
// MARK: - Transaction observers
|
||||
|
||||
func add(transactionObserver: TransactionObserver, extent: Database.TransactionObservationExtent) {
|
||||
func add(transactionObserver: some TransactionObserver, extent: Database.TransactionObservationExtent) {
|
||||
transactionObservations.append(TransactionObservation(observer: transactionObserver, extent: extent))
|
||||
}
|
||||
|
||||
func remove(transactionObserver: TransactionObserver) {
|
||||
func remove(transactionObserver: some TransactionObserver) {
|
||||
transactionObservations.removeFirst { $0.isWrapping(transactionObserver) }
|
||||
}
|
||||
|
||||
func disableUntilNextTransaction(transactionObserver: TransactionObserver) {
|
||||
/// Called from ``TransactionObserver/stopObservingDatabaseChangesUntilNextTransaction()``.
|
||||
func disableUntilNextTransaction(transactionObserver: some TransactionObserver) {
|
||||
if let observation = transactionObservations.first(where: { $0.isWrapping(transactionObserver) }) {
|
||||
observation.isDisabled = true
|
||||
statementObservations.removeFirst { $0.0 === observation }
|
||||
observation.isEnabled = false
|
||||
statementObservations.removeFirst { $0.transactionObservation === observation }
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Statement execution
|
||||
|
||||
/// Returns true if there exists some transaction observers interested in
|
||||
/// deletions in the given table.
|
||||
/// Returns true if there exists some transaction observer interested in
|
||||
/// the deletions in the given table.
|
||||
func observesDeletions(on table: String) -> Bool {
|
||||
transactionObservations.contains { observation in
|
||||
observation.observes(eventsOfKind: .delete(tableName: table))
|
||||
@@ -230,14 +261,15 @@ class DatabaseObservationBroker {
|
||||
// SchedulingWatchdog.current:
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = self
|
||||
|
||||
// Fill statementObservations with observations that are interested in
|
||||
// the kind of events performed by the statement.
|
||||
// Fill statementObservations with observations that are interested
|
||||
// in the kind of database events performed by the statement, as
|
||||
// reported by `sqlite3_set_authorizer`.
|
||||
//
|
||||
// Those statementObservations will be notified of individual changes
|
||||
// in databaseWillChange() and databaseDidChange().
|
||||
let eventKinds = statement.databaseEventKinds
|
||||
let authorizerEventKinds = statement.authorizerEventKinds
|
||||
|
||||
switch eventKinds.count {
|
||||
switch authorizerEventKinds.count {
|
||||
case 0:
|
||||
// Statement has no effect on any database table.
|
||||
//
|
||||
@@ -250,15 +282,17 @@ class DatabaseObservationBroker {
|
||||
//
|
||||
// For example, if one observes all deletions in the table T, then
|
||||
// all individual deletions of DELETE FROM T are notified:
|
||||
let eventKind = eventKinds[0]
|
||||
let eventKind = authorizerEventKinds[0]
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
guard observation.observes(eventsOfKind: eventKind) else {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
// observation will be notified of all individual events
|
||||
return (observation, DatabaseEventPredicate.true)
|
||||
// Observation will be notified of all individual events
|
||||
return StatementObservation(
|
||||
transactionObservation: observation,
|
||||
trackingEvents: .all)
|
||||
}
|
||||
default:
|
||||
// We'll execute a complex statement with side effects performed by
|
||||
@@ -270,39 +304,39 @@ class DatabaseObservationBroker {
|
||||
// by the mean of a foreign key action, then when one only observes
|
||||
// deletions in T1, one must not be notified of deletions in T2:
|
||||
statementObservations = transactionObservations.compactMap { observation in
|
||||
let observedKinds = eventKinds.filter(observation.observes)
|
||||
if observedKinds.isEmpty {
|
||||
let observedEventKinds = authorizerEventKinds.filter(observation.observes)
|
||||
if observedEventKinds.isEmpty {
|
||||
// observation is not interested
|
||||
return nil
|
||||
}
|
||||
|
||||
// observation will only be notified of individual events that
|
||||
// match one of the observed kinds.
|
||||
return (
|
||||
observation,
|
||||
DatabaseEventPredicate.matching(
|
||||
observedKinds: observedKinds,
|
||||
advertisedKinds: eventKinds))
|
||||
// Observation will only be notified of individual events
|
||||
// it is interested into.
|
||||
return StatementObservation(
|
||||
transactionObservation: observation,
|
||||
trackingEvents: .matching(
|
||||
observedEventKinds: observedEventKinds,
|
||||
authorizerEventKinds: authorizerEventKinds))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
transactionState = .none
|
||||
transactionCompletion = .none
|
||||
}
|
||||
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
/// a transaction.
|
||||
/// May throw the user-provided cancelled commit error, if a transaction
|
||||
/// observer has cancelled a transaction.
|
||||
func statementDidFail(_ statement: Statement) throws {
|
||||
// Undo statementWillExecute
|
||||
statementObservations = []
|
||||
SchedulingWatchdog.current!.databaseObservationBroker = nil
|
||||
|
||||
// Reset transactionState before databaseDidRollback eventually
|
||||
// Reset transactionCompletion before databaseDidRollback eventually
|
||||
// executes other statements.
|
||||
let transactionState = self.transactionState
|
||||
self.transactionState = .none
|
||||
let transactionCompletion = self.transactionCompletion
|
||||
self.transactionCompletion = .none
|
||||
|
||||
switch transactionState {
|
||||
switch transactionCompletion {
|
||||
case .rollback:
|
||||
// Don't notify observers because we're in a failed implicit
|
||||
// transaction here (like an INSERT which fails with
|
||||
@@ -316,8 +350,9 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
/// May throw a cancelled commit error, if a transaction observer cancels
|
||||
/// an empty transaction.
|
||||
/// May throw the user-provided cancelled commit error, if the statement
|
||||
/// commits an empty transaction, and a transaction observer cancels this
|
||||
/// empty transaction.
|
||||
func statementDidExecute(_ statement: Statement) throws {
|
||||
// Undo statementWillExecute
|
||||
if transactionObservations.isEmpty == false {
|
||||
@@ -332,7 +367,7 @@ class DatabaseObservationBroker {
|
||||
break
|
||||
|
||||
case .commitTransaction: // 1. A COMMIT statement has been executed
|
||||
if case .none = self.transactionState { // 2. sqlite3_commit_hook was not triggered
|
||||
if case .none = transactionCompletion { // 2. sqlite3_commit_hook was not called
|
||||
// 1+2 mean that an empty deferred transaction has been completed:
|
||||
//
|
||||
// BEGIN DEFERRED TRANSACTION; COMMIT
|
||||
@@ -351,7 +386,7 @@ class DatabaseObservationBroker {
|
||||
case .releaseSavepoint(let name): // 1. A RELEASE SAVEPOINT statement has been executed
|
||||
savepointStack.savepointDidRelease(name)
|
||||
|
||||
if case .none = self.transactionState, // 2. sqlite3_commit_hook was not triggered
|
||||
if case .none = transactionCompletion, // 2. sqlite3_commit_hook was not called
|
||||
!database.isInsideTransaction // 3. database is no longer inside a transaction
|
||||
{
|
||||
// 1+2+3 mean that an empty deferred transaction has been completed:
|
||||
@@ -372,12 +407,12 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
}
|
||||
|
||||
// Reset transactionState before databaseDidCommit or
|
||||
// Reset transactionCompletion before databaseDidCommit or
|
||||
// databaseDidRollback eventually execute other statements.
|
||||
let transactionState = self.transactionState
|
||||
self.transactionState = .none
|
||||
let transactionCompletion = self.transactionCompletion
|
||||
self.transactionCompletion = .none
|
||||
|
||||
switch transactionState {
|
||||
switch transactionCompletion {
|
||||
case .commit:
|
||||
databaseDidCommit()
|
||||
case .rollback:
|
||||
@@ -394,8 +429,8 @@ class DatabaseObservationBroker {
|
||||
|
||||
if savepointStack.isEmpty {
|
||||
// Notify now
|
||||
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
|
||||
observation.databaseWillChange(with: event)
|
||||
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
|
||||
statementObservation.transactionObservation.databaseWillChange(with: event)
|
||||
}
|
||||
} else {
|
||||
// Buffer
|
||||
@@ -419,8 +454,8 @@ class DatabaseObservationBroker {
|
||||
|
||||
if savepointStack.isEmpty {
|
||||
// Notify now
|
||||
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
|
||||
observation.databaseDidChange(with: event)
|
||||
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
|
||||
statementObservation.transactionObservation.databaseDidChange(with: event)
|
||||
}
|
||||
} else {
|
||||
// Buffer
|
||||
@@ -476,7 +511,7 @@ class DatabaseObservationBroker {
|
||||
//
|
||||
// For example, is the code below expected to print "did commit"?
|
||||
//
|
||||
// db.afterNextTransactionCommit { _ in print("did commit") }
|
||||
// db.afterNextTransaction { _ in print("did commit") }
|
||||
// try db.inTransaction {
|
||||
// performSomeTask(db)
|
||||
// return .commit
|
||||
@@ -511,15 +546,19 @@ class DatabaseObservationBroker {
|
||||
databaseDidEndTransaction()
|
||||
}
|
||||
|
||||
/// Remove transaction observers that have stopped observing transaction,
|
||||
/// and uninstall SQLite update hooks if there is no remaining observers.
|
||||
// Called from both databaseDidCommit() and databaseDidRollback()
|
||||
private func databaseDidEndTransaction() {
|
||||
assert(!database.isInsideTransaction)
|
||||
|
||||
// Remove transaction observations that are no longer observing, because
|
||||
// a transaction observer registered with the `.observerLifetime` extent
|
||||
// was deallocated, or because a transaction observer was registered
|
||||
// with the `.nextTransaction` extent.
|
||||
transactionObservations = transactionObservations.filter(\.isObserving)
|
||||
|
||||
// Undo disableUntilNextTransaction(transactionObserver:)
|
||||
for observation in transactionObservations {
|
||||
observation.isDisabled = false
|
||||
observation.isEnabled = true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -570,14 +609,13 @@ class DatabaseObservationBroker {
|
||||
}
|
||||
|
||||
// Now we can safely notify:
|
||||
|
||||
let eventsBuffer = savepointStack.eventsBuffer
|
||||
savepointStack.clear()
|
||||
|
||||
for (event, statementObservations) in eventsBuffer {
|
||||
assert(statementObservations.isEmpty || !database.isReadOnly, "Read-only transactions are not notified")
|
||||
for (observation, predicate) in statementObservations where predicate.evaluate(event) {
|
||||
event.send(to: observation)
|
||||
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
|
||||
event.send(to: statementObservation.transactionObservation)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -591,11 +629,11 @@ class DatabaseObservationBroker {
|
||||
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
|
||||
do {
|
||||
try broker.databaseWillCommit()
|
||||
broker.transactionState = .commit
|
||||
// Next step: statementDidExecute()
|
||||
broker.transactionCompletion = .commit
|
||||
// Next step: statementDidExecute(_:)
|
||||
return 0
|
||||
} catch {
|
||||
broker.transactionState = .cancelledCommit(error)
|
||||
broker.transactionCompletion = .cancelledCommit(error)
|
||||
// Next step: sqlite3_rollback_hook callback
|
||||
return 1
|
||||
}
|
||||
@@ -603,13 +641,13 @@ class DatabaseObservationBroker {
|
||||
|
||||
sqlite3_rollback_hook(database.sqliteConnection, { brokerPointer in
|
||||
let broker = Unmanaged<DatabaseObservationBroker>.fromOpaque(brokerPointer!).takeUnretainedValue()
|
||||
switch broker.transactionState {
|
||||
switch broker.transactionCompletion {
|
||||
case .cancelledCommit:
|
||||
// Next step: statementDidFail()
|
||||
// Next step: statementDidFail(_:)
|
||||
break
|
||||
default:
|
||||
broker.transactionState = .rollback
|
||||
// Next step: statementDidExecute()
|
||||
broker.transactionCompletion = .rollback
|
||||
// Next step: statementDidExecute(_:)
|
||||
}
|
||||
}, brokerPointer)
|
||||
}
|
||||
@@ -656,11 +694,20 @@ class DatabaseObservationBroker {
|
||||
#endif
|
||||
}
|
||||
|
||||
/// The various states of SQLite transactions
|
||||
enum TransactionState {
|
||||
/// The various SQLite transactions completions, as reported by the
|
||||
/// `sqlite3_commit_hook` and `sqlite3_rollback_hook` callbacks.
|
||||
fileprivate enum TransactionCompletion {
|
||||
/// Transaction state is unchanged.
|
||||
case none
|
||||
|
||||
/// Transaction turns committed.
|
||||
case commit
|
||||
|
||||
/// Transaction turns rollbacked.
|
||||
case rollback
|
||||
|
||||
/// Transaction turns rollbacked because a transaction observer has
|
||||
/// cancelled a commit by throwing an error.
|
||||
case cancelledCommit(Error)
|
||||
}
|
||||
}
|
||||
@@ -737,8 +784,7 @@ public protocol TransactionObserver: AnyObject {
|
||||
///
|
||||
/// **Availability Info**
|
||||
///
|
||||
/// Requires SQLite 3.13.0 +
|
||||
/// Compiled with option SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
/// Requires SQLite compiled with option SQLITE_ENABLE_PREUPDATE_HOOK.
|
||||
///
|
||||
/// As of OSX 10.11.5, and iOS 9.3.2, the built-in SQLite library
|
||||
/// does not have this enabled, so you'll need to compile your own
|
||||
@@ -800,19 +846,19 @@ extension TransactionObserver {
|
||||
final class TransactionObservation {
|
||||
let extent: Database.TransactionObservationExtent
|
||||
|
||||
// A disabled observation is not interested in individual database changes.
|
||||
// It is still interested in transactions commits & rollbacks.
|
||||
var isDisabled = false
|
||||
/// A disabled observation is not interested in individual database changes.
|
||||
/// It is still interested in transactions commits & rollbacks.
|
||||
var isEnabled = true
|
||||
|
||||
private weak var weakObserver: TransactionObserver?
|
||||
private var strongObserver: TransactionObserver?
|
||||
private var observer: TransactionObserver? { strongObserver ?? weakObserver }
|
||||
private weak var weakObserver: (any TransactionObserver)?
|
||||
private var strongObserver: (any TransactionObserver)?
|
||||
private var observer: (any TransactionObserver)? { strongObserver ?? weakObserver }
|
||||
|
||||
fileprivate var isObserving: Bool {
|
||||
observer != nil
|
||||
}
|
||||
|
||||
init(observer: TransactionObserver, extent: Database.TransactionObservationExtent) {
|
||||
init(observer: some TransactionObserver, extent: Database.TransactionObservationExtent) {
|
||||
self.extent = extent
|
||||
switch extent {
|
||||
case .observerLifetime:
|
||||
@@ -825,24 +871,23 @@ final class TransactionObservation {
|
||||
}
|
||||
}
|
||||
|
||||
func isWrapping(_ observer: TransactionObserver) -> Bool {
|
||||
func isWrapping(_ observer: some TransactionObserver) -> Bool {
|
||||
self.observer === observer
|
||||
}
|
||||
|
||||
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
|
||||
if isDisabled { return false }
|
||||
return observer?.observes(eventsOfKind: eventKind) ?? false
|
||||
observer?.observes(eventsOfKind: eventKind) ?? false
|
||||
}
|
||||
|
||||
#if SQLITE_ENABLE_PREUPDATE_HOOK
|
||||
func databaseWillChange(with event: DatabasePreUpdateEvent) {
|
||||
if isDisabled { return }
|
||||
guard isEnabled else { return }
|
||||
observer?.databaseWillChange(with: event)
|
||||
}
|
||||
#endif
|
||||
|
||||
func databaseDidChange(with event: DatabaseEvent) {
|
||||
if isDisabled { return }
|
||||
guard isEnabled else { return }
|
||||
observer?.databaseDidChange(with: event)
|
||||
}
|
||||
|
||||
@@ -859,6 +904,7 @@ final class TransactionObservation {
|
||||
// Observer must not get any further notification.
|
||||
// So we "forget" the observer before its `databaseDidCommit`
|
||||
// implementation eventually triggers another database change.
|
||||
assert(weakObserver == nil, "expected observer to be stored in strongObserver")
|
||||
strongObserver = nil
|
||||
observer.databaseDidCommit(db)
|
||||
}
|
||||
@@ -874,6 +920,7 @@ final class TransactionObservation {
|
||||
// Observer must not get any further notification.
|
||||
// So we "forget" the observer before its `databaseDidRollback`
|
||||
// implementation eventually triggers another database change.
|
||||
assert(weakObserver == nil, "expected observer to be stored in strongObserver")
|
||||
strongObserver = nil
|
||||
observer.databaseDidRollback(db)
|
||||
}
|
||||
@@ -881,7 +928,19 @@ final class TransactionObservation {
|
||||
}
|
||||
}
|
||||
|
||||
typealias StatementObservation = (TransactionObservation, DatabaseEventPredicate)
|
||||
/// The observation of one particular statement, by a particular
|
||||
/// transaction observer.
|
||||
struct StatementObservation {
|
||||
var transactionObservation: TransactionObservation
|
||||
|
||||
/// Filters database events that should be notified.
|
||||
var predicate: DatabaseEventPredicate
|
||||
|
||||
init(transactionObservation: TransactionObservation, trackingEvents predicate: DatabaseEventPredicate) {
|
||||
self.transactionObservation = transactionObservation
|
||||
self.predicate = predicate
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Database events
|
||||
|
||||
@@ -901,15 +960,15 @@ public enum DatabaseEventKind {
|
||||
var modifiedRegion: DatabaseRegion {
|
||||
switch self {
|
||||
case let .delete(tableName):
|
||||
return DatabaseRegion.fullTable(tableName)
|
||||
return DatabaseRegion(table: tableName)
|
||||
case let .insert(tableName):
|
||||
return DatabaseRegion.fullTable(tableName)
|
||||
return DatabaseRegion(table: tableName)
|
||||
case let .update(tableName, updatedColumnNames):
|
||||
return DatabaseRegion(table: tableName, columns: updatedColumnNames)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true iff this is a delete event.
|
||||
/// Returns whether this is a delete event.
|
||||
var isDelete: Bool {
|
||||
if case .delete = self {
|
||||
return true
|
||||
@@ -939,7 +998,7 @@ protocol DatabaseEventProtocol {
|
||||
public struct DatabaseEvent {
|
||||
|
||||
/// An event kind
|
||||
public enum Kind: Int32 {
|
||||
public enum Kind: CInt {
|
||||
/// SQLITE_INSERT
|
||||
case insert = 18
|
||||
|
||||
@@ -950,7 +1009,7 @@ public struct DatabaseEvent {
|
||||
case update = 23
|
||||
}
|
||||
|
||||
private let impl: DatabaseEventImpl
|
||||
private let impl: any DatabaseEventImpl
|
||||
|
||||
/// The event kind
|
||||
public let kind: Kind
|
||||
@@ -976,7 +1035,7 @@ public struct DatabaseEvent {
|
||||
impl.copy(self)
|
||||
}
|
||||
|
||||
fileprivate init(kind: Kind, rowID: Int64, impl: DatabaseEventImpl) {
|
||||
fileprivate init(kind: Kind, rowID: Int64, impl: any DatabaseEventImpl) {
|
||||
self.kind = kind
|
||||
self.rowID = rowID
|
||||
self.impl = impl
|
||||
@@ -1046,7 +1105,7 @@ private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
|
||||
public struct DatabasePreUpdateEvent {
|
||||
|
||||
/// An event kind
|
||||
public enum Kind: Int32 {
|
||||
public enum Kind: CInt {
|
||||
/// SQLITE_INSERT
|
||||
case insert = 18
|
||||
|
||||
@@ -1142,7 +1201,7 @@ public struct DatabasePreUpdateEvent {
|
||||
impl.copy(self)
|
||||
}
|
||||
|
||||
fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: DatabasePreUpdateEventImpl) {
|
||||
fileprivate init(kind: Kind, initialRowID: Int64?, finalRowID: Int64?, impl: any DatabasePreUpdateEventImpl) {
|
||||
self.kind = kind
|
||||
self.initialRowID = (kind == .update || kind == .delete ) ? initialRowID : nil
|
||||
self.finalRowID = (kind == .update || kind == .insert ) ? finalRowID : nil
|
||||
@@ -1168,7 +1227,7 @@ public struct DatabasePreUpdateEvent {
|
||||
tableNameCString: tableNameCString))
|
||||
}
|
||||
|
||||
private let impl: DatabasePreUpdateEventImpl
|
||||
private let impl: any DatabasePreUpdateEventImpl
|
||||
}
|
||||
|
||||
extension DatabasePreUpdateEvent: DatabaseEventProtocol {
|
||||
@@ -1234,7 +1293,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
|
||||
return getValue(
|
||||
connection,
|
||||
column: CInt(index),
|
||||
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
|
||||
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) in
|
||||
sqlite3_preupdate_old(connection, column, &value)
|
||||
})
|
||||
}
|
||||
@@ -1244,7 +1303,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
|
||||
return getValue(
|
||||
connection,
|
||||
column: CInt(index),
|
||||
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
|
||||
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) in
|
||||
sqlite3_preupdate_new(connection, column, &value)
|
||||
})
|
||||
}
|
||||
@@ -1298,7 +1357,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
|
||||
private func preupdate_getValues_old(_ connection: SQLiteConnection) -> [DatabaseValue]? {
|
||||
preupdate_getValues(
|
||||
connection,
|
||||
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
|
||||
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) in
|
||||
sqlite3_preupdate_old(connection, column, &value)
|
||||
})
|
||||
}
|
||||
@@ -1306,7 +1365,7 @@ private struct MetalDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
|
||||
private func preupdate_getValues_new(_ connection: SQLiteConnection) -> [DatabaseValue]? {
|
||||
preupdate_getValues(
|
||||
connection,
|
||||
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) -> CInt in
|
||||
sqlite_func: { (connection: SQLiteConnection, column: CInt, value: inout SQLiteValue? ) in
|
||||
sqlite3_preupdate_new(connection, column, &value)
|
||||
})
|
||||
}
|
||||
@@ -1329,28 +1388,47 @@ private struct CopiedDatabasePreUpdateEventImpl: DatabasePreUpdateEventImpl {
|
||||
|
||||
#endif
|
||||
|
||||
// A predicate that filters database events
|
||||
/// A predicate that filters database events reported by `sqlite3_update_hook`.
|
||||
enum DatabaseEventPredicate {
|
||||
// Yes filter
|
||||
case `true`
|
||||
// Only events that match observedKinds
|
||||
case matching(observedKinds: [DatabaseEventKind], advertisedKinds: [DatabaseEventKind])
|
||||
/// All events.
|
||||
case all
|
||||
|
||||
func evaluate(_ event: DatabaseEventProtocol) -> Bool {
|
||||
/// Filters events that match `observedEventKinds`, or are not
|
||||
///
|
||||
/// - parameter observedEventKinds: Event kinds observed by
|
||||
/// the TransactionObserver.
|
||||
/// - parameter authorizerEventKinds: Event kinds reported by the
|
||||
/// statement authorizer.
|
||||
case matching(observedEventKinds: [DatabaseEventKind], authorizerEventKinds: [DatabaseEventKind])
|
||||
|
||||
func evaluate(_ event: some DatabaseEventProtocol) -> Bool {
|
||||
switch self {
|
||||
case .true:
|
||||
case .all:
|
||||
return true
|
||||
case let .matching(observedKinds: observedKinds, advertisedKinds: advertisedKinds):
|
||||
if observedKinds.contains(where: { event.matchesKind($0) }) {
|
||||
|
||||
case let .matching(observedEventKinds: observedEventKinds, authorizerEventKinds: authorizerEventKinds):
|
||||
if observedEventKinds.contains(where: { event.matchesKind($0) }) {
|
||||
return true
|
||||
}
|
||||
if !advertisedKinds.contains(where: { event.matchesKind($0) }) {
|
||||
// FTS4 (and maybe other virtual tables) perform unadvertised
|
||||
// changes. For example, an "INSERT INTO document ..." statement
|
||||
// advertises an insertion in the `document` table, but the
|
||||
// actual change events happen in the `document_content` shadow
|
||||
// table. When such a non-advertised event happens, assume that
|
||||
// the event has to be notified.
|
||||
if !authorizerEventKinds.contains(where: { event.matchesKind($0) }) {
|
||||
// Here, `sqlite3_update_hook` emits an unexpected event, that
|
||||
// was not advertised by `sqlite3_set_authorizer` when the
|
||||
// statement was compiled:
|
||||
//
|
||||
// 1. Compile "INSERT INTO document ...": the authorizer
|
||||
// reports an insertion in the `document` table.
|
||||
// 2. Execute "INSERT INTO document ...": the update hook
|
||||
// reports an insertion in another table!
|
||||
//
|
||||
// Well, FTS4 (and maybe other virtual tables) perform such
|
||||
// unadvertised changes. Executing the "INSERT INTO document ..."
|
||||
// statement reports changes in the `document_content` shadow
|
||||
// table, not the `document` table reported when the
|
||||
// statement was compiled.
|
||||
//
|
||||
// When such a non-advertised event happens, we notify the
|
||||
// event to the transaction observer.
|
||||
//
|
||||
// See https://github.com/groue/GRDB.swift/issues/620
|
||||
return true
|
||||
}
|
||||
@@ -1372,7 +1450,7 @@ enum DatabaseEventPredicate {
|
||||
/// rollbacked.
|
||||
class SavepointStack {
|
||||
/// The buffered events (see DatabaseObservationBroker.databaseDidChange(with:))
|
||||
var eventsBuffer: [(event: DatabaseEventProtocol, statementObservations: [StatementObservation])] = []
|
||||
var eventsBuffer: [(event: any DatabaseEventProtocol, statementObservations: [StatementObservation])] = []
|
||||
|
||||
/// The savepoint stack, as an array of tuples (savepointName, index in the eventsBuffer array).
|
||||
/// Indexes let us drop rollbacked events from the event buffer.
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
|
||||
final class WALSnapshot {
|
||||
#if GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7)
|
||||
#if GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT)
|
||||
init?(_ db: Database) {
|
||||
return nil
|
||||
}
|
||||
@@ -35,33 +35,17 @@ final class WALSnapshot {
|
||||
/// error occurs.
|
||||
init?(_ db: Database) {
|
||||
var snapshot: UnsafeMutablePointer<sqlite3_snapshot>?
|
||||
let code: CInt = withUnsafeMutablePointer(to: &snapshot) {
|
||||
#if GRDBCUSTOMSQLITE
|
||||
let code = withUnsafeMutablePointer(to: &snapshot) {
|
||||
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
|
||||
#else
|
||||
// iOS 10.0 is always true because our minimum requirement is iOS 11.
|
||||
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
|
||||
return sqlite3_snapshot_get(db.sqliteConnection, "main", $0)
|
||||
} else {
|
||||
return SQLITE_ERROR
|
||||
}
|
||||
#endif
|
||||
}
|
||||
guard code == SQLITE_OK, let s = snapshot else {
|
||||
guard code == SQLITE_OK, let snapshot else {
|
||||
return nil
|
||||
}
|
||||
self.snapshot = s
|
||||
self.snapshot = snapshot
|
||||
}
|
||||
|
||||
deinit {
|
||||
#if GRDBCUSTOMSQLITE
|
||||
sqlite3_snapshot_free(snapshot)
|
||||
#else
|
||||
// iOS 10.0 is always true because our minimum requirement is iOS 11.
|
||||
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
|
||||
sqlite3_snapshot_free(snapshot)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Compares two WAL snapshots.
|
||||
@@ -70,16 +54,7 @@ final class WALSnapshot {
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot_cmp.html>.
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
#if GRDBCUSTOMSQLITE
|
||||
return sqlite3_snapshot_cmp(snapshot, other.snapshot)
|
||||
#else
|
||||
// iOS 10.0 is always true because our minimum requirement is iOS 11.
|
||||
if #available(macOS 10.12, watchOS 3.0, tvOS 10.0, *) {
|
||||
return sqlite3_snapshot_cmp(snapshot, other.snapshot)
|
||||
} else {
|
||||
preconditionFailure("snapshots are not available")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
#endif // GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT) || compiler(<5.7)
|
||||
#endif // GRDBCIPHER || (GRDBCUSTOMSQLITE && !SQLITE_ENABLE_SNAPSHOT)
|
||||
}
|
||||
+8
-17
@@ -43,32 +43,31 @@ public struct FTS3: VirtualTableModule {
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// FTS3.tokenize("SQLite database") // ["sqlite", "database"]
|
||||
/// FTS3.tokenize("Gustave Doré") // ["gustave", "doré"])
|
||||
/// try FTS3.tokenize("SQLite database") // ["sqlite", "database"]
|
||||
/// try FTS3.tokenize("Gustave Doré") // ["gustave", "doré"])
|
||||
///
|
||||
/// Results can be altered with an explicit tokenizer - default is `.simple`.
|
||||
/// See <https://www.sqlite.org/fts3.html#tokenizer>.
|
||||
///
|
||||
/// FTS3.tokenize("SQLite database", withTokenizer: .porter) // ["sqlite", "databas"]
|
||||
/// FTS3.tokenize("Gustave Doré", withTokenizer: .unicode61()) // ["gustave", "dore"])
|
||||
/// try FTS3.tokenize("SQLite database", withTokenizer: .porter) // ["sqlite", "databas"]
|
||||
/// try FTS3.tokenize("Gustave Doré", withTokenizer: .unicode61()) // ["gustave", "dore"])
|
||||
///
|
||||
/// Tokenization is performed by the `fts3tokenize` virtual table described
|
||||
/// at <https://www.sqlite.org/fts3.html#querying_tokenizers>.
|
||||
public static func tokenize(
|
||||
_ string: String,
|
||||
withTokenizer tokenizer: FTS3TokenizerDescriptor = .simple)
|
||||
-> [String]
|
||||
throws -> [String]
|
||||
{
|
||||
DatabaseQueue().inDatabase { db in
|
||||
try DatabaseQueue().inDatabase { db in
|
||||
var tokenizerChunks: [String] = []
|
||||
tokenizerChunks.append(tokenizer.name)
|
||||
for option in tokenizer.arguments {
|
||||
tokenizerChunks.append("\"\(option)\"")
|
||||
}
|
||||
let tokenizerSQL = tokenizerChunks.joined(separator: ", ")
|
||||
// Assume fts3tokenize virtual table in an in-memory database always succeeds
|
||||
try! db.execute(sql: "CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))")
|
||||
return try! String.fetchAll(db, sql: """
|
||||
try db.execute(sql: "CREATE VIRTUAL TABLE tokens USING fts3tokenize(\(tokenizerSQL))")
|
||||
return try String.fetchAll(db, sql: """
|
||||
SELECT token FROM tokens WHERE input = ? ORDER BY position
|
||||
""", arguments: [string])
|
||||
}
|
||||
@@ -79,14 +78,6 @@ public struct FTS3: VirtualTableModule {
|
||||
/// The virtual table module name
|
||||
public let moduleName = "fts3"
|
||||
|
||||
// TODO: remove when `makeTableDefinition()` is no longer a requirement
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition() -> FTS3TableDefinition {
|
||||
preconditionFailure()
|
||||
}
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
|
||||
@@ -41,8 +41,9 @@ public struct FTS3Pattern {
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS3 pattern
|
||||
public init?(matchingAnyTokenIn string: String) {
|
||||
let tokens = FTS3.tokenize(string, withTokenizer: .simple)
|
||||
guard !tokens.isEmpty else { return nil }
|
||||
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple),
|
||||
!tokens.isEmpty
|
||||
else { return nil }
|
||||
try? self.init(rawPattern: tokens.joined(separator: " OR "))
|
||||
}
|
||||
|
||||
@@ -54,8 +55,9 @@ public struct FTS3Pattern {
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS3 pattern
|
||||
public init?(matchingAllTokensIn string: String) {
|
||||
let tokens = FTS3.tokenize(string, withTokenizer: .simple)
|
||||
guard !tokens.isEmpty else { return nil }
|
||||
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple),
|
||||
!tokens.isEmpty
|
||||
else { return nil }
|
||||
try? self.init(rawPattern: tokens.joined(separator: " "))
|
||||
}
|
||||
|
||||
@@ -67,8 +69,9 @@ public struct FTS3Pattern {
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS3 pattern
|
||||
public init?(matchingAllPrefixesIn string: String) {
|
||||
let tokens = FTS3.tokenize(string, withTokenizer: .simple)
|
||||
guard !tokens.isEmpty else { return nil }
|
||||
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple),
|
||||
!tokens.isEmpty
|
||||
else { return nil }
|
||||
try? self.init(rawPattern: tokens.map { "\($0)*" }.joined(separator: " "))
|
||||
}
|
||||
|
||||
@@ -80,8 +83,9 @@ public struct FTS3Pattern {
|
||||
///
|
||||
/// - parameter string: The string to turn into an FTS3 pattern
|
||||
public init?(matchingPhrase string: String) {
|
||||
let tokens = FTS3.tokenize(string, withTokenizer: .simple)
|
||||
guard !tokens.isEmpty else { return nil }
|
||||
guard let tokens = try? FTS3.tokenize(string, withTokenizer: .simple),
|
||||
!tokens.isEmpty
|
||||
else { return nil }
|
||||
try? self.init(rawPattern: "\"" + tokens.joined(separator: " ") + "\"")
|
||||
}
|
||||
}
|
||||
|
||||
+1
-9
@@ -25,14 +25,6 @@ public struct FTS4: VirtualTableModule {
|
||||
/// The virtual table module name
|
||||
public let moduleName = "fts4"
|
||||
|
||||
// TODO: remove when `makeTableDefinition()` is no longer a requirement
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition() -> FTS4TableDefinition {
|
||||
preconditionFailure()
|
||||
}
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
@@ -296,7 +288,7 @@ public final class FTS4ColumnDefinition {
|
||||
return self
|
||||
}
|
||||
|
||||
/// Uses the column as the Int32 language id hidden column.
|
||||
/// Uses the column as the language id hidden column.
|
||||
///
|
||||
/// try db.create(virtualTable: "document", using: FTS4()) { t in
|
||||
/// t.column("a")
|
||||
|
||||
+4
-12
@@ -76,14 +76,6 @@ public struct FTS5: VirtualTableModule {
|
||||
/// The virtual table module name
|
||||
public let moduleName = "fts5"
|
||||
|
||||
// TODO: remove when `makeTableDefinition()` is no longer a requirement
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
public func makeTableDefinition() -> FTS5TableDefinition {
|
||||
preconditionFailure()
|
||||
}
|
||||
|
||||
/// Reserved; part of the VirtualTableModule protocol.
|
||||
///
|
||||
/// See Database.create(virtualTable:using:)
|
||||
@@ -249,9 +241,9 @@ public struct FTS5: VirtualTableModule {
|
||||
private static func api_v2(
|
||||
_ db: Database,
|
||||
// swiftlint:disable:next line_length
|
||||
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, Int32, UInt32, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> Int32,
|
||||
_ sqlite3_prepare_v3: @convention(c) (OpaquePointer?, UnsafePointer<Int8>?, CInt, CUnsignedInt, UnsafeMutablePointer<OpaquePointer?>?, UnsafeMutablePointer<UnsafePointer<Int8>?>?) -> CInt,
|
||||
// swiftlint:disable:next line_length
|
||||
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, Int32, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> Int32)
|
||||
_ sqlite3_bind_pointer: @convention(c) (OpaquePointer?, CInt, UnsafeMutableRawPointer?, UnsafePointer<Int8>?, (@convention(c) (UnsafeMutableRawPointer?) -> Void)?) -> CInt)
|
||||
-> UnsafePointer<fts5_api>
|
||||
{
|
||||
var statement: SQLiteStatement? = nil
|
||||
@@ -267,10 +259,10 @@ public struct FTS5: VirtualTableModule {
|
||||
_ = sqlite3_bind_pointer(statement, 1, &api, typePointer, nil)
|
||||
}
|
||||
sqlite3_step(statement)
|
||||
guard let result = api else {
|
||||
guard let api else {
|
||||
fatalError("FTS5 is not available")
|
||||
}
|
||||
return result
|
||||
return api
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 322 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user